当前位置:首页 > CMS教程 > Thinkphp > 列表

PHP小程序支付功能完整版【基于thinkPHP】

发布:smiling 来源: PHP粉丝网  添加日期:2021-11-14 11:52:01 浏览: 评论:0 

这篇文章主要介绍了PHP小程序支付功能,结合实例形式分析了基于thinkPHP框架实现微信支付功能的原理、操作步骤及注意事项,需要的朋友可以参考下。

本文实例讲述了PHP小程序支付功能,分享给大家供大家参考,具体如下:

环境: tp3.2  + 小程序 微信支付功能开通

Step1:  下载PHP 支付SDK(下载地址)  放到Library\Vendor下,取名Wxpay

修改WxPay.Config.php 里的appid appsecret key MCHID

Step2: 小程序 js 代码:

  1. var url = getApp().globalData.httpServer + 'api/buy/pay'; 
  2. var userId = getApp().globalData.userId; 
  3. var totalMoney = this.data.totalMoney; 
  4. var cart = this.data.goods; 
  5. var param = { 
  6.   cart: JSON.stringify(cart), 
  7.   cartamount: totalMoney, 
  8.   userid: userId, 
  9.   payment: this.data.payment, 
  10.   addressid: defaultAddress.id 
  11. }; 
  12. var that = this; 
  13. util.http(url, param, function (ret) { 
  14.   if (ret.data.code == 1) { 
  15.     if (that.data.payment == 'balance') { // 余额支付 
  16.       that.afterPaySuccess(ret.data.data); 
  17.     } else {                // 微信支付 
  18.       wx.requestPayment({ 
  19.         timeStamp: ret.data.data.timeStamp, 
  20.         nonceStr: ret.data.data.nonceStr, 
  21.         package: ret.data.data.package, 
  22.         signType: ret.data.data.signType, 
  23.         paySign: ret.data.data.paySign, 
  24.         'success': function (res) { 
  25.           that.afterPaySuccess(ret.data.data.orderid); 
  26.         }, 
  27.         'fail': function (res) { 
  28.           console.log(res); 
  29.         } 
  30.       }) 
  31.     } 
  32.   } else { 
  33.     util.showTip(ret.data.msg, '提交订单失败'); 
  34.   } 
  35. }); 
  36. /** 
  37.  * 网络请求 
  38.  */ 
  39. function http(url, params, callback) { 
  40.   wx.request({ 
  41.     url: url, 
  42.     data: params, 
  43.     success: function (res) { 
  44.       callback(res); 
  45.     }, 
  46.     fail: function (err) { 
  47.       console.log(err); 
  48.     } 
  49.   }); 
  50. } 

