WeChatPayService.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | likeadmin快速开发前后端分离管理后台(PHP版)
  4. // +----------------------------------------------------------------------
  5. // | 欢迎阅读学习系统程序代码,建议反馈是我们前进的动力
  6. // | 开源版本可自由商用,可去除界面版权logo
  7. // | gitee下载:https://gitee.com/likeshop_gitee/likeadmin
  8. // | github下载:https://github.com/likeshop-github/likeadmin
  9. // | 访问官网:https://www.likeadmin.cn
  10. // | likeadmin团队 版权所有 拥有最终解释权
  11. // +----------------------------------------------------------------------
  12. // | author: likeadminTeam
  13. // +----------------------------------------------------------------------
  14. namespace app\common\service\pay;
  15. use app\common\enum\PayEnum;
  16. use app\common\enum\user\UserTerminalEnum;
  17. use app\common\logic\PayNotifyLogic;
  18. use app\common\model\recharge\RechargeOrder;
  19. use app\common\model\user\UserAuth;
  20. use app\common\service\wechat\WeChatConfigService;
  21. use EasyWeChat\Pay\Application;
  22. use EasyWeChat\Pay\Message;
  23. /**
  24. * 微信支付
  25. * Class WeChatPayService
  26. * @package app\common\server
  27. */
  28. class WeChatPayService extends BasePayService
  29. {
  30. /**
  31. * 授权信息
  32. * @var UserAuth|array|\think\Model
  33. */
  34. protected $auth;
  35. /**
  36. * 微信配置
  37. * @var
  38. */
  39. protected $config;
  40. /**
  41. * easyWeChat实例
  42. * @var
  43. */
  44. protected $app;
  45. /**
  46. * 当前使用客户端
  47. * @var
  48. */
  49. protected $terminal;
  50. /**
  51. * 初始化微信支付配置
  52. * @param $terminal //用户终端
  53. * @param null $userId //用户id(获取授权openid)
  54. */
  55. public function __construct($terminal, $userId = null)
  56. {
  57. $this->terminal = $terminal;
  58. $this->config = WeChatConfigService::getPayConfigByTerminal($terminal);
  59. $this->app = new Application($this->config);
  60. if ($userId !== null) {
  61. $this->auth = UserAuth::where(['user_id' => $userId, 'terminal' => $terminal])->findOrEmpty();
  62. }
  63. }
  64. /**
  65. * @notes 发起微信支付统一下单
  66. * @param $from
  67. * @param $order
  68. * @return array|false|string
  69. * @author 段誉
  70. * @date 2021/8/4 15:05
  71. */
  72. public function pay($from, $order)
  73. {
  74. try {
  75. switch ($this->terminal) {
  76. case UserTerminalEnum::WECHAT_MMP:
  77. $config = WeChatConfigService::getMnpConfig();
  78. $result = $this->jsapiPay($from, $order, $config['app_id']);
  79. break;
  80. case UserTerminalEnum::WECHAT_OA:
  81. $config = WeChatConfigService::getOaConfig();
  82. $result = $this->jsapiPay($from, $order, $config['app_id']);
  83. break;
  84. case UserTerminalEnum::IOS:
  85. case UserTerminalEnum::ANDROID:
  86. $config = WeChatConfigService::getOpConfig();
  87. $result = $this->appPay($from, $order, $config['app_id']);
  88. break;
  89. case UserTerminalEnum::H5:
  90. $config = WeChatConfigService::getOaConfig();
  91. $result = $this->mwebPay($from, $order, $config['app_id']);
  92. break;
  93. case UserTerminalEnum::PC:
  94. $config = WeChatConfigService::getOaConfig();
  95. $result = $this->nativePay($from, $order, $config['app_id']);
  96. break;
  97. default:
  98. throw new \Exception('支付方式错误');
  99. }
  100. return [
  101. 'config' => $result,
  102. 'pay_way' => PayEnum::WECHAT_PAY
  103. ];
  104. } catch (\Exception $e) {
  105. $this->setError($e->getMessage());
  106. return false;
  107. }
  108. }
  109. /**
  110. * @notes jsapiPay
  111. * @param $from
  112. * @param $order
  113. * @param $appId
  114. * @return mixed
  115. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  116. * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
  117. * @author 段誉
  118. * @date 2023/2/28 12:12
  119. */
  120. public function jsapiPay($from, $order, $appId)
  121. {
  122. $response = $this->app->getClient()->postJson("v3/pay/transactions/jsapi", [
  123. "appid" => $appId,
  124. "mchid" => $this->config['mch_id'],
  125. "description" => $this->payDesc($from),
  126. "out_trade_no" => $order['pay_sn'],
  127. "notify_url" => $this->config['notify_url'],
  128. "amount" => [
  129. "total" => intval($order['order_amount'] * 100),
  130. ],
  131. "payer" => [
  132. "openid" => $this->auth['openid']
  133. ],
  134. 'attach' => $from
  135. ]);
  136. $result = $response->toArray(false);
  137. $this->checkResultFail($result);
  138. return $this->getPrepayConfig($result['prepay_id'], $appId);
  139. }
  140. /**
  141. * @notes 网站native
  142. * @param $from
  143. * @param $order
  144. * @param $appId
  145. * @return mixed
  146. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  147. * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
  148. * @author 段誉
  149. * @date 2023/2/28 12:12
  150. */
  151. public function nativePay($from, $order, $appId)
  152. {
  153. $response = $this->app->getClient()->postJson('v3/pay/transactions/native', [
  154. 'appid' => $appId,
  155. 'mchid' => $this->config['mch_id'],
  156. 'description' => $this->payDesc($from),
  157. 'out_trade_no' => $order['pay_sn'],
  158. 'notify_url' => $this->config['notify_url'],
  159. 'amount' => [
  160. 'total' => intval($order['order_amount'] * 100),
  161. ],
  162. 'attach' => $from
  163. ]);
  164. $result = $response->toArray(false);
  165. $this->checkResultFail($result);
  166. return $result['code_url'];
  167. }
  168. /**
  169. * @notes appPay
  170. * @param $from
  171. * @param $order
  172. * @param $appId
  173. * @return mixed
  174. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  175. * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
  176. * @author 段誉
  177. * @date 2023/2/28 12:12
  178. */
  179. public function appPay($from, $order, $appId)
  180. {
  181. $response = $this->app->getClient()->postJson('v3/pay/transactions/app', [
  182. 'appid' => $appId,
  183. 'mchid' => $this->config['mch_id'],
  184. 'description' => $this->payDesc($from),
  185. 'out_trade_no' => $order['pay_sn'],
  186. 'notify_url' => $this->config['notify_url'],
  187. 'amount' => [
  188. 'total' => intval($order['order_amount'] * 100),
  189. ],
  190. 'attach' => $from
  191. ]);
  192. $result = $response->toArray(false);
  193. $this->checkResultFail($result);
  194. return $result['prepay_id'];
  195. }
  196. /**
  197. * @notes h5
  198. * @param $from
  199. * @param $order
  200. * @param $appId
  201. * @param $redirectUrl
  202. * @return mixed
  203. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  204. * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
  205. * @author 段誉
  206. * @date 2023/2/28 12:13
  207. */
  208. public function mwebPay($from, $order, $appId)
  209. {
  210. $ip = request()->ip();
  211. if (!empty(env('project.test_web_ip')) && env('APP_DEBUG')) {
  212. $ip = env('project.test_web_ip');
  213. }
  214. $response = $this->app->getClient()->postJson('v3/pay/transactions/h5', [
  215. 'appid' => $appId,
  216. 'mchid' => $this->config['mch_id'],
  217. 'description' => $this->payDesc($from),
  218. 'out_trade_no' => $order['pay_sn'],
  219. 'notify_url' => $this->config['notify_url'],
  220. 'amount' => [
  221. 'total' => intval(strval($order['order_amount'] * 100)),
  222. ],
  223. 'attach' => $from,
  224. 'scene_info' => [
  225. 'payer_client_ip' => $ip,
  226. 'h5_info' => [
  227. 'type' => 'Wap',
  228. ]
  229. ]
  230. ]);
  231. $result = $response->toArray(false);
  232. $this->checkResultFail($result);
  233. $domain = request()->domain();
  234. if (!empty(env('project.test_web_domain')) && env('APP_DEBUG')) {
  235. $domain = env('project.test_web_domain');
  236. }
  237. $redirectUrl = $domain . '/mobile'. $order['redirect_url'] .'?id=' . $order['id'] . '&from='. $from . '&checkPay=true';
  238. return $result['h5_url'] . '&redirect_url=' . urlencode($redirectUrl);
  239. }
  240. /**
  241. * @notes 退款
  242. * @param array $refundData
  243. * @return mixed
  244. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  245. * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
  246. * @author 段誉
  247. * @date 2023/2/28 16:53
  248. */
  249. public function refund(array $refundData)
  250. {
  251. $response = $this->app->getClient()->postJson('v3/refund/domestic/refunds', [
  252. 'transaction_id' => $refundData['transaction_id'],
  253. 'out_refund_no' => $refundData['refund_sn'],
  254. 'amount' => [
  255. 'refund' => intval($refundData['refund_amount'] * 100),
  256. 'total' => intval($refundData['total_amount'] * 100),
  257. 'currency' => 'CNY',
  258. ]
  259. ]);
  260. $result = $response->toArray(false);
  261. $this->checkResultFail($result);
  262. return $result;
  263. }
  264. /**
  265. * @notes 查询退款
  266. * @param $refundSn
  267. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  268. * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
  269. * @author 段誉
  270. * @date 2023/3/1 11:16
  271. */
  272. public function queryRefund($refundSn)
  273. {
  274. $response = $this->app->getClient()->get("v3/refund/domestic/refunds/{$refundSn}");
  275. return $response->toArray(false);
  276. }
  277. /**
  278. * @notes 支付描述
  279. * @param $from
  280. * @return string
  281. * @author 段誉
  282. * @date 2023/2/27 17:54
  283. */
  284. public function payDesc($from)
  285. {
  286. $desc = [
  287. 'order' => '商品',
  288. 'recharge' => '充值',
  289. ];
  290. return $desc[$from] ?? '商品';
  291. }
  292. /**
  293. * @notes 捕获错误
  294. * @param $result
  295. * @throws \Exception
  296. * @author 段誉
  297. * @date 2023/2/28 12:09
  298. */
  299. public function checkResultFail($result)
  300. {
  301. if (!empty($result['code']) || !empty($result['message'])) {
  302. throw new \Exception('微信:'. $result['code'] . '-' . $result['message']);
  303. }
  304. }
  305. /**
  306. * @notes 预支付配置
  307. * @param $prepayId
  308. * @param $appId
  309. * @return mixed[]
  310. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  311. * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
  312. * @author 段誉
  313. * @date 2023/2/28 17:38
  314. */
  315. public function getPrepayConfig($prepayId, $appId)
  316. {
  317. return $this->app->getUtils()->buildBridgeConfig($prepayId, $appId);
  318. }
  319. /**
  320. * @notes 支付回调
  321. * @return \Psr\Http\Message\ResponseInterface
  322. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  323. * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
  324. * @throws \ReflectionException
  325. * @throws \Throwable
  326. * @author 段誉
  327. * @date 2023/2/28 14:20
  328. */
  329. public function notify()
  330. {
  331. $server = $this->app->getServer();
  332. // 支付通知
  333. $server->handlePaid(function (Message $message) {
  334. if ($message['trade_state'] === 'SUCCESS') {
  335. $extra['transaction_id'] = $message['transaction_id'];
  336. $attach = $message['attach'];
  337. $message['out_trade_no'] = mb_substr($message['out_trade_no'], 0, 18);
  338. switch ($attach) {
  339. case 'recharge':
  340. $order = RechargeOrder::where(['sn' => $message['out_trade_no']])->findOrEmpty();
  341. if($order->isEmpty() || $order->pay_status == PayEnum::ISPAID) {
  342. return true;
  343. }
  344. PayNotifyLogic::handle('recharge', $message['out_trade_no'], $extra);
  345. break;
  346. }
  347. }
  348. return true;
  349. });
  350. // 退款通知
  351. $server->handleRefunded(function (Message $message) {
  352. return true;
  353. });
  354. return $server->serve();
  355. }
  356. }