Home  >  Article  >  Backend Development  >  WeChat mini program payment function uses PHP for backend docking

WeChat mini program payment function uses PHP for backend docking

不言
不言Original
2018-06-13 09:29:571573browse

This article mainly introduces the payment function of WeChat mini program in detail, and shares the complete code of PHP backend docking, which has certain reference value. Interested friends can refer to

WeChat mini program Payment, PHP background docking complete code, all useful information, you can use it directly. The mini program requires 5 parameters before calling up WeChat Pay. At this time, you need to carry the code to request the background, and then the background obtains the openid based on the code and then performs the communication between servers.

1. Preparation work

1. Mini program registration. You must register a mini program as the company's identity to have WeChat payment permission;

2. Bind the merchant number.

3. Fill in the legal domain in the mini program

2. After completing the above conditions, you can get

Mini program appid Mini program secret key These two are used to obtain the user openid;

Merchant number id, merchant number secret key Required for the payment interface;

3. Start Development

Front-end code

 /* 
 调起微信支付 
 @param 支付价格,不填写默认为1分钱 
*/ 
function pay(total_fee) { 
 
 var total_fee = total_fee; 
 wx.login({ 
 success: res => { 
 
 //code 用于获取openID的条件之一 
 var code = res.code; 
 wx.request({ 
 url: '后台地址/index.php', 
 method: "POST", 
 data: { 
  total_fee:total_fee, 
  code: code, 
 }, 
 header: { 
  'content-type': 'application/x-www-form-urlencoded' // 默认值 
 }, 
 success: function (res) { //后端返回的数据 
  var data = res.data; 
  console.log(data); 
  console.log(data["timeStamp"]); 
  wx.requestPayment({ 
  timeStamp: data['timeStamp'], 
  nonceStr: data['nonceStr'], 
  package: data['package'], 
  signType: data['signType'], 
  paySign: data['paySign'], 
  success: function (res) { 
  wx.showModal({ 
  title: '支付成功', 
  content: '', 
  }) 
  }, 
  fail: function (res) { 
  console.log(res); 
  } 
  }) 
 } 
 }); 
 
 
 } 
 }) 
 
}

The following is the PHP back-end code, the tp framework is used here

<?php 
namespace Home\Controller; 
use Think\Controller; 
class PayController extends Controller { 
 
