WechatPay.php 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. <?php namespace App\Http\Controllers\Api;
  2. use App\Http\Controllers\Api\Api;
  3. use App\Models\Custom;
  4. use App\Models\Orders;
  5. use App\Facades\Servers\Logs\Log;
  6. use EasyWeChat\Factory;
  7. use Illuminate\Http\Request;
  8. use App\Servers\WechatPay\Payment;
  9. use App\Facades\Servers\WechatMini\Mini;
  10. use WeChatPay\Formatter;
  11. use WeChatPay\Crypto\AesGcm;
  12. use WeChatPay\Crypto\Rsa;
  13. /**
  14. * 微信支付接口
  15. *
  16. * @author JUN
  17. *
  18. * */
  19. class WechatPay extends Api{
  20. /**
  21. * 小程序微信支付下单 /api/wechat_pay/pay
  22. *
  23. * */
  24. public function pay(Custom $Custom)
  25. {
  26. // 检查登录
  27. $uid = $this->checkLogin();
  28. $code = request('code','');
  29. $orderId = request('order_id','');
  30. $orderInfo = Orders::query()->where('id','=',$orderId)->first()->toArray();
  31. if (empty($orderInfo))
  32. return json_send(['code'=>'error','msg'=>'订单不存在','data'=>['id'=>null]]);
  33. if ($orderInfo['custom_uid'] != $uid)
  34. return json_send(['code'=>'error','msg'=>'无权操作','data'=>['id'=>null]]);
  35. if ($orderInfo['status'] != 1)
  36. return json_send(['code'=>'error','msg'=>'订单已支付或取消','data'=>['id'=>null]]);
  37. //获取openid
  38. $result = Mini::jscode2session($code);
  39. if (!$result['openid']) return json_send(['code'=>'error','msg'=>'获取openid失败','data'=>$result['error']]);
  40. $openid = $result['openid'];
  41. $payment = new Payment();
  42. return $payment->pay(['out_trade_no' => $orderInfo['snowflake_id'],'openid' => $openid,'description' => '开邻智教课程','total_price' => $orderInfo['pay_total']]);
  43. }
  44. /**
  45. * 小程序微信支付回调 /api/wechat_pay/notify
  46. *
  47. * */
  48. public function notify(Custom $Custom)
  49. {
  50. $content = file_get_contents("php://input");
  51. if (!empty($content)) {
  52. //直接json字符串
  53. $params = $content;
  54. } elseif (!empty($_POST)) {
  55. //直接POST数据
  56. $params = $_POST;
  57. } else {
  58. $params = [];
  59. }
  60. $post_data = $params;
  61. Log::log('notify_wechat_pay', 'post_data:' . $post_data);
  62. //获取headers参数
  63. $headers = request()->header();
  64. Log::log('notify_wechat_pay', '微信支付回调返回headers参数:' . json_encode($headers));
  65. $inWechatpaySignature = $headers['wechatpay-signature'][0];
  66. $inWechatpayTimestamp = $headers['wechatpay-timestamp'][0];
  67. $inWechatpaySerial = $headers['wechatpay-serial'][0];
  68. $inWechatpayNonce = $headers['wechatpay-nonce'][0];
  69. $inBody = $post_data;
  70. Log::log('notify_wechat_pay', 'wechatpay-timestamp:' . $inWechatpayTimestamp);
  71. $apiv3Key = Config('wechatpay.APIV3');// 在商户平台上设置的APIv3密钥
  72. // 根据通知的平台证书序列号,查询本地平台证书文件,
  73. $platformCertificateFilePath = Config('wechatpay.platformCertificate');
  74. $platformPublicKeyInstance = Rsa::from($platformCertificateFilePath, Rsa::KEY_TYPE_PUBLIC);
  75. try {
  76. // 检查通知时间偏移量,允许5分钟之内的偏移
  77. $timeOffsetStatus = 300 >= abs(Formatter::timestamp() - (int)$inWechatpayTimestamp);
  78. Log::log('notify_wechat_pay', '时间偏移量:' . $timeOffsetStatus);
  79. $verifiedStatus = Rsa::verify(
  80. // 构造验签名串
  81. Formatter::joinedByLineFeed($inWechatpayTimestamp, $inWechatpayNonce, $inBody),
  82. $inWechatpaySignature,
  83. $platformPublicKeyInstance
  84. );
  85. }catch (\Exception $e){
  86. Log::log('notify_wechat_pay', '错误getMessage:' . $e->getMessage());
  87. }
  88. Log::log('notify_wechat_pay', '验签:' . $verifiedStatus.'验签inWechatpayTimestamp:' . $inWechatpayTimestamp.'验签verifiedStatus:' . $inWechatpayNonce);
  89. if ($timeOffsetStatus && $verifiedStatus) {
  90. // 转换通知的JSON文本消息为PHP Array数组
  91. $inBodyArray = (array)json_decode($inBody, true);
  92. // 使用PHP7的数据解构语法,从Array中解构并赋值变量
  93. ['resource' => [
  94. 'ciphertext' => $ciphertext,
  95. 'nonce' => $nonce,
  96. 'associated_data' => $aad
  97. ]] = $inBodyArray;
  98. // 加密文本消息解密
  99. $inBodyResource = AesGcm::decrypt($ciphertext, $apiv3Key, $nonce, $aad);
  100. // 把解密后的文本转换为PHP Array数组
  101. $inBodyResourceArray = (array)json_decode($inBodyResource, true);
  102. Log::log('notify_wechat_pay', '打印解密后的结果:' . json_encode($inBodyResourceArray));
  103. Log::log('notify_wechat_pay', '参数:' . $inBodyResourceArray['trade_state'] . '订单号' . $inBodyResourceArray['out_trade_no'] . '微信支付号' . $inBodyResourceArray['transaction_id']);
  104. if ($inBodyResourceArray['trade_state'] == "SUCCESS") {
  105. Log::log('notify_wechat_pay', '通知订单');
  106. //更新订单支付状态
  107. $orderData = [
  108. 'pay_time' => time(),
  109. 'transaction_id'=>$inBodyResourceArray['transaction_id'],
  110. 'status'=>2,
  111. ];
  112. try {
  113. $res = Orders::query()->where('snowflake_id','=',$inBodyResourceArray['out_trade_no'])->update($orderData);
  114. if (!$res) {
  115. Log::log('notify_wechat_pay', '更新订单失败' . json_encode($res));
  116. return json_send(['code'=>'FAIL']);
  117. }
  118. }catch (\Exception $e){
  119. Log::log('notify_wechat_pay', '更新订单失败' . json_encode($e));
  120. return json_send(['code'=>'FAIL']);
  121. }
  122. Log::log('notify_wechat_pay', '支付回调完成 通知返回' . json_encode($res));
  123. return json_send(['code'=>'SUCCESS']);
  124. }
  125. return json_send(['code'=>'SUCCESS']);
  126. }else{
  127. return json_send(['code'=>'FAIL']);
  128. }
  129. }
  130. }