WeChatPayService.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  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\model\works\ServiceWork;
  21. use app\common\model\group_activity\GroupUserOrder;
  22. use app\common\service\OnlineCustomerService;
  23. use app\common\service\wechat\WeChatConfigService;
  24. use EasyWeChat\Pay\Application;
  25. use EasyWeChat\Pay\Message;
  26. use think\facade\Log;
  27. /**
  28. * 微信支付
  29. * Class WeChatPayService
  30. * @package app\common\server
  31. */
  32. class WeChatPayService extends BasePayService
  33. {
  34. /**
  35. * 授权信息
  36. * @var UserAuth|array|\think\Model
  37. */
  38. protected $auth;
  39. /**
  40. * 微信配置
  41. * @var
  42. */
  43. protected $config;
  44. /**
  45. * easyWeChat实例
  46. * @var
  47. */
  48. protected $app;
  49. /**
  50. * 当前使用客户端
  51. * @var
  52. */
  53. protected $terminal;
  54. /**
  55. * 初始化微信支付配置
  56. * @param $terminal //用户终端
  57. * @param null $userId //用户id(获取授权openid)
  58. */
  59. public function __construct($terminal, $userId = null)
  60. {
  61. $this->terminal = $terminal;
  62. $this->config = WeChatConfigService::getPayConfigByTerminal($terminal);
  63. $this->app = new Application($this->config);
  64. if ($userId !== null) {
  65. $this->auth = UserAuth::where(['user_id' => $userId, 'terminal' => $terminal])->findOrEmpty();
  66. }
  67. }
  68. /**
  69. * @notes 发起微信支付统一下单
  70. * @param $from
  71. * @param $order
  72. * @return array|false|string
  73. * @author 段誉
  74. * @date 2021/8/4 15:05
  75. */
  76. public function pay($from, $order)
  77. {
  78. try {
  79. switch ($this->terminal) {
  80. case UserTerminalEnum::WECHAT_MMP:
  81. $config = WeChatConfigService::getMnpConfig();
  82. $result = $this->jsapiPay($from, $order, $config['app_id']);
  83. break;
  84. case UserTerminalEnum::WECHAT_OA:
  85. $config = WeChatConfigService::getOaConfig();
  86. $result = $this->jsapiPay($from, $order, $config['app_id']);
  87. break;
  88. case UserTerminalEnum::IOS:
  89. case UserTerminalEnum::ANDROID:
  90. $config = WeChatConfigService::getOpConfig();
  91. $result = $this->appPay($from, $order, $config['app_id']);
  92. break;
  93. case UserTerminalEnum::H5:
  94. $config = WeChatConfigService::getOaConfig();
  95. $result = $this->mwebPay($from, $order, $config['app_id']);
  96. break;
  97. case UserTerminalEnum::PC:
  98. $config = WeChatConfigService::getOaConfig();
  99. $result = $this->nativePay($from, $order, $config['app_id']);
  100. break;
  101. default:
  102. throw new \Exception('支付方式错误');
  103. }
  104. return [
  105. 'config' => $result,
  106. 'pay_way' => PayEnum::WECHAT_PAY
  107. ];
  108. } catch (\Exception $e) {
  109. $this->setError($e->getMessage());
  110. return false;
  111. }
  112. }
  113. /**
  114. * @notes jsapiPay
  115. * @param $from
  116. * @param $order
  117. * @param $appId
  118. * @return mixed
  119. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  120. * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
  121. * @author 段誉
  122. * @date 2023/2/28 12:12
  123. */
  124. public function jsapiPay($from, $order, $appId)
  125. {
  126. $response = $this->app->getClient()->postJson("v3/pay/transactions/jsapi", [
  127. "appid" => $appId,
  128. "mchid" => $this->config['mch_id'],
  129. "description" => $this->payDesc($from),
  130. "out_trade_no" => $order['pay_sn'],
  131. "notify_url" => $this->config['notify_url'],
  132. "amount" => [
  133. "total" => intval($order['order_amount'] * 100),
  134. ],
  135. "payer" => [
  136. "openid" => $this->auth['openid']
  137. ],
  138. 'attach' => $from
  139. ]);
  140. Log::write(json_encode($this->config, JSON_UNESCAPED_UNICODE));
  141. $result = $response->toArray(false);
  142. $this->checkResultFail($result);
  143. return $this->getPrepayConfig($result['prepay_id'], $appId);
  144. }
  145. /**
  146. * @notes 网站native
  147. * @param $from
  148. * @param $order
  149. * @param $appId
  150. * @return mixed
  151. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  152. * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
  153. * @author 段誉
  154. * @date 2023/2/28 12:12
  155. */
  156. public function nativePay($from, $order, $appId)
  157. {
  158. $response = $this->app->getClient()->postJson('v3/pay/transactions/native', [
  159. 'appid' => $appId,
  160. 'mchid' => $this->config['mch_id'],
  161. 'description' => $this->payDesc($from),
  162. 'out_trade_no' => $order['pay_sn'],
  163. 'notify_url' => $this->config['notify_url'],
  164. 'amount' => [
  165. 'total' => intval($order['order_amount'] * 100),
  166. ],
  167. 'attach' => $from
  168. ]);
  169. $result = $response->toArray(false);
  170. $this->checkResultFail($result);
  171. return $result['code_url'];
  172. }
  173. /**
  174. * @notes appPay
  175. * @param $from
  176. * @param $order
  177. * @param $appId
  178. * @return mixed
  179. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  180. * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
  181. * @author 段誉
  182. * @date 2023/2/28 12:12
  183. */
  184. public function appPay($from, $order, $appId)
  185. {
  186. $response = $this->app->getClient()->postJson('v3/pay/transactions/app', [
  187. 'appid' => $appId,
  188. 'mchid' => $this->config['mch_id'],
  189. 'description' => $this->payDesc($from),
  190. 'out_trade_no' => $order['pay_sn'],
  191. 'notify_url' => $this->config['notify_url'],
  192. 'amount' => [
  193. 'total' => intval($order['order_amount'] * 100),
  194. ],
  195. 'attach' => $from
  196. ]);
  197. $result = $response->toArray(false);
  198. $this->checkResultFail($result);
  199. return $result['prepay_id'];
  200. }
  201. /**
  202. * @notes h5
  203. * @param $from
  204. * @param $order
  205. * @param $appId
  206. * @param $redirectUrl
  207. * @return mixed
  208. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  209. * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
  210. * @author 段誉
  211. * @date 2023/2/28 12:13
  212. */
  213. public function mwebPay($from, $order, $appId)
  214. {
  215. $ip = request()->ip();
  216. if (!empty(env('project.test_web_ip')) && env('APP_DEBUG')) {
  217. $ip = env('project.test_web_ip');
  218. }
  219. $response = $this->app->getClient()->postJson('v3/pay/transactions/h5', [
  220. 'appid' => $appId,
  221. 'mchid' => $this->config['mch_id'],
  222. 'description' => $this->payDesc($from),
  223. 'out_trade_no' => $order['pay_sn'],
  224. 'notify_url' => $this->config['notify_url'],
  225. 'amount' => [
  226. 'total' => intval(strval($order['order_amount'] * 100)),
  227. ],
  228. 'attach' => $from,
  229. 'scene_info' => [
  230. 'payer_client_ip' => $ip,
  231. 'h5_info' => [
  232. 'type' => 'Wap',
  233. ]
  234. ]
  235. ]);
  236. $result = $response->toArray(false);
  237. $this->checkResultFail($result);
  238. $domain = request()->domain();
  239. if (!empty(env('project.test_web_domain')) && env('APP_DEBUG')) {
  240. $domain = env('project.test_web_domain');
  241. }
  242. $redirectUrl = $domain . '/mobile'. $order['redirect_url'] .'?id=' . $order['id'] . '&from='. $from . '&checkPay=true';
  243. return $result['h5_url'] . '&redirect_url=' . urlencode($redirectUrl);
  244. }
  245. /**
  246. * @notes 退款
  247. * @param array $refundData
  248. * @return mixed
  249. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  250. * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
  251. * @author 段誉
  252. * @date 2023/2/28 16:53
  253. */
  254. public function refund(array $refundData)
  255. {
  256. $response = $this->app->getClient()->postJson('v3/refund/domestic/refunds', [
  257. 'transaction_id' => $refundData['transaction_id'],
  258. 'out_refund_no' => $refundData['refund_sn'],
  259. 'amount' => [
  260. 'refund' => intval($refundData['refund_amount'] * 100),
  261. 'total' => intval($refundData['total_amount'] * 100),
  262. 'currency' => 'CNY',
  263. ]
  264. ]);
  265. $result = $response->toArray(false);
  266. $this->checkResultFail($result);
  267. return $result;
  268. }
  269. /**
  270. * @notes 查询退款
  271. * @param $refundSn
  272. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  273. * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
  274. * @author 段誉
  275. * @date 2023/3/1 11:16
  276. */
  277. public function queryRefund($refundSn)
  278. {
  279. $response = $this->app->getClient()->get("v3/refund/domestic/refunds/{$refundSn}");
  280. return $response->toArray(false);
  281. }
  282. /**
  283. * @notes 支付描述
  284. * @param $from
  285. * @return string
  286. * @author 段誉
  287. * @date 2023/2/27 17:54
  288. */
  289. public function payDesc($from)
  290. {
  291. $desc = [
  292. 'goods' => '商品',
  293. 'recharge' => '充值',
  294. ];
  295. return $desc[$from] ?? '商品';
  296. }
  297. /**
  298. * @notes 捕获错误
  299. * @param $result
  300. * @throws \Exception
  301. * @author 段誉
  302. * @date 2023/2/28 12:09
  303. */
  304. public function checkResultFail($result)
  305. {
  306. if (!empty($result['code']) || !empty($result['message'])) {
  307. throw new \Exception('微信:'. $result['code'] . '-' . $result['message']);
  308. }
  309. }
  310. /**
  311. * @notes 预支付配置
  312. * @param $prepayId
  313. * @param $appId
  314. * @return mixed[]
  315. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  316. * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
  317. * @author 段誉
  318. * @date 2023/2/28 17:38
  319. */
  320. public function getPrepayConfig($prepayId, $appId)
  321. {
  322. return $this->app->getUtils()->buildBridgeConfig($prepayId, $appId);
  323. }
  324. /**
  325. * @notes 支付回调
  326. * @return \Psr\Http\Message\ResponseInterface
  327. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  328. * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
  329. * @throws \ReflectionException
  330. * @throws \Throwable
  331. * @author 段誉
  332. * @date 2023/2/28 14:20
  333. */
  334. public function notify()
  335. {
  336. $server = $this->app->getServer();
  337. // 支付通知
  338. $server->handlePaid(function (Message $message) {
  339. if ($message['trade_state'] === 'SUCCESS') {
  340. $extra['transaction_id'] = $message['transaction_id'];
  341. $attach = $message['attach'];
  342. $message['out_trade_no'] = mb_substr($message['out_trade_no'], 0, 18);
  343. switch ($attach) {
  344. case 'recharge':
  345. $order = RechargeOrder::where(['sn' => $message['out_trade_no']])->findOrEmpty();
  346. if($order->isEmpty() || $order->pay_status == PayEnum::ISPAID) {
  347. return true;
  348. }
  349. PayNotifyLogic::handle('recharge', $message['out_trade_no'], $extra);
  350. break;
  351. case 'goods':
  352. $order = RechargeOrder::where(['sn' => $message['out_trade_no']])->findOrEmpty();
  353. if($order->isEmpty() || $order->pay_status == PayEnum::ISPAID) {
  354. return true;
  355. }
  356. $res = PayNotifyLogic::handle('goods', $message['out_trade_no'], $extra);
  357. if($res === true){
  358. // 用户下单后,给订单运营专员(配置固定ID)发送公众号提醒(订单信息)
  359. $order = RechargeOrder::where('sn', $message['out_trade_no'])
  360. ->where('payment_type','IN',[0,1])
  361. ->where('pay_status','=',1)
  362. ->findOrEmpty();
  363. if(!$order->isEmpty()){
  364. $workDetail = ServiceWork::findOrEmpty($order->work_id);
  365. if(!$workDetail->isEmpty()){
  366. event('Notice', [
  367. 'scene_id' => 100,
  368. 'params' => [
  369. 'user_id' => 0,
  370. 'order_id' => $workDetail['id'],
  371. 'thing3' => $workDetail['title'],
  372. 'time6' => $workDetail['appointment_time'],
  373. 'phone_number8' => asteriskString($workDetail['mobile']),
  374. 'thing5' => (iconv_strlen($workDetail['address'])>15)?(mb_substr($workDetail['address'],0,15,'UTF-8').'...'):$workDetail['address'],
  375. ]
  376. ]);
  377. // 分配客服派单
  378. OnlineCustomerService::serviceWorkMessage($workDetail['id']);
  379. }
  380. }
  381. // 订单完成通知【给用户】 - 尾款 -通知
  382. $order = RechargeOrder::where('sn', $message['out_trade_no'])
  383. ->where('payment_type','=',2)
  384. ->where('pay_status','=',1)
  385. ->findOrEmpty();
  386. if(!$order->isEmpty()){
  387. event('Notice', [
  388. 'scene_id' => 120,
  389. 'params' => [
  390. 'user_id' => $order['user_id']
  391. ]
  392. ]);
  393. }
  394. }
  395. break;
  396. case 'group':
  397. $order = GroupUserOrder::where(['sn' => $message['out_trade_no']])->findOrEmpty();
  398. if($order->isEmpty() || $order->pay_status == PayEnum::ISPAID) {
  399. return true;
  400. }
  401. PayNotifyLogic::handle('group', $message['out_trade_no'], $extra);
  402. break;
  403. }
  404. }
  405. return true;
  406. });
  407. // 退款通知
  408. $server->handleRefunded(function (Message $message) {
  409. return true;
  410. });
  411. return $server->serve();
  412. }
  413. }