系统城装机大师 - 固镇县祥瑞电脑科技销售部宣传站!

当前位置:首页 > 网络编程 > PHP编程 > 详细页面

PHP实现微信小程序在线支付功能(代码实例)

时间:2020-03-06来源:电脑系统城作者:电脑系统城

小程序访问地址:payfee.php 如果使用TP框架处理后台的话,写成方法即可


 
  1. include 'WeixinPay.php';
  2. $appid=''; //小程序appid
  3. $openid= $_POST['id'];
  4. $mch_id=''; //微信支付商户支付号
  5. $key=''; //Api密钥
  6. $out_trade_no = $mch_id. time();
  7. $total_fee = $_POST['fee'];
  8. if (empty($total_fee)) { //押金
  9. $body = "充值押金";
  10. $total_fee = floatval(99*100);
  11. } else {
  12. $body = "充值余额";
  13. $total_fee = floatval($total_fee*100);
  14. }
  15. $weixinpay = new WeixinPay($appid,$openid,$mch_id,$key,$out_trade_no,$body,$total_fee);
  16. $return=$weixinpay->pay();
  17. echo json_encode($return);

WeixinPay.php微信小程序支付类 所有微信小程序需要的参数都已经写入


 
  1. /*
  2. * 小程序微信支付
  3. */
  4. class WeixinPay {
  5. protected $appid;
  6. protected $mch_id;
  7. protected $key;
  8. protected $openid;
  9. protected $out_trade_no;
  10. protected $body;
  11. protected $total_fee;
  12. function __construct($appid, $openid, $mch_id, $key,$out_trade_no,$body,$total_fee) {
  13. $this->appid = $appid;
  14. $this->openid = $openid;
  15. $this->mch_id = $mch_id;
  16. $this->key = $key;
  17. $this->out_trade_no = $out_trade_no;
  18. $this->body = $body;
  19. $this->total_fee = $total_fee;
  20. }
  21. public function pay() {
  22. //统一下单接口
  23. $return = $this->weixinapp();
  24. return $return;
  25. }
  26. //统一下单接口
  27. private function unifiedorder() {
  28. $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
  29. $parameters = array(
  30. 'appid' => $this->appid, //小程序ID
  31. 'mch_id' => $this->mch_id, //商户号
  32. 'nonce_str' => $this->createNoncestr(), //随机字符串
  33. // 'body' => 'test', //商品描述
  34. 'body' => $this->body,
  35. // 'out_trade_no' => '2018013106125348', //商户订单号
  36. 'out_trade_no'=> $this->out_trade_no,
  37. // 'total_fee' => floatval(0.01 * 100), //总金额 单位 分
  38. 'total_fee' => $this->total_fee,
  39. 'spbill_create_ip' => $_SERVER['REMOTE_ADDR'], //终端IP
  40. // 'spbill_create_ip' => '192.168.0.161', //终端IP
  41. 'notify_url' => 'https://www.weixin.qq.com/wxpay/notify.php', //通知地址 确保外网能正常访问
  42. 'openid' => $this->openid, //用户id
  43. 'trade_type' => 'JSAPI'//交易类型
  44. );
  45. //统一下单签名
  46. $parameters['sign'] = $this->getSign($parameters);
  47. $xmlData = $this->arrayToXml($parameters);
  48. $return = $this->xmlToArray($this->postXmlCurl($xmlData, $url, 60));
  49. return $return;
  50. }
  51. private static function postXmlCurl($xml, $url, $second = 30)
  52. {
  53. $ch = curl_init();
  54. //设置超时
  55. curl_setopt($ch, CURLOPT_TIMEOUT, $second);
  56. curl_setopt($ch, CURLOPT_URL, $url);
  57. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  58. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); //严格校验
  59. //设置header
  60. curl_setopt($ch, CURLOPT_HEADER, FALSE);
  61. //要求结果为字符串且输出到屏幕上
  62. curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  63. //post提交方式
  64. curl_setopt($ch, CURLOPT_POST, TRUE);
  65. curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
  66. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
  67. curl_setopt($ch, CURLOPT_TIMEOUT, 40);
  68. set_time_limit(0);
  69. //运行curl
  70. $data = curl_exec($ch);
  71. //返回结果
  72. if ($data) {
  73. curl_close($ch);
  74. return $data;
  75. } else {
  76. $error = curl_errno($ch);
  77. curl_close($ch);
  78. throw new WxPayException("curl出错,错误码:$error");
  79. }
  80. }
  81. //数组转换成xml
  82. private function arrayToXml($arr) {
  83. $xml = "<xml>";
  84. foreach ($arr as $key => $val) {
  85. if (is_array($val)) {
  86. $xml .= "<" . $key . ">" . arrayToXml($val) . "</" . $key . ">";
  87. } else {
  88. $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
  89. }
  90. }
  91. $xml .= "</xml>";
  92. return $xml;
  93. }
  94. //xml转换成数组
  95. private function xmlToArray($xml) {
  96. //禁止引用外部xml实体
  97. libxml_disable_entity_loader(true);
  98. $xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
  99. $val = json_decode(json_encode($xmlstring), true);
  100. return $val;
  101. }
  102. //微信小程序接口
  103. private function weixinapp() {
  104. //统一下单接口
  105. $unifiedorder = $this->unifiedorder();
  106. // print_r($unifiedorder);
  107. $parameters = array(
  108. 'appId' => $this->appid, //小程序ID
  109. 'timeStamp' => '' . time() . '', //时间戳
  110. 'nonceStr' => $this->createNoncestr(), //随机串
  111. 'package' => 'prepay_id=' . $unifiedorder['prepay_id'], //数据包
  112. 'signType' => 'MD5'//签名方式
  113. );
  114. //签名
  115. $parameters['paySign'] = $this->getSign($parameters);
  116. return $parameters;
  117. }
  118. //作用:产生随机字符串,不长于32位
  119. private function createNoncestr($length = 32) {
  120. $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
  121. $str = "";
  122. for ($i = 0; $i < $length; $i++) { $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1); }return $str; } //作用:生成签名 private function getSign($Obj) { foreach ($Obj as $k => $v) {
  123. $Parameters[$k] = $v;
  124. }
  125. //签名步骤一:按字典序排序参数
  126. ksort($Parameters);
  127. $String = $this->formatBizQueryParaMap($Parameters, false);
  128. //签名步骤二:在string后加入KEY
  129. $String = $String . "&key=" . $this->key;
  130. //签名步骤三:MD5加密
  131. $String = md5($String);
  132. //签名步骤四:所有字符转为大写
  133. $result_ = strtoupper($String);
  134. return $result_;
  135. }
  136. ///作用:格式化参数,签名过程需要使用
  137. private function formatBizQueryParaMap($paraMap, $urlencode) {
  138. $buff = "";
  139. ksort($paraMap);
  140. foreach ($paraMap as $k => $v) {
  141. if ($urlencode) {
  142. $v = urlencode($v);
  143. }
  144. $buff .= $k . "=" . $v . "&";
  145. }
  146. $reqPar = '';
  147. if (strlen($buff) > 0) {
  148. $reqPar = substr($buff, 0, strlen($buff) - 1);
  149. }
  150. return $reqPar;
  151. }
  152. }

