PHP WeChat red packet API

Source: Internet
Author: User
Tags openid rand vars


According to the WeChat advanced red envelope interface, the PHP version of the API is developed and the main code analysis is now carried out.

The red envelope interface calls the request code. All request parameters are mandatory and correspond to the document:

Class Wxapi {
Private $ app_id = 'wxxxxxxxxxxxxxxxx'; // public account appid. First, apply for a public account
Private $ app_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxx'; // secret of the public account. The user obtains the token authorized by the user.
Private $ app_mchid = 'xxxxxxxx'; // merchant id
Function _ construct (){
// Do something here ....
    }
/**
* WeChat payment
* @ Param string $ openid: User openid
*/
Public function pay ($ re_openid)
    {
Include_once ('wxhongbaohelper. Php ');
$ CommonUtil = new CommonUtil ();
$ WxHongBaoHelper = new WxHongBaoHelper ();
$ WxHongBaoHelper-> setParameter ("nonce_str", $ this-> great_rand (); // random string, not longer than 32 characters
$ WxHongBaoHelper-> setParameter ("mch_billno", $ this-> app_mchid.date ('ymdhis '). rand (1000,999 9); // order number
$ WxHongBaoHelper-> setParameter ("mch_id", $ this-> app_mchid); // merchant ID
$ WxHongBaoHelper-> setParameter ("wxappid", $ this-> app_id );
$ WxHongBaoHelper-> setParameter ("nick_name", 'hongba'); // provider name
$ WxHongBaoHelper-> setParameter ("send_name", 'hongba'); // name of the Red Packet Sender
$ WxHongBaoHelper-> setParameter ("re_openid", $ re_openid); // openid for intercommunication with medical channels
$ WxHongBaoHelper-> setParameter ("total_amount", 100); // payment amount, in minutes
$ WxHongBaoHelper-> setParameter ("min_value", 100); // minimum red packet amount, in minutes
$ WxHongBaoHelper-> setParameter ("max_value", 100); // maximum red packet amount, in minutes
$ WxHongBaoHelper-> setParameter ("total_num", 1); // What about red packets? Why did the slogan fail? Br/> $ wxHongBaoHelper-> setParameter ("wishing", 'thank you for participating in the red packet distribution activity and wishing you a happy new year! '); // Red envelope blessing
$ WxHongBaoHelper-> setParameter ("client_ip", '192. 0.0.1 '); // Ip address of the machine that calls the interface
$ WxHongBaoHelper-> setParameter ("act_name", 'Red packet activity'); // name of the active token
$ WxHongBaoHelper-> setParameter ("remark", 'Come and grab it! '); // Remarks
$ PostXml = $ wxHongBaoHelper-> create_hongbao_xml ();
$ Url = 'https: // api.mch.weixin.qq.com/mmp aymkttransfers/sendredpack ';
$ ResponseXml = $ wxHongBaoHelper-> curl_post_ssl ($ url, $ postXml );
// Used as result debugging output
// Echo htmlentities ($ responseXml, ENT_COMPAT, 'utf-8 ');
$ ResponseObj = simplexml_load_string ($ responseXml, 'simplexmlelement', LIBXML_NOCDATA );
Return $ responseObj-> return_code;
    }

Method to obtain a random string:


/**
* Generate a random number
*/
Public function great_rand (){
$ Str = '1234567890abcdefghijklmnopqrstuvwxyz ';
For ($ I = 0; $ I <30; $ I ++ ){
$ J = rand (0, 35 );
$ T1. = $ str [$ j];
    }
Return $ t1;
}

Signature Algorithm:


/**
For example:
Appid: wxd111665abv58f4f
Mch_id: 10000100
Device Info: 1000
Body: test
Nonce_str: ibuaiVcKdpRxkhJA
Step 1: sort the parameters in key = value format and in the ASCII lexicographic order of parameter names as follows:
StringA = "appid = wxd930ea5d5a258f4f & body = test & device_info = 1000 & mch_ I
D = 10000100 & nonce_str = ibuaiVcKdpRxkhJA ";
Step 2: splice the payment key:
StringSignTemp = "stringA & key = 192006250b4c09247ec02edce69f6a2d"
Sign = MD5 (stringSignTemp). toUpperCase () = "9A0A8659F005D6984697E2CA0A
9CF3B7"
*/
Protected function get_sign (){
Define ('ererkey', "QSRXXXXXXXXXXXXXXXXXXXXX ");
Try {
If (null = PARTNERKEY | "" = PARTNERKEY ){
Throw new SDKRuntimeException ("The key cannot be blank! "." <Br> ");
        }
If ($ this-> check_sign_parameters () = false) {// Check the signature parameters generated
Throw new SDKRuntimeException ("The generated signature parameter is missing! "." <Br> ");
        }
$ CommonUtil = new CommonUtil ();
Ksort ($ this-> parameters );
$ UnSignParaString = $ commonUtil-> formatQueryParaMap ($ this-> parameters, false );
$ Md5SignUtil = new MD5SignUtil ();
Return $ md5SignUtil-> sign ($ unSignParaString, $ commonUtil-> trimString (PARTNERKEY ));
} Catch (SDKRuntimeException $ e)
    {
Die ($ e-> errorMessage ());
    }
 
}
CURL request and certificate sending:

Function curl_post_ssl ($ url, $ vars, $ second = 30, $ aHeader = array ())
{
$ Ch = curl_init ();
// Timeout
Curl_setopt ($ ch, CURLOPT_TIMEOUT, $ second );
Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1 );
// Set proxy here, if any
Curl_setopt ($ ch, CURLOPT_URL, $ url );
Curl_setopt ($ ch, CURLOPT_SSL_VERIFYPEER, false );
Curl_setopt ($ ch, CURLOPT_SSL_VERIFYHOST, false );
// Cert and key belong to two. pem files respectively.
// Make sure that your libcurl version supports two-way authentication. The version is later than 7.20.1
Curl_setopt ($ ch, CURLOPT_SSLCERT, dirname (_ FILE _). DIRECTORY_SEPARATOR. 'Zhengshu '. DIRECTORY_SEPARATOR. 'Apiclient _ cert. Pem ');
Curl_setopt ($ ch, CURLOPT_SSLKEY, dirname (_ FILE _). DIRECTORY_SEPARATOR. 'Zhengshu '. DIRECTORY_SEPARATOR. 'Apiclient _ key. Pem ');
Curl_setopt ($ ch, CURLOPT_CAINFO, dirname (_ FILE _). DIRECTORY_SEPARATOR. 'Zhengshu '. DIRECTORY_SEPARATOR. 'Rootca. Pem ');
If (count ($ aHeader)> = 1 ){
Curl_setopt ($ ch, CURLOPT_HTTPHEADER, $ aHeader );
    }
Curl_setopt ($ ch, CURLOPT_POST, 1 );
Curl_setopt ($ ch, CURLOPT_POSTFIELDS, $ vars );
$ Data = curl_exec ($ ch );
If ($ data ){
Curl_close ($ ch );
Return $ data;
    }
Else {
$ Error = curl_errno ($ ch );
// Echo "call faild, errorCode: $ error \ n ";
Curl_close ($ ch );
Return false;
    }
}

Portal file:

 

@ Require "pay. php ";
// Obtain user information
$ Get = $ _ GET ['param'];
$ Code = $ _ GET ['code'];
// Determine whether the code exists
If ($ get = 'Access _ token '&&! Empty ($ code )){
$ Param ['param'] = 'Access _ token ';
$ Param ['code'] = $ code;
$ Packet = new Packet ();
// Obtain the user's openid
$ Userinfo = $ packet-> _ route ('userinfo', $ param );
If (empty ($ userinfo ['openid']) {
Exit ("NOAUTH ");
    }
// Retrieve the payment method
$ Packet-> _ route ('wxpacket ', array ('openid' => $ userinfo ['openid']);
} Else {
$ Packet-> _ route ('userinfo ');
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.