WeChatPayService.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  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\service\wechat\WeChatConfigService;
  22. use EasyWeChat\Pay\Application;
  23. use EasyWeChat\Pay\Message;
  24. use think\facade\Log;
  25. /**
  26. * 微信支付
  27. * Class WeChatPayService
  28. * @package app\common\server
  29. */
  30. class WeChatPayService extends BasePayService
  31. {
  32. /**
  33. * 授权信息
  34. * @var UserAuth|array|\think\Model
  35. */
  36. protected $auth;
  37. /**
  38. * 微信配置
  39. * @var
  40. */
  41. protected $config;
  42. /**
  43. * easyWeChat实例
  44. * @var
  45. */
  46. protected $app;
  47. /**
  48. * 当前使用客户端
  49. * @var
  50. */
  51. protected $terminal;
  52. /**
  53. * 初始化微信支付配置
  54. * @param $terminal //用户终端
  55. * @param null $userId //用户id(获取授权openid)
  56. */
  57. public function __construct($terminal, $userId = null)
  58. {
  59. $this->terminal = $terminal;
  60. $this->config = WeChatConfigService::getPayConfigByTerminal($terminal);
  61. $this->app = new Application($this->config);
  62. if ($userId !== null) {
  63. $this->auth = UserAuth::where(['user_id' => $userId, 'terminal' => $terminal])->findOrEmpty();
  64. }
  65. }
  66. /**
  67. * @notes 发起微信支付统一下单
  68. * @param $from
  69. * @param $order
  70. * @return array|false|string
  71. * @author 段誉
  72. * @date 2021/8/4 15:05
  73. */
  74. public function pay($from, $order)
  75. {
  76. try {
  77. switch ($this->terminal) {
  78. case UserTerminalEnum::WECHAT_MMP:
  79. $config = WeChatConfigService::getMnpConfig();
  80. $result = $this->jsapiPay($from, $order, $config['app_id']);
  81. break;
  82. case UserTerminalEnum::WECHAT_OA:
  83. $config = WeChatConfigService::getOaConfig();
  84. $result = $this->jsapiPay($from, $order, $config['app_id']);
  85. break;
  86. case UserTerminalEnum::IOS:
  87. case UserTerminalEnum::ANDROID:
  88. $config = WeChatConfigService::getOpConfig();
  89. $result = $this->appPay($from, $order, $config['app_id']);
  90. break;
  91. case UserTerminalEnum::H5:
  92. $config = WeChatConfigService::getOaConfig();
  93. $result = $this->mwebPay($from, $order, $config['app_id']);
  94. break;
  95. case UserTerminalEnum::PC:
  96. $config = WeChatConfigService::getOaConfig();
  97. $result = $this->nativePay($from, $order, $config['app_id']);
  98. break;
  99. default:
  100. throw new \Exception('支付方式错误');
  101. }
  102. return [
  103. 'config' => $result,
  104. 'pay_way' => PayEnum::WECHAT_PAY
  105. ];
  106. } catch (\Exception $e) {
  107. $this->setError($e->getMessage());
  108. return false;
  109. }
  110. }
  111. /**
  112. * @notes jsapiPay
  113. * @param $from
  114. * @param $order
  115. * @param $appId
  116. * @return mixed
  117. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  118. * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
  119. * @author 段誉
  120. * @date 2023/2/28 12:12
  121. */
  122. public function jsapiPay($from, $order, $appId)
  123. {
  124. $response = $this->app->getClient()->postJson("v3/pay/transactions/jsapi", [
  125. "appid" => $appId,
  126. "mchid" => $this->config['mch_id'],
  127. "description" => $this->payDesc($from),
  128. "out_trade_no" => $order['pay_sn'],
  129. "notify_url" => $this->config['notify_url'],
  130. "amount" => [
  131. "total" => intval($order['order_amount'] * 100),
  132. ],
  133. "payer" => [
  134. "openid" => $this->auth['openid']
  135. ],
  136. 'attach' => $from
  137. ]);
  138. Log::write(json_encode($this->config, JSON_UNESCAPED_UNICODE));
  139. $result = $response->toArray(false);
  140. $this->checkResultFail($result);
  141. return $this->getPrepayConfig($result['prepay_id'], $appId);
  142. }
  143. /**
  144. * @notes 网站native
  145. * @param $from
  146. * @param $order
  147. * @param $appId
  148. * @return mixed
  149. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  150. * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
  151. * @author 段誉
  152. * @date 2023/2/28 12:12
  153. */
  154. public function nativePay($from, $order, $appId)
  155. {
  156. $response = $this->app->getClient()->postJson('v3/pay/transactions/native', [
  157. 'appid' => $appId,
  158. 'mchid' => $this->config['mch_id'],
  159. 'description' => $this->payDesc($from),
  160. 'out_trade_no' => $order['pay_sn'],
  161. 'notify_url' => $this->config['notify_url'],
  162. 'amount' => [
  163. 'total' => intval($order['order_amount'] * 100),
  164. ],
  165. 'attach' => $from
  166. ]);
  167. $result = $response->toArray(false);
  168. $this->checkResultFail($result);
  169. return $result['code_url'];
  170. }
  171. /**
  172. * @notes appPay
  173. * @param $from
  174. * @param $order
  175. * @param $appId
  176. * @return mixed
  177. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  178. * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
  179. * @author 段誉
  180. * @date 2023/2/28 12:12
  181. */
  182. public function appPay($from, $order, $appId)
  183. {
  184. $response = $this->app->getClient()->postJson('v3/pay/transactions/app', [
  185. 'appid' => $appId,
  186. 'mchid' => $this->config['mch_id'],
  187. 'description' => $this->payDesc($from),
  188. 'out_trade_no' => $order['pay_sn'],
  189. 'notify_url' => $this->config['notify_url'],
  190. 'amount' => [
  191. 'total' => intval($order['order_amount'] * 100),
  192. ],
  193. 'attach' => $from
  194. ]);
  195. $result = $response->toArray(false);
  196. $this->checkResultFail($result);
  197. return $result['prepay_id'];
  198. }
  199. /**
  200. * @notes h5
  201. * @param $from
  202. * @param $order
  203. * @param $appId
  204. * @param $redirectUrl
  205. * @return mixed
  206. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  207. * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
  208. * @author 段誉
  209. * @date 2023/2/28 12:13
  210. */
  211. public function mwebPay($from, $order, $appId)
  212. {
  213. $ip = request()->ip();
  214. if (!empty(env('project.test_web_ip')) && env('APP_DEBUG')) {
  215. $ip = env('project.test_web_ip');
  216. }
  217. $response = $this->app->getClient()->postJson('v3/pay/transactions/h5', [
  218. 'appid' => $appId,
  219. 'mchid' => $this->config['mch_id'],
  220. 'description' => $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. 'goods' => '商品',
  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. $order = RechargeOrder::where(['sn' => $message['out_trade_no']])->findOrEmpty();
  342. if($order->isEmpty() || $order->pay_status == PayEnum::ISPAID) {
  343. return true;
  344. }
  345. switch ($attach) {
  346. case 'recharge':
  347. PayNotifyLogic::handle('recharge', $message['out_trade_no'], $extra);
  348. break;
  349. case 'goods':
  350. $res = PayNotifyLogic::handle('goods', $message['out_trade_no'], $extra);
  351. if($res === true){
  352. // 用户下单后,给订单运营专员(配置固定ID)发送公众号提醒(订单信息)
  353. $order = RechargeOrder::where('sn', $message['out_trade_no'])
  354. ->where('payment_type','IN',[0,1])
  355. ->where('pay_status','=',1)
  356. ->findOrEmpty();
  357. if(!$order->isEmpty()){
  358. $workDetail = ServiceWork::findOrEmpty($order->work_id);
  359. if(!$workDetail->isEmpty()){
  360. event('Notice', [
  361. 'scene_id' => 100,
  362. 'params' => [
  363. 'user_id' => 0,
  364. 'thing3' => $workDetail['title'],
  365. 'time6' => $workDetail['appointment_time'],
  366. 'phone_number8' => $workDetail['mobile'],
  367. ]
  368. ]);
  369. }
  370. }
  371. }
  372. break;
  373. }
  374. }
  375. return true;
  376. });
  377. // 退款通知
  378. $server->handleRefunded(function (Message $message) {
  379. return true;
  380. });
  381. return $server->serve();
  382. }
  383. }