小程序页面请求处理:


 
  1. wx.request({
  2. url: 'https://yourhost.com/wxpay/payfee.php',//改成你自己的链接
  3. data:{
  4. id: app.globalData.openid,//获取用户openid
  5. fee:100 //商品价格
  6. },
  7. header: {
  8. 'Content-Type': 'application/x-www-form-urlencoded'
  9. },
  10. method: 'POST',
  11. success: function (res) {
  12. console.log(res.data);
  13. console.log('调起支付');
  14. wx.requestPayment({
  15. 'timeStamp': res.data.timeStamp,
  16. 'nonceStr': res.data.nonceStr,
  17. 'package': res.data.package,
  18. 'signType': 'MD5',
  19. 'paySign': res.data.paySign,
  20. 'success': function (res) {
  21. console.log('success');
  22. wx.showToast({
  23. title: '支付成功',
  24. icon: 'success',
  25. duration: 3000
  26. });
  27. },
  28. 'fail': function (res) {
  29. console.log(res);
  30. },
  31. 'complete': function (res) {
  32. console.log('complete');
  33. }
  34. });
  35. },
  36. fail: function (res) {
  37. console.log(res.data)
  38. }
  39. });

回调URL:notify.php


 
  1. $postXml = $GLOBALS["HTTP_RAW_POST_DATA"]; //接收微信参数
  2. // 接受不到参数可以使用file_get_contents("php://input"); PHP高版本中$GLOBALS好像已经被废弃了
  3. if (empty($postXml)) {
  4. return false;
  5. }
  6.  
  7. //将xml格式转换成数组
  8. function xmlToArray($xml) {
  9. //禁止引用外部xml实体
  10. libxml_disable_entity_loader(true);
  11. $xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
  12. $val = json_decode(json_encode($xmlstring), true);
  13. return $val;
  14. }
  15.  
  16. $attr = xmlToArray($postXml);
  17. $total_fee = $attr['total_fee'];
  18. $open_id = $attr['openid'];
  19. $out_trade_no = $attr['out_trade_no'];
  20. $time = $attr['time_end'];

So:在微信的异步通知后,也需要给微信服务器,返回一个信息,只不过微信的所有数据格式都是xml的,所以我们在返回一个数据给微信即可。

echo exit('<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>');

总结

到此这篇关于PHP微信小程序在线支付功能的文章就介绍到这了,更多相关php 微信小程序在线支付内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

分享到:

相关信息

系统教程栏目

栏目热门教程

人气教程排行

站长推荐

热门系统下载