WeChatPayService.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  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. //$this->payDesc($from)
  123. $response = $this->app->getClient()->postJson("v3/pay/transactions/jsapi", [
  124. "appid" => $appId,
  125. "mchid" => $this->config['mch_id'],
  126. "description" => $order['desc']??$this->payDesc($from),
  127. "out_trade_no" => $order['pay_sn'],
  128. "notify_url" => $this->config['notify_url'],
  129. "amount" => [
  130. "total" => intval($order['order_amount'] * 100),
  131. ],
  132. "payer" => [
  133. "openid" => $this->auth['openid']
  134. ],
  135. 'attach' => $from
  136. ]);
  137. $result = $response->toArray(false);
  138. $this->checkResultFail($result);
  139. return $this->getPrepayConfig($result['prepay_id'], $appId);
  140. }
  141. /**
  142. * @notes 网站native
  143. * @param $from
  144. * @param $order
  145. * @param $appId
  146. * @return mixed
  147. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  148. * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
  149. * @author 段誉
  150. * @date 2023/2/28 12:12
  151. */
  152. public function nativePay($from, $order, $appId)
  153. {
  154. // $this->payDesc($from)
  155. $response = $this->app->getClient()->postJson('v3/pay/transactions/native', [
  156. 'appid' => $appId,
  157. 'mchid' => $this->config['mch_id'],
  158. 'description' =>$order['desc']??$this->payDesc($from),
  159. 'out_trade_no' => $order['pay_sn'],
  160. 'notify_url' => $this->config['notify_url'],
  161. 'amount' => [
  162. 'total' => intval($order['order_amount'] * 100),
  163. ],
  164. 'attach' => $from
  165. ]);
  166. $result = $response->toArray(false);
  167. $this->checkResultFail($result);
  168. return $result['code_url'];
  169. }
  170. /**
  171. * @notes appPay
  172. * @param $from
  173. * @param $order
  174. * @param $appId
  175. * @return mixed
  176. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  177. * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
  178. * @author 段誉
  179. * @date 2023/2/28 12:12
  180. */
  181. public function appPay($from, $order, $appId)
  182. {
  183. $response = $this->app->getClient()->postJson('v3/pay/transactions/app', [
  184. 'appid' => $appId,
  185. 'mchid' => $this->config['mch_id'],
  186. 'description' => $order['desc']??$this->payDesc($from),
  187. 'out_trade_no' => $order['pay_sn'],
  188. 'notify_url' => $this->config['notify_url'],
  189. 'amount' => [
  190. 'total' => intval($order['order_amount'] * 100),
  191. ],
  192. 'attach' => $from
  193. ]);
  194. $result = $response->toArray(false);
  195. $this->checkResultFail($result);
  196. return $result['prepay_id'];
  197. }
  198. /**
  199. * @notes h5
  200. * @param $from
  201. * @param $order
  202. * @param $appId
  203. * @param $redirectUrl
  204. * @return mixed
  205. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  206. * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
  207. * @author 段誉
  208. * @date 2023/2/28 12:13
  209. */
  210. public function mwebPay($from, $order, $appId)
  211. {
  212. $ip = request()->ip();
  213. if (!empty(env('project.test_web_ip')) && env('APP_DEBUG')) {
  214. $ip = env('project.test_web_ip');
  215. }
  216. //
  217. $response = $this->app->getClient()->postJson('v3/pay/transactions/h5', [
  218. 'appid' => $appId,
  219. 'mchid' => $this->config['mch_id'],
  220. 'description' => $order['desc']??$this->payDesc($from),
  221. 'out_trade_no' => $order['pay_sn'],
  222. 'notify_url' => $this->config['notify_url'],
  223. 'amount' => [
  224. 'total' => intval(strval($order['order_amount'] * 100)),
  225. ],
  226. 'attach' => $from,
  227. 'scene_info' => [
  228. 'payer_client_ip' => $ip,
  229. 'h5_info' => [
  230. 'type' => 'Wap',
  231. ]
  232. ]
  233. ]);
  234. $result = $response->toArray(false);
  235. $this->checkResultFail($result);
  236. $domain = request()->domain();
  237. if (!empty(env('project.test_web_domain')) && env('APP_DEBUG')) {
  238. $domain = env('project.test_web_domain');
  239. }
  240. $redirectUrl = $domain . '/mobile'. $order['redirect_url'] .'?id=' . $order['id'] . '&from='. $from . '&checkPay=true';
  241. return $result['h5_url'] . '&redirect_url=' . urlencode($redirectUrl);
  242. }
  243. /**
  244. * @notes 退款
  245. * @param array $refundData
  246. * @return mixed
  247. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  248. * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
  249. * @author 段誉
  250. * @date 2023/2/28 16:53
  251. */
  252. public function refund(array $refundData)
  253. {
  254. $response = $this->app->getClient()->postJson('v3/refund/domestic/refunds', [
  255. 'transaction_id' => $refundData['transaction_id'],
  256. 'out_refund_no' => $refundData['refund_sn'],
  257. 'amount' => [
  258. 'refund' => intval($refundData['refund_amount'] * 100),
  259. 'total' => intval($refundData['total_amount'] * 100),
  260. 'currency' => 'CNY',
  261. ]
  262. ]);
  263. $result = $response->toArray(false);
  264. $this->checkResultFail($result);
  265. return $result;
  266. }
  267. /**
  268. * @notes 查询退款
  269. * @param $refundSn
  270. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  271. * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
  272. * @author 段誉
  273. * @date 2023/3/1 11:16
  274. */
  275. public function queryRefund($refundSn)
  276. {
  277. $response = $this->app->getClient()->get("v3/refund/domestic/refunds/{$refundSn}");
  278. return $response->toArray(false);
  279. }
  280. /**
  281. * @notes 支付描述
  282. * @param $from
  283. * @return string
  284. * @author 段誉
  285. * @date 2023/2/27 17:54
  286. */
  287. public function payDesc($from)
  288. {
  289. $desc = [
  290. 'order' => '服务',
  291. 'recharge' => '充值',
  292. ];
  293. return $desc[$from] ?? '服务';
  294. }
  295. /**
  296. * @notes 捕获错误
  297. * @param $result
  298. * @throws \Exception
  299. * @author 段誉
  300. * @date 2023/2/28 12:09
  301. */
  302. public function checkResultFail($result)
  303. {
  304. if (!empty($result['code']) || !empty($result['message'])) {
  305. throw new \Exception('微信:'. $result['code'] . '-' . $result['message']);
  306. }
  307. }
  308. /**
  309. * @notes 预支付配置
  310. * @param $prepayId
  311. * @param $appId
  312. * @return mixed[]
  313. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  314. * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
  315. * @author 段誉
  316. * @date 2023/2/28 17:38
  317. */
  318. public function getPrepayConfig($prepayId, $appId)
  319. {
  320. return $this->app->getUtils()->buildBridgeConfig($prepayId, $appId);
  321. }
  322. /**
  323. * @notes 支付回调
  324. * @return \Psr\Http\Message\ResponseInterface
  325. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  326. * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
  327. * @throws \ReflectionException
  328. * @throws \Throwable
  329. * @author 段誉
  330. * @date 2023/2/28 14:20
  331. */
  332. public function notify()
  333. {
  334. $server = $this->app->getServer();
  335. // 支付通知
  336. $server->handlePaid(function (Message $message) {
  337. if ($message['trade_state'] === 'SUCCESS') {
  338. $extra['transaction_id'] = $message['transaction_id'];
  339. $attach = $message['attach'];
  340. $message['out_trade_no'] = mb_substr($message['out_trade_no'], 0, 18);
  341. switch ($attach) {
  342. case 'recharge':
  343. $order = RechargeOrder::where(['sn' => $message['out_trade_no']])->findOrEmpty();
  344. if($order->isEmpty() || $order->pay_status == PayEnum::ISPAID) {
  345. return true;
  346. }
  347. PayNotifyLogic::handle('recharge', $message['out_trade_no'], $extra);
  348. break;
  349. case 'service':
  350. $order = RechargeOrder::where(['sn' => $message['out_trade_no']])->findOrEmpty();
  351. if($order->isEmpty() || $order->pay_status == PayEnum::ISPAID) {
  352. return true;
  353. }
  354. PayNotifyLogic::handle('service', $message['out_trade_no'], $extra);
  355. break;
  356. }
  357. }
  358. return true;
  359. });
  360. // 退款通知
  361. $server->handleRefunded(function (Message $message) {
  362. return true;
  363. });
  364. return $server->serve();
  365. }
  366. }