Home > WeChat Applet > WeChat Development > Example analysis of implementing APP WeChat payment through PHP

Example analysis of implementing APP WeChat payment through PHP

php中世界最好的语言
Release: 2018-03-05 13:47:09
Original
2103 people have browsed it

Nowadays, using APP WeChat payment has become the mainstream payment mode. Below, the editor will introduce to you an example explanation of how to implement APP WeChat payment through PHP. , it is simple and easy to learn. Let’s learn APP with the editor Pay with WeChat.

1. The PHP background generates a prepayment transaction order, returns the correct prepayment transaction response ID, and then calls up the payment in the APP!

Official document:https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=9_1

Spliced ​​according to the document The parameters required by WeChat need several methods. Just upload the code!

The parameters transmitted to WeChat must be assembled into xml format and sent as parameter array!

public function ToXml($data=array())
 {
 if(!is_array($data) || count($data) <= 0)
 {
  return &#39;数组异常&#39;;
 }
 $xml = "<xml>";
 foreach ($data as $key=>$val)
 {
  if (is_numeric($val)){
  $xml.="<".$key.">".$val."</".$key.">";
  }else{
  $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
  }
 }
 $xml.="</xml>";
 return $xml;
 }
Copy after login

2. Generate random characters String, the parameters required by WeChat! There are many methods here, it depends on your hobbies!

function rand_code(){
 $str = &#39;0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ&#39;;//62个字符
 $str = str_shuffle($str);
 $str = substr($str,0,32);
 return $str;
}
Copy after login

3. This is an important step for WeChat, this method will be used many times! Generate signature

private function getSign($params) {
 ksort($params); //将参数数组按照参数名ASCII码从小到大排序
 foreach ($params as $key => $item) {
  if (!empty($item)) {  //剔除参数值为空的参数
  $newArr[] = $key.&#39;=&#39;.$item; // 整合新的参数数组
  }
 }
 $stringA = implode("&", $newArr);  //使用 & 符号连接参数
 $stringSignTemp = $stringA."&key="."************************"; //拼接key
 // key是在商户平台API安全里自己设置的
 $stringSignTemp = MD5($stringSignTemp); //将字符串进行MD5加密
 $sign = strtoupper($stringSignTemp); //将所有字符转换为大写
 return $sign;
 }
Copy after login

4. Pass the parameters to WeChat and generate a pre-payment order! Receive the data returned by WeChat and send it back to the APP. The APP calls the payment interface to complete the payment! For the parameters required on the APP, please see the WeChat documentation: https://pay. weixin.qq.com/wiki/doc/api/app/app.php?chapter=9_12&index=2

