This paper briefly introduces the application, access, use and confirmation of payment results of wechat scanning code payment

Series of articles

Series 1 wechat App payment full resolution series 2 Alipay App Payment full resolution series 3 wechat public account payment full resolution series 4 wechat scan code payment full resolution series 5 Alipay instant payment full resolution series 6 wechat refund full resolution series 7 Alipay refund full resolution series 8 Full analysis of alipay open platform payment updates and upgrades

1 application

For application procedures, refer to the official documents

There are two main blocks:

  1. Apply to open a public platform and create an application
  2. Apply for payment and open merchant platform

After all applications are approved, the parameters required for payment are as follows:

1.1 AppID and AppSecret

The unique identity of the application created by the public platform. Login wechat public platform, enter the application details to view AppID and AppSecret.

Paste_Image.png

1.2 mch_id

After the completion of the wechat payment application, the wechat merchant platform will send a notification email to your mailbox, which contains the merchant information of the payment

Paste_Image.png

1.3 API secret key

Namely, merchant payment secret key, which is mainly responsible for communication related parameters encryption. Log in to the wechat merchant platform (the account password is in the email sent by the wechat merchant platform) and click “Account Setting – API Security” on the left (the first login will let you install the operation certificate, please install the operation certificate first). Click Set Key to set your own key.

Paste_Image.png

1.4 Merchant Certificate

For refund and other need certificate authentication interface use. Click “Account Center – API Security” on wechat merchant platform and click “Download certificate”

Paste_Image.png

Pem, apiclient_key.pem, and rootca.pem certificates are displayed when you open the compressed file package.

2 Access Process

Reference Access document

The main steps are:

  1. Unified order (placed on the server, encryption parameters required)
  2. Generate payment parameters (on the server side, need to generate signature)
  3. The payment address will generate a QR code to scan the payment directly
  4. The server receives the payment result asynchronously

2.1 Unified order

$appid = "";  Your appid / /
$mch_id = "";  / / merchant id
$wx_api_key = "";    // Merchant API key
$out_trade_no = "";  // Transaction no generated by your own business system can be uniquely identified
$client_ip = "";  // Client IP address
$notify_url = "";    // Receive payment result notification URL
$openid = "";    // OpenID obtained by wechat authorization
$product_id = "";  // Product ID A unique item ID defined by the service

$UNIFIED_ORDER_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder";  // add a single address

$data = array(a); $data['appid'] = $appid; 
$data['mch_id'] =$mch_id;
$data['nonce_str'] = randomStr(20);  // A random 20-character string
$data['product_id'] = $product_id;
$data['body'] = "Wechat Scan payment Test";
$data['detail'] = "Wechat scan code payment test detail";
$data['out_trade_no'] = $out_trade_no;    
$data['total_fee'] = 1;  // Note that the unit is minutes
$data['spbill_create_ip'] = $client_ip;
$data['openid'] = $openid;
$data['notify_url'] = $notify_url;
$data['trade_type'] = "NATIVE";  // Transaction type
$data['sign'] =sign($data, $wx_api_key);    / / signature

// Convert to XML format
$xml_str = arrayToXmlStr($data); 

// Send the request using the wrapped curl_POST
$result = curl_post($UNIFIED_ORDER_URL, $xml_str);

// Parse the resulting value
$get_data = simplexml_load_string($raw_data, 'SimpleXMLElement', LIBXML_NOCDATA);
$get_para = array(a); $get_sign ="";
foreach ($get_data->children() as $child) 
{    
  if($child->getName() == 'sign') {        
    $get_sign = strval($child);    
  } else{ $get_para[strval($child->getName())] = strval($child); }}if($get_para['return_code']! = ="SUCCESS") {
    //return code fail
}

// Verify the signature
if(! verifySign($get_sign, $get_para, $wx_api_key)) {// Verify that the signature is invalid
}

// Get the payment address
$code_url = $get_para['code_url'];Copy the code

Some functions:

/** * array to XML STR *@param $arr
 */
public static function arrayToXmlStr($arr) {    
  $xml_data = new \SimpleXMLElement("<xml></xml>");    
  Func::arrayToXml($arr, $xml_data);    
  return $xml_data->asXML();
}

/** * Generates a random string of specified length (including uppercase letters, lowercase letters, and digits) *@param$length int Specifies the length of the string to be generated *@returnString A random string of uppercase and lowercase letters and numbers */
public static function randomStr($length){    
  // Generate an array of uppercase letters, lowercase letters, and numbers
  $arr = array_merge(range(0.9), range('a'.'z'), range('A'.'Z'));    
  $str = ' ';    
  $arr_len = count($arr);    
  for ($i = 0; $i < $length; $i++)    {        
    $rand = mt_rand(0, $arr_len- 1);        
    $str.=$arr[$rand];    
  }    
  return $str;
}

/** * wechat signature *@param$para mixed with signature parameter array *@param $wx_key string wxkey
 */
public static function sign($para, $wx_key) {    
  $unsign_str = Func::createLinkString(Func::argSort($para)) . "&key=" . $wx_key;    
  $sign = strtoupper(md5($unsign_str));    
  return $sign;
}

/** * wechat signature verification *@param $sign
 * @param $para
 * @param $wx_key
 * @returnFalse - Authentication failed true- Authentication succeeded */
public static function verifySign($sign, $para, $wx_key) {    
  $unsign_str = Func::createLinkString(Func::argSort($para)) . "&key=" . $wx_key;    
  $sign_str = strtoupper(md5($unsign_str));    
  if($sign === $sign_str) {        
    return true;    
  }    
  return false;
}Copy the code

3. Pay

Directly convert the Code_url obtained after placing a unified order into the QR code for payment. Note: the qr code is valid for 2 hours.

After the payment is completed, the business party is advised to poll to check the transaction status of the server because no synchronization result is returned due to code scanning.

4 Asynchronous result notification

Note: in particular, it is necessary to correctly deal with repeated notifications after successful verification of notification results, and to place multiple shipments resulting in capital losses

$raw_data = $GLOBALS["HTTP_RAW_POST_DATA"];

$get_data = simplexml_load_string($raw_data, 'SimpleXMLElement', LIBXML_NOCDATA);
$get_para = array(a); $get_sign ="";
foreach ($get_data->children() as $child) 
{    
  if($child->getName() == 'sign') {        
    $get_sign = strval($child);    
  } else{ $get_para[strval($child->getName())] = strval($child); }}if($get_para['return_code']! = ="SUCCESS") {
    //return code fail
    die("
      
       
        
       
      ");
}

// Verify the signature
if(! verifySign($get_sign, $get_para, $wx_api_key)) {// Verify that the signature is invalid
    //todo
    die("
      
       
        
       
      ");
}

// In fact, the notification has been accepted successfully can be returned to tell wechat that there is no need to notify again
echo("
      
       
        
       
      ");

// Determine the service status code
if ($get_para['result_code']! = ='SUCCESS') {       // The status code is incorrect
  // Payment error change order status log, etc
  / /...
}

// Pay successfully change order status record log, etc
//todoCopy the code

Five other

  1. After receiving the synchronous payment result, the client recommends polling and checking the server for a period of time to obtain the result of the server. The final payment status is subject to the server

At the end

More articles follow my public account

My official account