English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Developing WeChat payment function for APP end in PHP

Some personal thoughts on developing WeChat payment on the APP side with PHP

Recently, due to the company's requirements, I need to develop WeChat payment on the APP side. After reading the WeChat document, I feel it is not bad, I haven't encountered too many pitfalls, and the points to pay attention to are not too many.

Write a note document as a memo.

APP payment process

From the above picture, it can be seen that the process that needs to be paid attention to is a total of3Part;
The first part: calling the order API, returning the pre-payment order, signing the information again and then returning it (4,5,6,7)
The second part: asynchronous notification (15,16)
The third part: the final judgment of the payment result
The most important part to pay attention to is the first part: calling the order API, returning the pre-payment order, signing the information again and then returning it

WeChat DocumentDetailed instructions are provided in the attachment, and no further elaboration is needed here.

Append my code below, copycats, just modify the code a little and it can be used.

//Entry function
function weChatPay(){
   $json = array();
   //The required parameters for generating a pre-payment transaction order:
   $json = array();
   //Application ID
   $newPara["appid"] = "wx2421b1c4370ec43b";
   //Merchant number
   $newPara["mch_id"] = "10000100";
   //Device number
   $newPara["device_info"] = "WEB";
   //Random string, it is recommended to use the function to generate
   $newPara["nonce_str"] = "1add1a30ac87aa2db72f57a2375d8fec"
   //Product description
   $newPara["body"] = "APP payment test";
   //Merchant order number, this is the internal order number of the merchant
   $newPara["out_trade_no"] = "1415659990";
   //Total amount
   $newPara["total_fee"] = 1;
   //Terminal IP
   $newPara["spbill_create_ip"] = $_SERVER["REMOTE_ADDR"];
   //Notification address, note that no parameters should be added to the URL here
   $newPara["notify_url"] = "http://wxpay.wxutil.com/pub_v2/pay/notify.v2.php";
   //Transaction type
   $newPara["trade_type"] = "APP";
   //First signature
   $newPara["sign"] = produceWeChatSign($newPara);
   //Convert the array to XML format
   $xmlData = getWeChatXML($newPara);
   //Use PHP's CURL package to send data to WeChat unified order interface, and return a normal prepay_id
   $get_data = sendPrePayCurl($xmlData);
   //Determine the result returned.
   if($get_data['return_code'] == "SUCCESS" && $get_data['result_code'] == "SUCCESS"){
    //Perform the second signature based on the result returned by WeChat payment
    //Random string required for the second signature
    $newPara["nonce_str"] = "5K8264ILTKCH16CQ2502SI8ZNMTM67VS";
    //Timestamp required for the second signature
    $newPara['timeStamp'] = time()."";
    //Supplement of remaining parameters for the second signature
    $secondSignArray = array(
     "appid"=>$newPara['appid'],
     "noncestr"=>$newPara['nonce_str'],
     "package"=>"Sign=WXPay",
     "prepayid"=>$get_data['prepay_id'],
     "partnerid"=>$newPara['mch_id'],
     "timestamp"=>$newPara['timeStamp'],
    );
    $json['datas'] = $secondSignArray;
    $json['ordersn'] = $newPara["out_trade_no"];
    $json['datas']['sign'] = weChatSecondSign($newPara,$get_data['prepay_id']);
    $json['message'] = "预支付完成";
    //The prepayment is completed, and the internal business logic is performed below
    /*****************************/
    return json_encode($json);
   }
   else{
    $json['message'] = $get_data['return_msg'];
   }
  }
  return json_encode($json);
 }
//The function produceWeChatSign for the first signature
function produceWeChatSign($newPara){
  $stringA = self::getSignContent($newPara);
  $stringSignTemp=$stringA."&key=192006250b4c09247ec02edce69f6a2d";
  return strtoupper(MD5($stringSignTemp));
 }
//Function to generate XML format
 public static function getWeChatXML($newPara){
  $xmlData = "<xml>";
  foreach ($newPara as $key => $value) {
   $xmlData = $xmlData."<".$key.">".$value."</".$key.">";
  }
  $xmlData = $xmlData."</xml>";
  return $xmlData;
 }
//Function to send data to the WeChat interface via curl
function sendPrePayCurl($xmlData) {
  $url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
  $header[] = "Content-type: text/xml";
  $curl = curl_init();
  curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
  curl_setopt($curl, CURLOPT_URL, $url);
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($curl, CURLOPT_POST, 1);
  curl_setopt($curl, CURLOPT_POSTFIELDS, $xmlData);
  $data = curl_exec($curl);
  if (curl_errno($curl)) {
   print curl_error($curl);
  }
  curl_close($curl);
  return self::XMLDataParse($data);
 }
//xml format data parsing function
 public static function XMLDataParse($data){
  $msg = array();
  $msg = (array)simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA);
  return $msg;
 }
//The function of the second signature
function weChatSecondSign($newPara,$prepay_id){
  $secondSignArray = array(
   "appid"=>$newPara['appid'],
   "noncestr"=>$newPara['nonce_str'],
   "package"=>"Sign=WXPay",
   "prepayid"=>$prepay_id,
   "partnerid"=>$newPara['mch_id'],
   "timestamp"=>$newPara['timeStamp'],
  );
  $stringA = self::getSignContent($secondSignArray);
  $stringSignTemp=$stringA."&key=192006250b4c09247ec02edce69f6a2d";
  return strtoupper(MD5($stringSignTemp));
 }

Two points to note:

1.The second signature needs to be completed in the background, and after completion, all the information used for the second signature should be sent to the front end to trigger WeChat payment. This is not easy to cause the situation where WeChat payment cannot be triggered.
2.Two signatures use different random strings.

That's all for this article. Hope it will be helpful to everyone's learning and also hope everyone will support the Yelling Tutorial more.

Statement: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.)

You May Also Like