Step3: 接口代码:

  1. public function pay() 
  2. { 
  3.     $cart = I('cart', '', 'trim'); 
  4.     $cartAmount = I('cartamount'); 
  5.     $addressId = I('addressid', 0, 'intval'); 
  6.     $payment = I('payment', '', 'trim'); 
  7.     $userId = $this->userid; 
  8.     $cart = json_decode($cart, true); 
  9.     if (emptyempty($cart)) { 
  10.       $result['msg'] = '购物车获取失败'; 
  11.       $result['code'] = 0; 
  12.       $this->ajaxReturn($result); 
  13.     } 
  14.     $totalMoney = 0; 
  15.     foreach ($cart as $goods) { 
  16.       $money = $goods['price'];  // price 
  17.       $selectCount = $goods['selectcount'];  // price 
  18.       $itemAmount = number_format($money * $selectCount, 2, '.', ''); 
  19.       $totalMoney += $itemAmount; 
  20.     } 
  21.     // 检查总金额是否一致 
  22.     if ($totalMoney != $cartAmount) { 
  23.       $result['msg'] = '总金额不匹配:' . $totalMoney; 
  24.       $result['code'] = 0; 
  25.       $this->ajaxReturn($result); 
  26.     } 
  27.     // 获取用户地址 
  28.     $address = M('MemberAddress')->where('userid=' . $userId . " and id=" . $addressId)->find(); 
  29.     if (emptyempty($address)) { 
  30.       $result['msg'] = '用户地址不存在'; 
  31.       $result['code'] = 0; 
  32.       $this->ajaxReturn($result); 
  33.     } 
  34.     // 用户信息 
  35.     $user = M('Member')->where("id=" . $userId)->find(); 
  36.     if ($payment == 'balance') { 
  37.       if ($user['amount'] < $cartAmount) { 
  38.         $result['msg'] = '余额不足'; 
  39.         $result['code'] = 0; 
  40.         $this->ajaxReturn($result); 
  41.       } 
  42.     } 
  43.     // 生成订单 
  44.     $order['ordersn'] = $this->genOrdersn($user['id']); 
  45.     $order['price'] = $cartAmount; 
  46.     $order['addressid'] = $address['id']; 
  47.     $order['addressinfo'] = serialize($address); //json_encode($address); 
  48.     $order['longitude'] = $address['longitude']; 
  49.     $order['latitude'] = $address['latitude']; 
  50.     $order['addtime'] = time(); 
  51.     $order['status'] = 0; 
  52.     $order['userid'] = $user['id']; 
  53.     $order['paytype'] = $payment; 
  54.     $order['paysn'] = ''; 
  55.     $order['paytime'] = time(); 
  56.     $orderId = M("Order")->add($order); 
  57.     if ($orderId == 0) { 
  58.       $result['msg'] = '创建订单失败'; 
  59.       $result['code'] = 0; 
  60.       $this->ajaxReturn($result); 
  61.     } 
  62.     foreach ($cart as $goods) { 
  63.       $orderGoods['orderid'] = $orderId; 
  64.       $orderGoods['goodsid'] = $goods['id']; 
  65.       $orderGoods['title'] = $goods['title']; 
  66.       $orderGoods['price'] = $goods['price']; 
  67.       $orderGoods['attr'] = $goods['attr']; 
  68.       $orderGoods['pic'] = $goods['pic']; 
  69.       $orderGoods['num'] = $goods['selectcount']; 
  70.       M("OrderGoods")->add($orderGoods); 
  71.     } 
  72.     if ($payment == 'balance') { 
  73.       // 余额支付 
  74.       $this->balancePay($cartAmount, $user['wxopenid'], $orderId); 
  75.     } else if ($payment == 'weixin') { 
  76.       // 微信支付 
  77.       $this->weixinPay($cartAmount, $user['wxopenid'], $orderId, $order['ordersn']); 
  78.     } 
  79. } 
  80. /** 
  81. * 微信支付 
  82. * @author 大脸猫脸大 
  83. * @param $cart 
  84. * @param $cartAmount 
  85. * @param $address 
  86. * @param $user 
  87. */ 
  88. private function weixinPay($cartAmount, $openId, $orderId, $orderSn) 
  89. { 
  90.     import("Vendor.Wxpay.lib.WxPay#Api", "", ".php"); 
  91.     //订单号 
  92.     $money = $cartAmount * 100; 
  93.     $openid = $openId; 
  94.     $input = new \WxPayUnifiedOrder(); 
  95.     $input->SetBody("迪克-商品"); 
  96.     $input->SetOut_trade_no("$orderSn"); 
  97.     $input->SetTotal_fee("$money"); 
  98.     $input->SetNotify_url("https://" . $_SERVER['HTTP_HOST'] . "/api/buy/payNotify"); 
  99.     $input->SetTrade_type("JSAPI"); 
  100.     $input->SetOpenid($openid); 
  101.     $unifiedOrder = \WxPayApi::unifiedOrder($input); 
  102.     if ($unifiedOrder['result_code'] == 'SUCCESS' && $unifiedOrder['return_code'] == 'SUCCESS') { 
  103.       $time = time(); 
  104.       $data['timeStamp'] = "$time";              //时间戳 
  105.       $data['nonceStr'] = $unifiedOrder['nonce_str'];     //随机字符串 
  106.       $data['signType'] = 'MD5';                //签名算法,暂支持 MD5 
  107.       $data['package'] = 'prepay_id=' . $unifiedOrder['prepay_id'];  //统一下单接口返回的 prepay_id 参数值,提交格式如:prepay_id=* 
  108.       $data['paySign'] = $this->genPaySign($unifiedOrder, $time);// 之前以为是$unifiedOrder['sign']; 后来发现是调用的这种方法. 签名方案参见微信公众号支付帮助文档; 
  109.       $data['out_trade_no'] = $orderSn; 
  110.       $data['orderid'] = $orderId; 
  111.       $return['code'] = 1; 
  112.       $return['data'] = $data; 
  113.     } else { 
  114.         Log::write(var_export($unifiedOrder, true), Log::ERR, '', C('LOG_PATH')."wx_pay_".date('y_m_d').'.log'); 
  115.         $return['code'] = 0; 
  116.         $return['msg'] = '微信支付失败';// $unifiedOrder['RETURN_MSG']; 
  117.     } 
  118.     $this->ajaxReturn($return); 
  119. } 
  120. /* 生成支付签名*/ 
  121. private function genPaySign($unifiedOrder, $time) 
  122. { 
  123.     $appId = \WxPayConfig::APPID; 
  124.     $nonceStr = $unifiedOrder['nonce_str']; 
  125.     $package = 'prepay_id=' . $unifiedOrder['prepay_id']; 
  126.     $signType = "MD5"; 
  127.     $timeStamp = $time; 
  128.     $key = \WxPayConfig::KEY; 
  129.     $sign = md5(sprintf("appId=%s&nonceStr=%s&package=%s&signType=%s&timeStamp=%s&key=%s", $appId, $nonceStr, $package, $signType, $timeStamp, $key)); 
  130.     return $sign; 
  131. } 
  132. /** 
  133. * 支付回调 
  134. * @author:大脸猫脸大 
  135. */ 
  136. public function payNotify() 
  137. { 
  138.     import("Vendor.Wxpay.lib.WxPay#Data", "", ".php"); 
  139.     $xml = $GLOBALS['HTTP_RAW_POST_DATA']; 
  140.     $val = \WxPayResults::Init($xml); 
  141.     if ($val['result_code'] == 'SUCCESS' && $val['return_code'] == 'SUCCESS') { 
  142.       $orderSn = $val['out_trade_no']; 
  143.       $transactionId = $val['transaction_id']; 
  144.       $data = array('paytype' => 'weixin', 'status' => '1', 'paytime' => time(), 'paysn' => $transactionId); 
  145.       M("Order")->where("ordersn='$orderSn'")->setField($data); 
  146.       exit('<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>'); 
  147.     }else { 
  148.       Log::write(var_export($val, true), Log::ERR, '', C('LOG_PATH')."wx_pay_notify_".date('y_m_d').'.log'); 
  149.       exit('<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>'); 
  150.     } 
  151. } 

payNotify 回调方法里一定要注意返回

<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>

如果不处理,你会发现payNotify  会被执行很多次参见:官方文档

总结一下: 注意二点, 1.签名的问题 2. 回调方法的返回处理。

Tags: PHP小程序支付 thinkPHP

分享到: