Wechat.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. <?php
  2. namespace addons\shopro\library\pay\provider;
  3. use think\Log;
  4. use think\exception\HttpResponseException;
  5. use Yansongda\Pay\Pay;
  6. class Wechat extends Base
  7. {
  8. protected $payService = null;
  9. protected $platform = null;
  10. public function __construct($payService, $platform = null)
  11. {
  12. $this->payService = $payService;
  13. $this->platform = $platform;
  14. }
  15. public function pay($order, $config = [])
  16. {
  17. $this->init('wechat', $config);
  18. if (isset($this->config['wechat']['default']['mode']) && $this->config['wechat']['default']['mode'] === 2) {
  19. if (in_array($this->platform, ['WechatOfficialAccount', 'WechatMiniProgram'])) {
  20. $order['payer']['sub_openid'] = $order['payer']['openid'] ?? '';
  21. unset($order['payer']['openid']);
  22. }
  23. }
  24. $order['amount']['total'] = intval(bcmul($order['total_amount'], '100')); // 按分 为单位
  25. if ($this->platform == 'H5') {
  26. $order['_type'] = 'app'; // 使用 配置中的 app_id 字段
  27. $order['scene_info'] = [
  28. 'payer_client_ip' => request()->ip(),
  29. 'h5_info' => [
  30. 'type' => 'Wap',
  31. ]
  32. ];
  33. }
  34. unset($order['order_id'], $order['total_amount']);
  35. $method = $this->getMethod('wechat');
  36. $result = Pay::wechat()->$method($order);
  37. return $result;
  38. }
  39. public function transfer($payload, $config = [])
  40. {
  41. $this->init('wechat', $config, 'sub_mch');
  42. $code = 0;
  43. $payload['total_amount'] = intval(bcmul($payload['total_amount'], '100'));
  44. foreach ($payload['transfer_detail_list'] as $key => &$detail) {
  45. $detail['transfer_amount'] = intval(bcmul($detail['transfer_amount'], '100'));
  46. }
  47. if (isset($this->config['wechat']['default']['_type'])) {
  48. // 为了能正常获取 appid
  49. $payload['_type'] = $this->config['wechat']['default']['_type'];
  50. }
  51. // $payload['authorization_type'] = 'INFORMATION_AUTHORIZATION_TYPE';
  52. $payload['authorization_type'] = 'FUND_AUTHORIZATION_TYPE';
  53. // $payload['authorization_type'] = 'INFORMATION_AND_FUND_AUTHORIZATION_TYPE';
  54. $response = Pay::wechat()->transfer($payload);
  55. if (isset($response['batch_id']) && $response['batch_id']) {
  56. $code = 1;
  57. }
  58. return [$code, $response];
  59. }
  60. public function notify($callback, $config = [])
  61. {
  62. $this->init('wechat', $config);
  63. try {
  64. $originData = Pay::wechat()->callback(); // 是的,验签就这么简单!
  65. // {
  66. // "id": "a5c68a7c-5474-5151-825d-88b4143f8642",
  67. // "create_time": "2022-06-20T16:16:12+08:00",
  68. // "resource_type": "encrypt-resource",
  69. // "event_type": "TRANSACTION.SUCCESS",
  70. // "summary": "支付成功",
  71. // "resource": {
  72. // "original_type": "transaction",
  73. // "algorithm": "AEAD_AES_256_GCM",
  74. // "ciphertext": {
  75. // "mchid": "1623831039",
  76. // "appid": "wx43051b2afa4ed3d0",
  77. // "out_trade_no": "P202204155176122100021000",
  78. // "transaction_id": "4200001433202206201698588194",
  79. // "trade_type": "JSAPI",
  80. // "trade_state": "SUCCESS",
  81. // "trade_state_desc": "支付成功",
  82. // "bank_type": "OTHERS",
  83. // "attach": "",
  84. // "success_time": "2022-06-20T16:16:12+08:00",
  85. // "payer": {
  86. // "openid": "oRj5A44G6lgCVENzVMxZtoMfNeww"
  87. // },
  88. // "amount": {
  89. // "total": 1,
  90. // "payer_total": 1,
  91. // "currency": "CNY",
  92. // "payer_currency": "CNY"
  93. // }
  94. // },
  95. // "associated_data": "transaction",
  96. // "nonce": "qoJzoS9MCNgu"
  97. // }
  98. // }
  99. Log::write('pay-notify-origin-data:' . json_encode($originData));
  100. if ($originData['event_type'] == 'TRANSACTION.SUCCESS') {
  101. // 支付成功回调
  102. $data = $originData['resource']['ciphertext'] ?? [];
  103. if (isset($data['trade_state']) && $data['trade_state'] == 'SUCCESS') {
  104. // 交易成功
  105. $data['pay_fee'] = ($data['amount']['total'] / 100);
  106. $data['notify_time'] = date('Y-m-d H:i:s', strtotime((string)$data['success_time']));
  107. $data['buyer_info'] = $data['payer']['openid'] ?? ($data['payer']['sub_openid'] ?? '');
  108. $result = $callback($data, $originData);
  109. return $result;
  110. }
  111. return 'fail';
  112. } else {
  113. // 微信交易未成功,返回 false,让微信再次通知
  114. Log::error('notify-error:交易未成功:' . $originData['event_type']);
  115. return 'fail';
  116. }
  117. } catch (HttpResponseException $e) {
  118. $data = $e->getResponse()->getData();
  119. $message = $data ? ($data['msg'] ?? '') : $e->getMessage();
  120. format_log_error($e, 'wechatNotify.HttpResponseException', $message);
  121. return 'fail';
  122. } catch (\Exception $e) {
  123. format_log_error($e, 'wechatNotify');
  124. return 'fail';
  125. }
  126. }
  127. /**
  128. * 退款
  129. *
  130. * @param array $order_data
  131. * @param array $config
  132. * @return array
  133. */
  134. public function refund($order_data, $config = [])
  135. {
  136. $config['notify_url'] = $config['notify_url'] ?? request()->domain() . '/addons/shopro/pay/notifyRefund/payment/wechat/platform/' . $this->platform;
  137. $order_data['notify_url'] = $config['notify_url'];
  138. $this->init('wechat', $config);
  139. $order_data['amount']['total'] = intval(bcmul($order_data['amount']['total'], '100'));
  140. $order_data['amount']['refund'] = intval(bcmul($order_data['amount']['refund'], '100'));
  141. $result = Pay::wechat()->refund($order_data);
  142. Log::write('pay-refund-origin-data:' . json_encode($result, JSON_UNESCAPED_UNICODE));
  143. // { 返回数据字段
  144. // "amount": {
  145. // "currency": "CNY",
  146. // "discount_refund": 0,
  147. // "from": [],
  148. // "payer_refund": 1,
  149. // "payer_total": 1,
  150. // "refund": 1,
  151. // "settlement_refund": 1,
  152. // "settlement_total": 1,
  153. // "total": 1
  154. // },
  155. // "channel": "ORIGINAL",
  156. // "create_time": "2022-06-20T19:06:36+08:00",
  157. // "funds_account": "AVAILABLE",
  158. // "out_refund_no": "R202207063668479227002100",
  159. // "out_trade_no": "P202205155977315528002100",
  160. // "promotion_detail": [],
  161. // "refund_id": "50301802252022062021833667769",
  162. // "status": "PROCESSING",
  163. // "transaction_id": "4200001521202206207964248014",
  164. // "user_received_account": "\u652f\u4ed8\u7528\u6237\u96f6\u94b1"
  165. // }
  166. return $result;
  167. }
  168. /**
  169. * 微信退款回调
  170. *
  171. * @param array $callback
  172. * @param array $config
  173. * @return array
  174. */
  175. public function notifyRefund($callback, $config = [])
  176. {
  177. $this->init('wechat', $config);
  178. try {
  179. $originData = Pay::wechat()->callback(); // 是的,验签就这么简单!
  180. Log::write('pay-notifyrefund-callback-data:' . json_encode($originData));
  181. // {
  182. // "id": "4a553265-1f28-53a3-9395-8d902b902462",
  183. // "create_time": "2022-06-21T11:25:33+08:00",
  184. // "resource_type": "encrypt-resource",
  185. // "event_type": "REFUND.SUCCESS",
  186. // "summary": "\u9000\u6b3e\u6210\u529f",
  187. // "resource": {
  188. // "original_type": "refund",
  189. // "algorithm": "AEAD_AES_256_GCM",
  190. // "ciphertext": {
  191. // "mchid": "1623831039",
  192. // "out_trade_no": "P202211233042122753002100",
  193. // "transaction_id": "4200001417202206214219765470",
  194. // "out_refund_no": "R202211252676008994002100",
  195. // "refund_id": "50300002272022062121864292533",
  196. // "refund_status": "SUCCESS",
  197. // "success_time": "2022-06-21T11:25:33+08:00",
  198. // "amount": {
  199. // "total": 1,
  200. // "refund": 1,
  201. // "payer_total": 1,
  202. // "payer_refund": 1
  203. // },
  204. // "user_received_account": "\u652f\u4ed8\u7528\u6237\u96f6\u94b1"
  205. // },
  206. // "associated_data": "refund",
  207. // "nonce": "8xfQknYyLVop"
  208. // }
  209. // }
  210. if ($originData['event_type'] == 'REFUND.SUCCESS') {
  211. // 支付成功回调
  212. $data = $originData['resource']['ciphertext'] ?? [];
  213. if (isset($data['refund_status']) && $data['refund_status'] == 'SUCCESS') {
  214. // 退款成功
  215. $result = $callback($data, $originData);
  216. return $result;
  217. }
  218. return 'fail';
  219. } else {
  220. // 微信交易未成功,返回 false,让微信再次通知
  221. Log::error('notify-error:退款未成功:' . $originData['event_type']);
  222. return 'fail';
  223. }
  224. } catch (HttpResponseException $e) {
  225. $data = $e->getResponse()->getData();
  226. $message = $data ? ($data['msg'] ?? '') : $e->getMessage();
  227. format_log_error($e, 'wechatNotifyRefund.HttpResponseException', $message);
  228. return 'fail';
  229. } catch (\Exception $e) {
  230. format_log_error($e, 'wechatNotifyRefund');
  231. return 'fail';
  232. }
  233. }
  234. /**
  235. * 格式化支付参数
  236. *
  237. * @param [type] $params
  238. * @return void
  239. */
  240. protected function formatConfig($config, $data = [], $type = 'normal')
  241. {
  242. if ($config['mode'] == 2 && $type == 'sub_mch') {
  243. // 服务商模式,但需要子商户直连 ,重新定义 config(商家转账到零钱)
  244. $config = [
  245. 'mch_id' => $config['sub_mch_id'],
  246. 'mch_secret_key' => $config['sub_mch_secret_key'],
  247. 'mch_secret_cert' => $config['sub_mch_secret_cert'],
  248. 'mch_public_cert_path' => $config['sub_mch_public_cert_path'],
  249. ];
  250. $config['mode'] = 0; // 临时改为普通商户
  251. }
  252. if ($config['mode'] === 2) {
  253. // 首先将平台配置的 app_id 初始化到配置中
  254. $config['mp_app_id'] = $config['app_id']; // 服务商关联的公众号的 appid
  255. $config['sub_app_id'] = $data['app_id']; // 服务商特约子商户
  256. } else {
  257. $config['app_id'] = $data['app_id'];
  258. }
  259. switch ($this->platform) {
  260. case 'WechatMiniProgram':
  261. $config['_type'] = 'mini'; // 小程序提现,需要传 _type = mini 才能正确获取到 appid
  262. if ($config['mode'] === 2) {
  263. $config['sub_mini_app_id'] = $config['sub_app_id'];
  264. unset($config['sub_app_id']);
  265. } else {
  266. $config['mini_app_id'] = $config['app_id'];
  267. unset($config['app_id']);
  268. }
  269. break;
  270. case 'WechatOfficialAccount':
  271. $config['_type'] = 'mp'; // 小程序提现,需要传 _type = mp 才能正确获取到 appid
  272. if ($config['mode'] === 2) {
  273. $config['sub_mp_app_id'] = $config['sub_app_id'];
  274. unset($config['sub_app_id']);
  275. } else {
  276. $config['mp_app_id'] = $config['app_id'];
  277. unset($config['app_id']);
  278. }
  279. break;
  280. case 'App':
  281. case 'H5':
  282. default:
  283. break;
  284. }
  285. $config['notify_url'] = request()->domain() . '/addons/shopro/pay/notify/payment/wechat/platform/' . $this->platform;
  286. $config['mch_secret_cert'] = ROOT_PATH . 'public' . $config['mch_secret_cert'];
  287. $config['mch_public_cert_path'] = ROOT_PATH . 'public' . $config['mch_public_cert_path'];
  288. return $config;
  289. }
  290. }