public function wx_pay() {
 $nonce_str = $this->rand_code(); //调用随机字符串生成方法获取随机字符串
 $data[&#39;appid&#39;] =&#39;wxdbc5dc*******&#39;; //appid
 $data[&#39;mch_id&#39;] = &#39;1493*****&#39; ; //商户号
 $data[&#39;body&#39;] = "APP支付测试";
 $data[&#39;spbill_create_ip&#39;] = $_SERVER[&#39;HTTP_HOST&#39;]; //ip地址
 $data[&#39;total_fee&#39;] = 1;    //金额
 $data[&#39;out_trade_no&#39;] = time().mt_rand(10000,99999); //商户订单号,不能重复
 $data[&#39;nonce_str&#39;] = $nonce_str;   //随机字符串
 $data[&#39;notify_url&#39;] = &#39;http://xxx.xxx.com/wx_notify&#39;; //回调地址,用户接收支付后的通知,必须为能直接访问的网址,不能跟参数
 $data[&#39;trade_type&#39;] = &#39;APP&#39;; //支付方式
 //将参与签名的数据保存到数组 注意:以上几个参数是追加到$data中的,$data中应该同时包含开发文档中要求必填的剔除sign以外的所有数据
 $data[&#39;sign&#39;] = $this->getSign($data); //获取签名
 $xml = $this->ToXml($data);  //数组转xml
 //curl 传递给微信方
 $url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
 //header("Content-type:text/xml");
 $ch = curl_init();
 curl_setopt($ch,CURLOPT_URL, $url);
 if(stripos($url,"https://")!==FALSE){
  curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
 } else {
  curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,TRUE);
  curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,2);//严格校验
 }
 //设置header
 curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
 curl_setopt($ch, CURLOPT_HEADER, FALSE);
 //要求结果为字符串且输出到屏幕上
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
 //设置超时
 curl_setopt($ch, CURLOPT_TIMEOUT, 30);
 curl_setopt($ch, CURLOPT_POST, TRUE);
 //传输文件
 curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
 //运行curl
 $data = curl_exec($ch);
 //返回结果
 if($data){
  curl_close($ch);
  //返回成功,将xml数据转换为数组.
  $re = $this->FromXml($data);
  if($re[&#39;return_code&#39;] != &#39;SUCCESS&#39;){
  json("201",&#39;签名失败&#39;);
  }
  else{
  //接收微信返回的数据,传给APP!
  $arr =array(
   &#39;prepayid&#39; =>$re[&#39;prepay_id&#39;],
   &#39;appid&#39; => &#39;wxdbc5dc*****&#39;,
   &#39;partnerid&#39; => &#39;14937****&#39;,
   &#39;package&#39; => &#39;Sign=WXPay&#39;,
   &#39;noncestr&#39; => $nonce_str,
   &#39;timestamp&#39; =>time(),
  );
  //第二次生成签名
  $sign = $this->getSign($arr);
  $arr[&#39;sign&#39;] = $sign;
  json(&#39;200&#39;,&#39;签名成功&#39;,$arr);
  }
 } else {
  $error = curl_errno($ch);
  curl_close($ch);
  json(&#39;201&#39;,"curl出错,错误码:$error");
 }
 }
Copy after login

5. Convert xml data into an array, used when receiving data returned by WeChat.

public function FromXml($xml)
 {
 if(!$xml){
  echo "xml数据异常!";
 }
 //将XML转为array
 //禁止引用外部xml实体
 libxml_disable_entity_loader(true);
 $data = json_decode(json_encode(simplexml_load_string($xml, &#39;SimpleXMLElement&#39;, LIBXML_NOCDATA)), true);
 return $data;
 }
Copy after login

2. After the APP payment is successful, it will call the callback address you filled in.

For details of the return parameters, please refer to the WeChat documentation: https://pay. weixin.qq.com/wiki/doc/api/app/app.php?chapter=9_7&index=3

// 微信支付回调
 function wx_notify(){
  //接收微信返回的数据数据,返回的xml格式
  $xmlData = file_get_contents(&#39;php://input&#39;);
  //将xml格式转换为数组
  $data = $this->FromXml($xmlData);
  //用日志记录检查数据是否接受成功,验证成功一次之后,可删除。
  $file = fopen(&#39;./log.txt&#39;, &#39;a+&#39;);
  fwrite($file,var_export($data,true));
  //为了防止假数据,验证签名是否和返回的一样。
  //记录一下,返回回来的签名,生成签名的时候,必须剔除sign字段。
  $sign = $data[&#39;sign&#39;];
  unset($data[&#39;sign&#39;]);
  if($sign == $this->getSign($data)){
  //签名验证成功后,判断返回微信返回的
  if ($data[&#39;result_code&#39;] == &#39;SUCCESS&#39;) {
  //根据返回的订单号做业务逻辑
  $arr = array(
   &#39;pay_status&#39; => 1,
   );
  $re = M(&#39;order&#39;)->where([&#39;order_sn&#39;=>$data[&#39;out_trade_no&#39;]])->save($arr);
  //处理完成之后,告诉微信成功结果!
  if($re){
   echo &#39;<xml>
  <return_code><![CDATA[SUCCESS]]></return_code>
  <return_msg><![CDATA[OK]]></return_msg>
  </xml>&#39;;exit();
  }
  }
  //支付失败,输出错误信息
  else{
  $file = fopen(&#39;./log.txt&#39;, &#39;a+&#39;);
  fwrite($file,"错误信息:".$data[&#39;return_msg&#39;].date("Y-m-d H:i:s"),time()."\r\n"); 
  }
 }
 else{
  $file = fopen(&#39;./log.txt&#39;, &#39;a+&#39;);
  fwrite($file,"错误信息:签名验证失败".date("Y-m-d H:i:s"),time()."\r\n"); 
  }
}
Copy after login

Here, the WeChat APP payment process is completed successfully! Thank you for your support!

The above is the specific method of implementing APP WeChat payment in PHP. Through the editor's example explanation, I believe everyone has mastered it.

Related recommendations:

Alarm notification example of WeChat payment

WeChat refund function example of PHP WeChat payment development

Thinkphp integrated WeChat payment function detailed explanation


The above is the detailed content of Example analysis of implementing APP WeChat payment through PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template