NoPayService.php 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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(',', PaymentProviderConfig::get('no', '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 PaymentProviderConfig::get('no', 'deposit_mch_id');
  47. }
  48. public static function getWithdrawMerchantId(): string
  49. {
  50. return PaymentProviderConfig::get('no', '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. $config = PaymentProviderConfig::snapshot('no');
  77. $data = self::signedData([
  78. 'appId' => $config['deposit_mch_id'],
  79. 'merchantMemberNo' => $memberNo,
  80. 'merchantOrderNo' => $orderNo,
  81. 'amount' => self::amount($amount),
  82. 'paymentMethod' => self::paymentMethod($channel),
  83. 'notifyUrl' => self::getDepositNotifyUrl(),
  84. 'timestamp' => time(),
  85. 'version' => 'v1',
  86. ], $config['deposit_key']);
  87. return self::post($config['deposit_gateway'], $data, $config['deposit_mch_id']);
  88. }
  89. public static function queryPayOrder(string $orderNo, string $memberNo): array
  90. {
  91. $config = PaymentProviderConfig::snapshot('no');
  92. $data = self::signedData([
  93. 'appId' => $config['deposit_mch_id'],
  94. 'merchantOrderNo' => $orderNo,
  95. 'merchantMemberNo' => $memberNo,
  96. 'timestamp' => time(),
  97. 'version' => 'v1',
  98. ], $config['deposit_key']);
  99. return self::post($config['deposit_query_gateway'], $data, $config['deposit_mch_id']);
  100. }
  101. public static function withdraw($amount, string $orderNo, string $memberNo, string $accountName, string $qAccount): array
  102. {
  103. $config = PaymentProviderConfig::snapshot('no');
  104. $data = self::signedData([
  105. 'appId' => $config['withdraw_mch_id'],
  106. 'merchantOrderNo' => $orderNo,
  107. 'merchantMemberNo' => $memberNo,
  108. 'amount' => self::amount($amount),
  109. 'accountName' => $accountName,
  110. 'notifyUrl' => self::getWithdrawNotifyUrl(),
  111. 'qAccount' => $qAccount,
  112. 'timestamp' => time(),
  113. 'version' => 'v1',
  114. ], $config['withdraw_key']);
  115. return self::post($config['withdraw_gateway'], $data, $config['withdraw_mch_id']);
  116. }
  117. public static function verifyDepositNotify(array $params): bool
  118. {
  119. $config = PaymentProviderConfig::snapshot('no');
  120. return self::verifyNotify($params, $config['deposit_mch_id'], $config['deposit_key']);
  121. }
  122. public static function verifyWithdrawNotify(array $params): bool
  123. {
  124. $config = PaymentProviderConfig::snapshot('no');
  125. return self::verifyNotify($params, $config['withdraw_mch_id'], $config['withdraw_key']);
  126. }
  127. public static function depositNotifySignatureDiagnostics(array $params): array
  128. {
  129. return self::signatureDiagnostics($params, PaymentProviderConfig::get('no', 'deposit_key'));
  130. }
  131. public static function withdrawNotifySignatureDiagnostics(array $params): array
  132. {
  133. return self::signatureDiagnostics($params, PaymentProviderConfig::get('no', 'withdraw_key'));
  134. }
  135. private static function signedData(array $data, string $key): array
  136. {
  137. $data['sign'] = self::signature($data, $key);
  138. return $data;
  139. }
  140. private static function verifyNotify(array $params, string $merchantId, string $key): bool
  141. {
  142. if ($merchantId === '' || ($params['appId'] ?? '') !== $merchantId || empty($params['sign'])) {
  143. return false;
  144. }
  145. $receivedSign = strtolower((string)$params['sign']);
  146. foreach (self::signatureCandidates($params, $key) as $candidate) {
  147. if (hash_equals($candidate, $receivedSign)) {
  148. return true;
  149. }
  150. }
  151. return false;
  152. }
  153. private static function signatureCandidates(array $params, string $key): array
  154. {
  155. $candidates = [self::signature($params, $key)];
  156. // Some NO environments sign callbacks with the implicit default version
  157. // without including the version field in the callback payload.
  158. if (!isset($params['version'])) {
  159. $params['version'] = 'v1';
  160. $candidates[] = self::signature($params, $key);
  161. }
  162. return array_values(array_unique($candidates));
  163. }
  164. private static function signatureDiagnostics(array $params, string $key): array
  165. {
  166. $fields = $params;
  167. unset($fields['sign']);
  168. return [
  169. 'received_sign' => strtolower((string)($params['sign'] ?? '')),
  170. 'calculated_signs' => self::signatureCandidates($params, $key),
  171. 'signing_fields' => array_keys(array_filter($fields, static function ($value) {
  172. return $value !== null && $value !== '';
  173. })),
  174. ];
  175. }
  176. private static function post(string $url, array $data, string $merchantId): array
  177. {
  178. $logData = $data;
  179. unset($logData['sign'], $logData['password']);
  180. Log::info('NO钱包接口请求', [
  181. 'url' => $url,
  182. 'merchant_id' => $merchantId,
  183. 'data' => $logData,
  184. ]);
  185. try {
  186. $response = (new Client(['timeout' => 10.0]))->post($url, [
  187. 'json' => $data,
  188. 'headers' => [
  189. 'Accept' => 'application/json',
  190. 'appId' => $merchantId,
  191. 'language' => 'zh_CN',
  192. ],
  193. ]);
  194. $body = $response->getBody()->getContents();
  195. Log::info('NO钱包接口响应', [
  196. 'url' => $url,
  197. 'merchant_id' => $merchantId,
  198. 'http_status' => $response->getStatusCode(),
  199. 'body' => $body,
  200. ]);
  201. return json_decode($body, true) ?: [];
  202. } catch (RequestException $e) {
  203. $response = $e->getResponse();
  204. $body = $response ? $response->getBody()->getContents() : '';
  205. Log::error('NO钱包接口请求失败', [
  206. 'url' => $url,
  207. 'merchant_id' => $merchantId,
  208. 'http_status' => $response ? $response->getStatusCode() : null,
  209. 'body' => $body,
  210. 'error' => $e->getMessage(),
  211. ]);
  212. throw $e;
  213. } catch (\Throwable $e) {
  214. Log::error('NO钱包接口异常', [
  215. 'url' => $url,
  216. 'merchant_id' => $merchantId,
  217. 'error' => $e->getMessage(),
  218. ]);
  219. throw $e;
  220. }
  221. }
  222. public static function getWhere(array $search = []): array
  223. {
  224. return [];
  225. }
  226. }