NoPayService.php 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. <?php
  2. namespace App\Services\Payment;
  3. use App\Services\BaseService;
  4. use GuzzleHttp\Client;
  5. use GuzzleHttp\Exception\RequestException;
  6. use Illuminate\Support\Facades\Log;
  7. class NoPayService extends BaseService
  8. {
  9. public const CHANNEL_SCAN = 'NOpay12';
  10. public const CHANNEL_BALANCE = 'NOpay13';
  11. public const WITHDRAW_CHANNEL = 'NOwithdraw';
  12. public const STATE_SUCCESS = '9';
  13. public const STATE_FAIL = '10';
  14. public static function isRechargeChannel(?string $channel): bool
  15. {
  16. return in_array(strtolower((string)$channel), [
  17. strtolower(self::CHANNEL_SCAN),
  18. strtolower(self::CHANNEL_BALANCE),
  19. ], true);
  20. }
  21. public static function isWithdrawChannel(?string $channel): bool
  22. {
  23. return strtolower((string)$channel) === strtolower(self::WITHDRAW_CHANNEL);
  24. }
  25. public static function canUserRecharge($userId): bool
  26. {
  27. $allowedUserIds = array_values(array_filter(array_map(
  28. 'trim',
  29. explode(',', (string)config('app.no_pay_recharge_user_ids', ''))
  30. )));
  31. if (empty($allowedUserIds)) {
  32. return true;
  33. }
  34. return in_array((string)$userId, $allowedUserIds, true);
  35. }
  36. public static function paymentMethod(string $channel): int
  37. {
  38. return strtolower($channel) === strtolower(self::CHANNEL_BALANCE) ? 13 : 12;
  39. }
  40. public static function amount($amount): string
  41. {
  42. return number_format((float)$amount, 2, '.', '');
  43. }
  44. public static function getDepositMerchantId(): string
  45. {
  46. return (string)config('app.no_pay_deposit_mch_id');
  47. }
  48. public static function getWithdrawMerchantId(): string
  49. {
  50. return (string)config('app.no_pay_withdraw_mch_id');
  51. }
  52. public static function getDepositNotifyUrl(): string
  53. {
  54. return rtrim(config('app.url'), '/') . '/api/pay/harvest';
  55. }
  56. public static function getWithdrawNotifyUrl(): string
  57. {
  58. return rtrim(config('app.url'), '/') . '/api/pay/notify';
  59. }
  60. public static function signature(array $params, string $key): string
  61. {
  62. unset($params['sign']);
  63. $params = array_filter($params, static function ($value) {
  64. return $value !== null && $value !== '';
  65. });
  66. ksort($params, SORT_STRING);
  67. $parts = [];
  68. foreach ($params as $name => $value) {
  69. $parts[] = $name . '=' . $value;
  70. }
  71. $parts[] = 'key=' . $key;
  72. return hash('sha256', implode('&', $parts));
  73. }
  74. public static function pay($amount, string $orderNo, string $memberNo, string $channel): array
  75. {
  76. $data = self::signedData([
  77. 'appId' => self::getDepositMerchantId(),
  78. 'merchantMemberNo' => $memberNo,
  79. 'merchantOrderNo' => $orderNo,
  80. 'amount' => self::amount($amount),
  81. 'paymentMethod' => self::paymentMethod($channel),
  82. 'notifyUrl' => self::getDepositNotifyUrl(),
  83. 'timestamp' => time(),
  84. 'version' => 'v1',
  85. ], (string)config('app.no_pay_deposit_key'));
  86. return self::post((string)config('app.no_pay_deposit_gateway'), $data, self::getDepositMerchantId());
  87. }
  88. public static function queryPayOrder(string $orderNo, string $memberNo): array
  89. {
  90. $data = self::signedData([
  91. 'appId' => self::getDepositMerchantId(),
  92. 'merchantOrderNo' => $orderNo,
  93. 'merchantMemberNo' => $memberNo,
  94. 'timestamp' => time(),
  95. 'version' => 'v1',
  96. ], (string)config('app.no_pay_deposit_key'));
  97. return self::post((string)config('app.no_pay_deposit_query_gateway'), $data, self::getDepositMerchantId());
  98. }
  99. public static function withdraw($amount, string $orderNo, string $memberNo, string $accountName, string $qAccount): array
  100. {
  101. $data = self::signedData([
  102. 'appId' => self::getWithdrawMerchantId(),
  103. 'merchantOrderNo' => $orderNo,
  104. 'merchantMemberNo' => $memberNo,
  105. 'amount' => self::amount($amount),
  106. 'accountName' => $accountName,
  107. 'notifyUrl' => self::getWithdrawNotifyUrl(),
  108. 'qAccount' => $qAccount,
  109. 'timestamp' => time(),
  110. 'version' => 'v1',
  111. ], (string)config('app.no_pay_withdraw_key'));
  112. return self::post((string)config('app.no_pay_withdraw_gateway'), $data, self::getWithdrawMerchantId());
  113. }
  114. public static function verifyDepositNotify(array $params): bool
  115. {
  116. return self::verifyNotify($params, self::getDepositMerchantId(), (string)config('app.no_pay_deposit_key'));
  117. }
  118. public static function verifyWithdrawNotify(array $params): bool
  119. {
  120. return self::verifyNotify($params, self::getWithdrawMerchantId(), (string)config('app.no_pay_withdraw_key'));
  121. }
  122. public static function depositNotifySignatureDiagnostics(array $params): array
  123. {
  124. return self::signatureDiagnostics($params, (string)config('app.no_pay_deposit_key'));
  125. }
  126. public static function withdrawNotifySignatureDiagnostics(array $params): array
  127. {
  128. return self::signatureDiagnostics($params, (string)config('app.no_pay_withdraw_key'));
  129. }
  130. private static function signedData(array $data, string $key): array
  131. {
  132. $data['sign'] = self::signature($data, $key);
  133. return $data;
  134. }
  135. private static function verifyNotify(array $params, string $merchantId, string $key): bool
  136. {
  137. if ($merchantId === '' || ($params['appId'] ?? '') !== $merchantId || empty($params['sign'])) {
  138. return false;
  139. }
  140. $receivedSign = strtolower((string)$params['sign']);
  141. foreach (self::signatureCandidates($params, $key) as $candidate) {
  142. if (hash_equals($candidate, $receivedSign)) {
  143. return true;
  144. }
  145. }
  146. return false;
  147. }
  148. private static function signatureCandidates(array $params, string $key): array
  149. {
  150. $candidates = [self::signature($params, $key)];
  151. // Some NO environments sign callbacks with the implicit default version
  152. // without including the version field in the callback payload.
  153. if (!isset($params['version'])) {
  154. $params['version'] = 'v1';
  155. $candidates[] = self::signature($params, $key);
  156. }
  157. return array_values(array_unique($candidates));
  158. }
  159. private static function signatureDiagnostics(array $params, string $key): array
  160. {
  161. $fields = $params;
  162. unset($fields['sign']);
  163. return [
  164. 'received_sign' => strtolower((string)($params['sign'] ?? '')),
  165. 'calculated_signs' => self::signatureCandidates($params, $key),
  166. 'signing_fields' => array_keys(array_filter($fields, static function ($value) {
  167. return $value !== null && $value !== '';
  168. })),
  169. ];
  170. }
  171. private static function post(string $url, array $data, string $merchantId): array
  172. {
  173. $logData = $data;
  174. unset($logData['sign'], $logData['password']);
  175. Log::info('NO钱包接口请求', [
  176. 'url' => $url,
  177. 'merchant_id' => $merchantId,
  178. 'data' => $logData,
  179. ]);
  180. try {
  181. $response = (new Client(['timeout' => 10.0]))->post($url, [
  182. 'json' => $data,
  183. 'headers' => [
  184. 'Accept' => 'application/json',
  185. 'appId' => $merchantId,
  186. 'language' => 'zh_CN',
  187. ],
  188. ]);
  189. $body = $response->getBody()->getContents();
  190. Log::info('NO钱包接口响应', [
  191. 'url' => $url,
  192. 'merchant_id' => $merchantId,
  193. 'http_status' => $response->getStatusCode(),
  194. 'body' => $body,
  195. ]);
  196. return json_decode($body, true) ?: [];
  197. } catch (RequestException $e) {
  198. $response = $e->getResponse();
  199. $body = $response ? $response->getBody()->getContents() : '';
  200. Log::error('NO钱包接口请求失败', [
  201. 'url' => $url,
  202. 'merchant_id' => $merchantId,
  203. 'http_status' => $response ? $response->getStatusCode() : null,
  204. 'body' => $body,
  205. 'error' => $e->getMessage(),
  206. ]);
  207. throw $e;
  208. } catch (\Throwable $e) {
  209. Log::error('NO钱包接口异常', [
  210. 'url' => $url,
  211. 'merchant_id' => $merchantId,
  212. 'error' => $e->getMessage(),
  213. ]);
  214. throw $e;
  215. }
  216. }
  217. public static function getWhere(array $search = []): array
  218. {
  219. return [];
  220. }
  221. }