ZimuPayService.php 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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 ZimuPayService extends BaseService
  8. {
  9. public const CHANNEL_RECHARGE = 'ZIMUpay';
  10. public const CHANNEL_WITHDRAW = 'ZIMUwithdraw';
  11. public const CHANNEL_CASH = 'ZIMUcash';
  12. public const PAY_STATUS_SUCCESS = '3';
  13. public const PAY_STATUS_FAIL = '2';
  14. public const WITHDRAW_STATUS_SUCCESS = '2';
  15. public const WITHDRAW_STATUS_FAIL = '5';
  16. public const CASH_STATUS_SUCCESS = '3';
  17. public const CASH_STATUS_FAIL = '4';
  18. public static function isRechargeChannel(?string $channel): bool
  19. {
  20. return in_array(strtolower((string)$channel), [
  21. strtolower(self::CHANNEL_RECHARGE),
  22. 'zimupay',
  23. '808pay',
  24. '808支付',
  25. ], true);
  26. }
  27. public static function isWithdrawChannel(?string $channel): bool
  28. {
  29. return strtolower((string)$channel) === strtolower(self::CHANNEL_WITHDRAW);
  30. }
  31. public static function isCashChannel(?string $channel): bool
  32. {
  33. return strtolower((string)$channel) === strtolower(self::CHANNEL_CASH);
  34. }
  35. public static function isPayoutChannel(?string $channel): bool
  36. {
  37. return self::isWithdrawChannel($channel) || self::isCashChannel($channel);
  38. }
  39. public static function canUserRecharge($userId): bool
  40. {
  41. $allowedUserIds = array_values(array_filter(array_map(
  42. 'trim',
  43. explode(',', PaymentProviderConfig::get('zimu', 'recharge_user_ids'))
  44. )));
  45. if (empty($allowedUserIds)) {
  46. return true;
  47. }
  48. return in_array((string)$userId, $allowedUserIds, true);
  49. }
  50. public static function amount($amount): string
  51. {
  52. return number_format((float)$amount, 2, '.', '');
  53. }
  54. public static function getAppId(): string
  55. {
  56. return PaymentProviderConfig::get('zimu', 'app_id');
  57. }
  58. public static function getSecret(): string
  59. {
  60. return PaymentProviderConfig::get('zimu', 'key');
  61. }
  62. public static function getPayNotifyUrl(): string
  63. {
  64. return rtrim(config('app.url'), '/') . '/api/pay/harvest';
  65. }
  66. public static function getPayoutNotifyUrl(): string
  67. {
  68. return rtrim(config('app.url'), '/') . '/api/pay/notify';
  69. }
  70. public static function signature(array $params, ?string $key = null): string
  71. {
  72. unset($params['sign']);
  73. $params = array_filter($params, static function ($value) {
  74. return $value !== null && $value !== '';
  75. });
  76. ksort($params, SORT_STRING);
  77. $parts = [];
  78. foreach ($params as $name => $value) {
  79. $parts[] = $name . '=' . $value;
  80. }
  81. $parts[] = 'key=' . ($key ?? self::getSecret());
  82. return strtoupper(md5(implode('&', $parts)));
  83. }
  84. public static function pay($amount, string $orderNo, string $member): array
  85. {
  86. $config = PaymentProviderConfig::snapshot('zimu');
  87. $data = self::signedData([
  88. 'appId' => $config['app_id'],
  89. 'mchOrderNo' => $orderNo,
  90. 'amount' => self::amount($amount),
  91. 'member' => $member,
  92. 'notifyUrl' => self::getPayNotifyUrl(),
  93. 'timestamp' => self::timestamp(),
  94. 'nonce' => self::nonce(),
  95. ], $config['key']);
  96. return self::post($config['pay_gateway'], $data);
  97. }
  98. public static function queryPayOrder(string $orderNo): array
  99. {
  100. $config = PaymentProviderConfig::snapshot('zimu');
  101. return self::post($config['pay_query_gateway'], self::queryData($orderNo, $config));
  102. }
  103. public static function withdraw($amount, string $orderNo, string $member, string $receiveAccount, string $realName = ''): array
  104. {
  105. $config = PaymentProviderConfig::snapshot('zimu');
  106. $data = self::signedData([
  107. 'appId' => $config['app_id'],
  108. 'member' => $member,
  109. 'realName' => $realName,
  110. 'mchOrderNo' => $orderNo,
  111. 'amount' => self::amount($amount),
  112. 'notifyUrl' => self::getPayoutNotifyUrl(),
  113. 'timestamp' => self::timestamp(),
  114. 'nonce' => self::nonce(),
  115. 'receiveAccount' => $receiveAccount,
  116. ], $config['key']);
  117. return self::post($config['withdraw_gateway'], $data);
  118. }
  119. public static function queryWithdrawOrder(string $orderNo): array
  120. {
  121. $config = PaymentProviderConfig::snapshot('zimu');
  122. return self::post($config['withdraw_query_gateway'], self::queryData($orderNo, $config));
  123. }
  124. public static function cash($amount, string $orderNo, string $accountName, string $accountNo, string $bank, string $payMethod = ''): array
  125. {
  126. $config = PaymentProviderConfig::snapshot('zimu');
  127. $data = self::signedData([
  128. 'appId' => $config['app_id'],
  129. 'mchOrderNo' => $orderNo,
  130. 'amount' => self::amount($amount),
  131. 'notifyUrl' => self::getPayoutNotifyUrl(),
  132. 'accountName' => $accountName,
  133. 'accountNo' => $accountNo,
  134. 'bank' => $bank,
  135. 'payMethod' => $payMethod,
  136. 'timestamp' => self::timestamp(),
  137. 'nonce' => self::nonce(),
  138. ], $config['key']);
  139. return self::post($config['cash_gateway'], $data);
  140. }
  141. public static function queryCashOrder(string $orderNo): array
  142. {
  143. $config = PaymentProviderConfig::snapshot('zimu');
  144. return self::post($config['cash_query_gateway'], self::queryData($orderNo, $config));
  145. }
  146. public static function balance(): array
  147. {
  148. $config = PaymentProviderConfig::snapshot('zimu');
  149. $data = self::signedData([
  150. 'appId' => $config['app_id'],
  151. 'timestamp' => self::timestamp(),
  152. 'nonce' => self::nonce(),
  153. ], $config['key']);
  154. return self::post($config['balance_gateway'], $data);
  155. }
  156. public static function verifyNotify(array $params): bool
  157. {
  158. $config = PaymentProviderConfig::snapshot('zimu');
  159. if ($config['app_id'] === '' || ($params['appId'] ?? '') !== $config['app_id'] || empty($params['sign'])) {
  160. return false;
  161. }
  162. return hash_equals(self::signature($params, $config['key']), strtoupper((string)$params['sign']));
  163. }
  164. public static function notifySignatureDiagnostics(array $params): array
  165. {
  166. $fields = $params;
  167. unset($fields['sign']);
  168. return [
  169. 'received_sign' => strtoupper((string)($params['sign'] ?? '')),
  170. 'calculated_sign' => self::signature($params),
  171. 'signing_fields' => array_keys(array_filter($fields, static function ($value) {
  172. return $value !== null && $value !== '';
  173. })),
  174. ];
  175. }
  176. public static function cashPayMethod(string $bankName): string
  177. {
  178. if (str_contains($bankName, '微信')) {
  179. return '2';
  180. }
  181. if (str_contains($bankName, '支付宝')) {
  182. return '3';
  183. }
  184. if (str_contains($bankName, '数字')) {
  185. return '4';
  186. }
  187. return '1';
  188. }
  189. private static function queryData(string $orderNo, array $config): array
  190. {
  191. return self::signedData([
  192. 'appId' => $config['app_id'],
  193. 'mchOrderNo' => $orderNo,
  194. 'timestamp' => self::timestamp(),
  195. 'nonce' => self::nonce(),
  196. ], $config['key']);
  197. }
  198. private static function signedData(array $data, string $key): array
  199. {
  200. $data['sign'] = self::signature($data, $key);
  201. return $data;
  202. }
  203. private static function timestamp(): string
  204. {
  205. return (string)round(microtime(true) * 1000);
  206. }
  207. private static function nonce(): string
  208. {
  209. return substr(str_replace('.', '', uniqid('', true)), 0, 15);
  210. }
  211. private static function post(string $url, array $data): array
  212. {
  213. $logData = $data;
  214. unset($logData['sign']);
  215. Log::info('ZIMU支付接口请求', [
  216. 'url' => $url,
  217. 'app_id' => ($data['appId'] ?? ''),
  218. 'data' => $logData,
  219. ]);
  220. try {
  221. $response = (new Client(['timeout' => 10.0]))->post($url, [
  222. 'json' => $data,
  223. 'headers' => [
  224. 'Accept' => 'application/json',
  225. 'Content-Type' => 'application/json',
  226. ],
  227. ]);
  228. $body = $response->getBody()->getContents();
  229. Log::info('ZIMU支付接口响应', [
  230. 'url' => $url,
  231. 'app_id' => ($data['appId'] ?? ''),
  232. 'http_status' => $response->getStatusCode(),
  233. 'body' => $body,
  234. ]);
  235. return json_decode($body, true) ?: [];
  236. } catch (RequestException $e) {
  237. $response = $e->getResponse();
  238. $body = $response ? $response->getBody()->getContents() : '';
  239. Log::error('ZIMU支付接口请求失败', [
  240. 'url' => $url,
  241. 'app_id' => ($data['appId'] ?? ''),
  242. 'http_status' => $response ? $response->getStatusCode() : null,
  243. 'body' => $body,
  244. 'error' => $e->getMessage(),
  245. ]);
  246. throw $e;
  247. } catch (\Throwable $e) {
  248. Log::error('ZIMU支付接口异常', [
  249. 'url' => $url,
  250. 'app_id' => ($data['appId'] ?? ''),
  251. 'error' => $e->getMessage(),
  252. ]);
  253. throw $e;
  254. }
  255. }
  256. public static function getWhere(array $search = []): array
  257. {
  258. return [];
  259. }
  260. }