In this paper, we describe the algorithm of red envelopes implemented by PHP. Share to everyone for your reference. Specific as follows:
Specific code:
<?php/** * Red Envelope class * */class Wxhongbao {private $mch _id = "111111";//Merchant ID Write dead Private $wxappid = "22222222";//public number, write dead Private $client _ip = "119.29.80.114"; Call the host IP of the Red envelope interface, the server IP, write dead, that is, the script file is located in the IP private $apikey = "33333333";//pay's secret key value private $total _num = 1;//The number of people issued. Fixed value 1, cannot modify private $nick _name = "Product Center public number"; Red Envelope merchant Name Private $send _name = "Product Center public number";//the name of the red envelope issuer private $wishing = "blessing language"; Private $act _name = "red envelope activity"; Activity name Private $remark = "Activity notes"; Private $nonce _str = ""; Private $mch _billno = ""; Private $re _openid = "";//the recipient's OpenID private $total _amount = 1;//red envelope amount, Unit private $min _value = 1;//Minimum Amount private $ma X_value = 1; According to the interface requirements, the above 3 values must be consistent private $sign = ""; The signature generates a private $amt _type on send; The split red envelope parameter, defined in Sendgroup, is a constant All_rand//certificate, defined in the constructor, note! Private $apiclient _cert; = GETCWD (). " /apiclient_cert.pem "; Private $apiclient _key;//= GETCWD (). " /apiclient_key.pem "; Share parameter private $isShare = FALSE; Useful? It seems to be a useless parameter, all of which are not required and interdependent parameters private $share _content= ""; Private $share _url = ""; Private $share _imgurl = ""; Private $WXHB _inited; Private $api _hb_group = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendgroupredpack";//fission Red envelopes private $api _hb_ Single = "Https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack"; Private $error = "OK"; Init/** * WXHONGBAO::__CONSTRUCT () * Step * NEW (OPENID,AMOUNT) * setnickname * setsend_name * setwishing * Setact_name * Setremark * Send () * @return void */function __construct () {//There seems to be nothing to do with the constructor $this->WX hb_inited = false; $this->apiclient_cert = GETCWD (). " /apiclient_cert.pem "; $this->apiclient_key = GETCWD (). " /apiclient_key.pem "; } Public Function err () {return $this->error; Public Function error () {return $this->err (); }/** * WXHONGBAO::NEWHB () * Constructs a new red envelope * @param mixed $toOpenId * @param mixed $amount amount * @return void * * PU Blic function NEWHB ($toOpenId, $amount) {if (!is_numeric ($amount)) { $this->error = "wrong amount parameter"; Return }elseif ($amount <100) {$this->error = "The amount is too small"; Return }elseif ($amount >20000) {$this->error = "Amount is too large"; Return } $this->gen_nonce_str ();//construct random string $this->gen_mch_billno ();//construct Order number $this->setopenid ($toOpenId); $this->setamount ($amount); $this->wxhb_inited = true; Flag red packets have been initialized to send//each new will be the content of the share to be emptied out, otherwise there will be a residual reference $this->share_content= ""; $this->share_imgurl = ""; $this->share_url = ""; }/** * Wxhongbao::send () * Send red Envelopes * Construct Signature * Note the second parameter, do not change the single time! * @return Boolean $success */Public Function send ($url = "Https://api.mch.weixin.qq.com/mmpaymkttransfer S/sendredpack ", $total _num = 1) {if (! $this->wxhb_inited) {$this->error. =" (red packets not Ready) "; return false; Uninitialized completion} $this->total_num = $total _num; $this->gen_sign (); Generate signature//construct submitted data $xml = $this->genxmlparam (); //Debug File_put_contents ("Hbxml.txt", $xml); Submit Xml,curl//$url = "Https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack"; $ch = Curl_init (); curl_setopt ($ch, curlopt_timeout,10); curl_setopt ($ch, Curlopt_returntransfer, 1); curl_setopt ($ch, Curlopt_url, $url); curl_setopt ($ch, Curlopt_ssl_verifypeer,false); curl_setopt ($ch, Curlopt_ssl_verifyhost,false); curl_setopt ($ch, Curlopt_sslcerttype, ' PEM '); curl_setopt ($ch, Curlopt_sslcert, $this->apiclient_cert); curl_setopt ($ch, Curlopt_sslkeytype, ' PEM '); curl_setopt ($ch, Curlopt_sslkey, $this->apiclient_key); /* if (count ($aHeader) >= 1) {curl_setopt ($ch, Curlopt_httpheader, $aHeader); } */curl_setopt ($ch, Curlopt_post, 1); curl_setopt ($ch, Curlopt_postfields, $xml); $data = curl_exec ($ch); if ($data) {curl_close ($ch); $rsxml = simplexml_load_string ($data); if ($rsxml->return_code = = ' SUCCESS ') {return true; }else{$this->error = $rsxml->return_msg; return false; }}else{$this->error = Curl_errno ($ch); Curl_close ($ch); return false; }}/** * Wxhongbao::sendgroup () * Send a fission red envelope with a parameter of fission quantity * @param integer $num 3-20 * @return */Public function S Endgroup ($num =3) {$this->amt_type = "All_rand";//$amt; fixed value. Send a fissile red envelope group document specifying parameters, random return $this->send ($this->api_hb_group, $num); } public Function Getapisingle () {return $this->api_hb_single; } public Function Getapigroup () {return $this->api_hb_group; The Public Function Setnickname ($nick) {$this->nick_name = $nick; The Public Function Setsendname ($name) {$this->send_name = $name; The Public Function setwishing ($wishing) {$this->wishing = $wishing; }/** * Wxhongbao::setactname () * Activity name * @param mixed $act * @return void */Public function setactname ($AC T) {$this->act_name = $act; } Public Function SetreMark ($remark) {$this->remark = $remark; The Public Function Setopenid ($openid) {$this->re_openid = $openid; }/** * Wxhongbao::setamount () * Set RED envelope amount * Document has two conflicting descriptions * One refers to the amount of money >=1 (cent) * Another means the amount >=100 < 20000 [1-200 yuan ] * Pending test verification! * @param mixed $price Unit sub * @return void */Public Function Setamount ($price) {$this->total_amount = $price; $this->min_value = $price; $this->max_value = $price; The Public Function Sethbminmax ($min, $max) {$this->min_value = $min is used for setting up the split red envelope}//following method; $this->max_value = $max; Public Function setshare ($img = "", $url = "", $content = "") {//https://mmbiz.qlogo.cn/mmbiz/ms1jado92ep4qno9ev0rni Tptybrzuhjqt8oxsscofdxibnnwmjiabaqglpkdaejmia6fqtxaxulkba9nlfxymwya/0?wx_fmt=png//http://mp.weixin.qq.com/s?__ Biz=mza5njg4ntk3ma==&mid=206257621&idx=1&sn=56241da30e384e40771065051e4aa6a8#rd $this->share_ Content = $content; $this->share_imgurl = $img; $this->share_url =$url; } Private Function Gen_nonce_str () {$this->nonce_str = Strtoupper (MD5 (Mt_rand (). Time ()));//Make sure not to repeat} private function Gen_sign () {unset ($param); You should actually rearrange right with key? $param ["Act_name"]= $this->act_name;//if ($this->total_num==1) {//These are parameters that are not used for a fissile red envelope, resulting in a signature error $param ["Client_ip "]= $this->client_ip; $param ["Max_value"]= $this->max_value; $param ["Min_value"]= $this->min_value; $param ["Nick_name"]= $this->nick_name; } $param ["Mch_billno"] = $this->mch_billno; $param ["mch_id"]= $this->mch_id;//$param ["Nonce_str"]= $this->nonce_str; $param ["Re_openid"]= $this->re_openid;//$param ["Remark"]= $this->remark; $param ["Send_name"]= $this->send_name;//$param ["Total_amount"]= $this->total_amount;//$param ["Total_num" ]= $this->total_num; $param ["Wishing"]= $this->wishing;//$param ["Wxappid"]= $this->wxappid;//if ($this->share_content) $param["share_content"] = $this->share_content; if ($this->share_imgurl) $param ["share_imgurl"] = $this->share_imgurl; if ($this->share_url) $param ["share_url"] = $this->share_url; if ($this->amt_type) $param ["amt_type"] = $this->amt_type; Ksort ($param); Sort by Key name ... 艹, I've been in line for a long time//$sign _raw = Http_build_query ($param). " &key= ". $this->apikey; $sign _raw = ""; foreach ($param as $k = + $v) {$sign _raw. = $k. " = ". $v." & "; } $sign _raw. = "key=". $this->apikey; File_put_contents ("Sign.raw", $sign _raw),//debug $this->sign = Strtoupper (MD5 ($sign _raw)); }/** * Wxhongbao::genxmlparam () * Generate post Parameters XML packet * Note that before generating the values to be generated, especially sign * @return $xml */Public function Genxmlparam () {$xml = "
". $this->sign."
". $this->mch_billno."
". $this->mch_id."
". $this->wxappid."
".$this-> nick_name. "] >
</nick_name>
".$this-> send_name. "] >
</send_name>
". $this->re_openid."
". $this->total_amount."
". $this->min_value."
". $this->max_value."
". $this->total_num."
".$this-> wishing. "] >
</wishing>
".$this-> client_ip. "] >
</client_ip>
<![CDATA[".$this->act_name. "] >
".$this-> remark. "] >
</remark>
". $this->nonce_str."
"; if ($this->share_content) $xml. = "
".$this-> share_content. "] >
</share_content>
"; if ($this->share_imgurl) $xml. = "
".$this-> share_imgurl. "] >
</share_imgurl>
"; if ($this->share_url) $xml. = "
".$this-> share_url. "] >
</share_url>
"; if ($this->amt_type) $xml. = "<![CDATA[".$this->amt_type. "] >"; $xml. = "
"; return $xml; }/** * Wxhongbao::gen_mch_billno () * Merchant Order number (each order number must be unique) consists of a number that cannot be duplicated in the mch_id+yyyymmdd+10 bit of the day. The interface supports re-entry based on merchant order numbers, which can be recalled if a timeout occurs. * @return void */Private Function Gen_mch_billno () {//generates a length of 10, the Arabic numeral random string $rnd _num = Array (' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 '); $rndstr = ""; while (strlen ($RNDSTR) <10) {$rndstr. = $rnd _num[array_rand ($rnd _num)]; } $this->mch_billno = $this->mch_id.date ("Ymd"). $rndstr; }}?> then instantiate class. $toOpenId = ' ASDASDASD '; OpenID $HB for users receiving red envelopes = new Wxhongbao (); $HB->NEWHB ($toOpenId, 1000); Create a new 10-yuan red envelope, the second parameter unit is divided, note the value range of 1-200 yuan//Below a number of optional operations, do not specify the class script at the top of the default value $HB->setnickname ("Local Tyrants Limited"); $HB->setsendname ("Local tyrants"); $HB->setwishing ("Congratulations on Fortune"); $HB->setactname ("money-sending activities"); $HB->setremark ("Wayward One"); Send red envelopes if (! $HB->send ()) {//Send error echo $HB->err (); }else{echo "Red envelope sent successfully"; }
I hope this article is helpful to everyone's PHP programming.