 /** 
 * [callback 微信支付回调处理] 
 * @Author zhengmingzhou 
 * @DateTime 2018-05-22 
 * @return function [description] 
 */ 
 public function callback(){ 
 vendor("Wechart.WxPay.Api"); 
 vendor("Wechart.NativePay"); 
 vendor("Wechart.WxPay.Data"); 
 vendor("Wechart.WxPay.Notify"); 
 
 
 //获取微信返回支付信息 
 $xml = $GLOBALS[&#39;HTTP_RAW_POST_DATA&#39;]; 
 $WxPayData = new \WxPayDataBase(); 
 $result = $WxPayData->FromXml($xml); 
 if($result[&#39;return_code&#39;] == &#39;SUCCESS&#39; && $result[&#39;result_code&#39;] == &#39;SUCCESS&#39;){ 
  //回调逻辑处理。。。 
  
  
  //返回给微信的参数 
  $data[&#39;RETURN_CODE&#39;] = &#39;SUCCESS&#39;; 
  $data[&#39;RETURN_MSG&#39;] = &#39;OK&#39;; 
 
 
 }else{ 
  $data[&#39;RETURN_CODE&#39;] = &#39;FAIL&#39;; 
  $data[&#39;RETURN_MSG&#39;] = &#39;NO&#39;; 
 } 
 //返回给微信 
 $xml = self::arrtoxml($data); 
 echo $xml; 
 } 
 
 /** 
 * [arrtoxml 格式化返回给微信的数据格式] 
 * @Author zhengmingzhou 
 * @DateTime 2018-05-22 
 * @param [type] $arr [description] 
 * @return [type]  [description] 
 */ 
 private function arrtoxml( $arr ){ 
 if(!$arr){ 
  return &#39;&#39;; 
 }else{ 
  $xml = "<xml>"; 
  foreach ($arr as $key=>$val) 
  { 
  if (is_numeric($val)){ 
   $xml.="<".$key.">".$val."</".$key.">"; 
  }else{ 
   $xml.="<".$key."><![CDATA[".$val."]]></".$key.">"; 
  } 
  } 
  $xml.="</xml>"; 
  return $xml; 
 } 
 } 
 
//微信支付 
public function pay(){ 
 //获取openid 
 if(I("post.code")) 
 { //用code获取openid 
  $code=I("post.code"); 
  $WX_APPID = &#39;&#39;;//appid 
  $WX_SECRET = &#39;&#39;;//AppSecret 
  $url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $WX_APPID . "&secret=" . $WX_SECRET . "&js_code=" . $code . "&grant_type=authorization_code"; 
  $infos = json_decode(file_get_contents($url)); 
  $openid = $infos->openid; 
 } 
 if(I("post.total_fee")) 
 { 
  $total_fee=I("post.total_fee"); 
 } 
 else 
 { 
  $total_fee=0.01; 
 } 
 
 $fee = 0.01;//举例充值0.01 
 $appid = &#39;&#39;;//appid 
 $body =  &#39;标题&#39;; 
 $mch_id = &#39;&#39;; //商户号 
 $nonce_str = $this->nonce_str();//随机字符串 
 $notify_url = &#39;&#39;; //回调的url【自己填写】 
 $openid = $openid; 
 $out_trade_no = $this->order_number();//商户订单号 
 $spbill_create_ip = &#39;&#39;;//服务器的ip【自己填写】; 
 $total_fee = $fee*100;//这里需要*100 
 $trade_type = &#39;JSAPI&#39;;//交易类型 默认 
 
 
 //这里是按照顺序的 因为下面的签名是按照顺序 排序错误 肯定出错 
 $post[&#39;appid&#39;] = $appid; 
 $post[&#39;body&#39;] = $body; 
 $post[&#39;mch_id&#39;] = $mch_id; 
 $post[&#39;nonce_str&#39;] = $nonce_str;//随机字符串 
 $post[&#39;notify_url&#39;] = $notify_url; 
 $post[&#39;openid&#39;] = $openid; 
 $post[&#39;out_trade_no&#39;] = $out_trade_no; 
 $post[&#39;spbill_create_ip&#39;] = $spbill_create_ip;//终端的ip 
 $post[&#39;total_fee&#39;] = $total_fee;//总金额 
 $post[&#39;trade_type&#39;] = $trade_type; 
 $sign = $this->sign($post);//签名 
 $post_xml = &#39;<xml> 
  <appid>&#39;.$appid.&#39;</appid> 
  <body>&#39;.$body.&#39;</body> 
  <mch_id>&#39;.$mch_id.&#39;</mch_id> 
  <nonce_str>&#39;.$nonce_str.&#39;</nonce_str> 
  <notify_url>&#39;.$notify_url.&#39;</notify_url> 
  <openid>&#39;.$openid.&#39;</openid> 
  <out_trade_no>&#39;.$out_trade_no.&#39;</out_trade_no> 
  <spbill_create_ip>&#39;.$spbill_create_ip.&#39;</spbill_create_ip> 
  <total_fee>&#39;.$total_fee.&#39;</total_fee> 
  <trade_type>&#39;.$trade_type.&#39;</trade_type> 
  <sign>&#39;.$sign.&#39;</sign> 
 </xml> &#39;; 
 
 
 //print_r($post_xml);die; 
 //统一接口prepay_id 
 $url = &#39;https://api.mch.weixin.qq.com/pay/unifiedorder&#39;; 
 $xml = $this->http_request($url,$post_xml); 
 
 $array = $this->xml($xml);//全要大写 
 
 
 //print_r($array); 
 if($array[&#39;RETURN_CODE&#39;] == &#39;SUCCESS&#39; && $array[&#39;RESULT_CODE&#39;] == &#39;SUCCESS&#39;){ 
 $time = time(); 
 $tmp=&#39;&#39;;//临时数组用于签名 
 $tmp[&#39;appId&#39;] = $appid; 
 $tmp[&#39;nonceStr&#39;] = $nonce_str; 
 $tmp[&#39;package&#39;] = &#39;prepay_id=&#39;.$array[&#39;PREPAY_ID&#39;]; 
 $tmp[&#39;signType&#39;] = &#39;MD5&#39;; 
 $tmp[&#39;timeStamp&#39;] = "$time"; 
 
 
 $data[&#39;state&#39;] = 200; 
 $data[&#39;timeStamp&#39;] = "$time";//时间戳 
 $data[&#39;nonceStr&#39;] = $nonce_str;//随机字符串 
 $data[&#39;signType&#39;] = &#39;MD5&#39;;//签名算法,暂支持 MD5 
 $data[&#39;package&#39;] = &#39;prepay_id=&#39;.$array[&#39;PREPAY_ID&#39;];//统一下单接口返回的 prepay_id 参数值,提交格式如:prepay_id=* 
 $data[&#39;paySign&#39;] = $this->sign($tmp);//签名,具体签名方案参见微信公众号支付帮助文档; 
 $data[&#39;out_trade_no&#39;] = $out_trade_no; 
 
 
 }else{ 
 $data[&#39;state&#39;] = 0; 
 $data[&#39;text&#39;] = "错误"; 
 $data[&#39;RETURN_CODE&#39;] = $array[&#39;RETURN_CODE&#39;]; 
 $data[&#39;RETURN_MSG&#39;] = $array[&#39;RETURN_MSG&#39;]; 
 } 
 
 
 echo json_encode($data); 
} 

 
//随机32位字符串 
private function nonce_str(){ 
 $result = &#39;&#39;; 
 $str = &#39;QWERTYUIOPASDFGHJKLZXVBNMqwertyuioplkjhgfdsamnbvcxz&#39;; 
 for ($i=0;$i<32;$i++){ 
 $result .= $str[rand(0,48)]; 
 } 
 return $result; 
} 
 
 
//生成订单号 
private function order_number($openid){ 
 //date(&#39;Ymd&#39;,time()).time().rand(10,99);//18位 
 return md5($openid.time().rand(10,99));//32位 
} 
 
 
//签名 $data要先排好顺序 
private function sign($data){ 
 $stringA = &#39;&#39;; 
 foreach ($data as $key=>$value){ 
 if(!$value) continue; 
 if($stringA) $stringA .= &#39;&&#39;.$key."=".$value; 
 else $stringA = $key."=".$value; 
 } 
 $wx_key = &#39;&#39;;//申请支付后有给予一个商户账号和密码,登陆后自己设置的key 
 $stringSignTemp = $stringA.&#39;&key=&#39;.$wx_key; 
 return strtoupper(md5($stringSignTemp)); 
} 
 
 
//curl请求 
public function http_request($url,$data = null,$headers=array()) 
{ 
 $curl = curl_init(); 
 if( count($headers) >= 1 ){ 
 curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); 
 } 
 curl_setopt($curl, CURLOPT_URL, $url); 
 
 
 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); 
 curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); 
 
 
 if (!empty($data)){ 
 curl_setopt($curl, CURLOPT_POST, 1); 
 curl_setopt($curl, CURLOPT_POSTFIELDS, $data); 
 } 
 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); 
 $output = curl_exec($curl); 
 curl_close($curl); 
 return $output; 
} 
 
 
//获取xml 
private function xml($xml){ 
 $p = xml_parser_create(); 
 xml_parse_into_struct($p, $xml, $vals, $index); 
 xml_parser_free($p); 
 $data = ""; 
 foreach ($index as $key=>$value) { 
 if($key == &#39;xml&#39; || $key == &#39;XML&#39;) continue; 
 $tag = $vals[$value[0]][&#39;tag&#39;]; 
 $value = $vals[$value[0]][&#39;value&#39;]; 
 $data[$tag] = $value; 
 } 
 return $data; 
} 
 
}

The above is the entire content of this article. I hope it will be helpful to everyone’s study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

Use html_entity_decode to implement HTML entity escaping in php

The above is the detailed content of WeChat mini program payment function uses PHP for backend docking. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn