This article is mainly for you to introduce the PHP implementation of the payment of cash red envelopes, with a certain reference value, interested in small partners can refer to
Many of the online PHP payment access tutorials are quite complex, and need to configure and introduce more files, I through the collation of a single file version, I hope that you want to access to pay a little help and reference significance.
Run the file directly to send a cash red envelope to the specified user.
Things to keep in mind:
1. Cash red envelopes required to pass the certificate, need to go here Account Center--Account Settings->api security, download the certificate, and then modify the certificate path in the code
2. The default usage scenario is the lottery (that is, the scene_id parameter is product_2), the amount is 1-200 yuan, so the minimum amount to test is 1 yuan. Modify in product settings, cash red envelopes, product center, products
3. This file needs to be placed in the payment authorization directory and can be set up in the development configuration of the payment merchant platform, product center.
4. If prompt signature error can be verified by Payment Signature Verification tool: Public Platform payment Interface debugging tool
5. Error code reference: Address
The code is as follows:
<?php/** * Notes on cash red envelopes * 1. Cash Red envelopes required to pass the certificate, you need to https://pay.weixin.qq.com account Center--Account Settings->api Security--Download the certificate, The certificate path is modified in lines No. 214 and 217 * 2. The default usage scenario is a lottery (that is, the scene_id parameter is product_2), the amount is 1-200 yuan, so the minimum amount to test is 1 yuan. If you need to modify the product settings in cash red envelopes---Product center---Products, change * 3. Error code reference: https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php? Chapter=13_4&index=3 */header (' content-type:text/html; Charset=utf-8 '); $mchid = ' xxxxx '; Payment merchant number Partnerid through the payment of merchant information after the mail sent $appid = ' xxxxx '; Appid$appkey of the public number of the payment application = ' xxxxx '; App Key$apikey = ' xxxxx ' for the public number of the payment application; Https://pay.weixin.qq.com Account Settings-security settings-api Security-api key-Set API Key//①, get user OpenID for current access page (if sending red envelopes to a given user, fill in the specified user's OpenID) $ Wxpay = new Wxpayservice ($mchid, $appid, $appKey, $apiKey); $openId = $wxPay->getopenid (); Get Openidif (! $openId) exit (' Get openId failed ');//②, send red envelope $outtradeno = Uniqid (); Your own commodity order number $payamount = 1; Red Envelope amount, Unit: yuan $sendname = ' weave dream cat '; Red Envelope sender Name $wishing = ' Thank you for your participation in guessing lantern riddles and wish you a Happy Lantern Festival! '; Red Envelopes Blessing Language $act_name= ' guessing riddles to rob red envelopes activities '; Activity name $result = $wxPay->createjsbizpackage ($openId, $payAmount, $outTradeNo, $sendNaMe, $wishing, $act _name); Echo ' success '; class wxpayservice{protected $mchid; protected $appid; protected $appKey; protected $apiKey; public $data = null; Public function __construct ($mchid, $appid, $appKey, $key) {$this->mchid = $mchid; $this->appid = $appid; $this AppKey = $appKey; $this->apikey = $key; }/** * by jumping to get the user's OpenID, the jump process is as follows: * 1, set the URL you need to recall and other parameters, jump to server https://open.weixin.qq.com/connect/oauth2/authorize * 2, After the service processing is completed, it jumps back to the user Redirect_uri address, which takes some parameters, such as: code * @return The user's OpenID */Public Function Getopenid () {//code to get OpenID if (! Isset ($_get[' code ')) {//Trigger return code Code $SCHEME = $_server[' HTTPS ']== ' on '? ' https://': '/HTTP '; $BASEURL = UrlEncode ($scheme. $_server[' http_host '].$_server[' php_self '].$_server[' query_string ']); $url = $this->__createoauthurlforcode ($BASEURL); Header ("Location: $url"); Exit (); } else {//Get code to get OpenID $code = $_get[' code ']; $openid = $this->getopenidfrommp ($code); return $openid; }}/** * Get the OpenID machine from the work platform via code Access_token * @param string $code jump back on the band code * @return OpenID */Public Function GETOPENIDFROMMP ($code) {$url = $this->__create Oauthurlforopenid ($code); $res = Self::curlget ($url); Remove OpenID $data = Json_decode ($res, true); $this->data = $data; $openid = $data [' OpenID ']; return $openid; }/** * Constructs get open and Access_toke URL address * @param string $code, jump back to code * @return Request URL */Private function __createoauthurlfo Ropenid ($code) {$URLOBJ ["appid"] = $this->appid; $urlObj ["secret"] = $this->appkey; $urlObj ["code"] = $code; $urlO bj["Grant_type"] = "Authorization_code"; $bizString = $this->tourlparams ($URLOBJ); Return "Https://api.weixin.qq.com/sns/oauth2/access_token?". $bizString; }/** * construct gets the URL of code connection * @param string $redirectUrl The URL of the server to jump back, need URL encoding * @return return the constructed URL */Private function __createoaut Hurlforcode ($REDIRECTURL) {$URLOBJ ["appid"] = $this->appid; $urlObj ["redirect_uri"] = "$REDIRECTURL"; $URLOBJ [" Response_type "] =" code "; $URLOBJ ["scope"] = "snsapi_base"; $URLOBJ ["state"] = "State". " #wechat_redirect "; $bizString = $this->tourlparams ($URLOBJ); Return "Https://open.weixin.qq.com/connect/oauth2/authorize?". $bizString; }/** * Stitching signature String * @param array $URLOBJ * @return return the string that has been stitched up */Private Function Tourlparams ($URLOBJ) {$buff = ""; foreach ($urlObj as $k = + $v) {if ($k! = "sign") $buff. = $k. "=" . $v. "&"; } $buff = Trim ($buff, "&"); return $buff; /** * Send Red envelopes * @param string $openid user OpenID * @param float $totalFee red envelope amount in the public number * @param string $outTradeNo order number * @ param string $orderName Red envelope Sender name * @param string $wishing Blessing * @param string $actName Interactive name * @return String */public func tion Createjsbizpackage ($openid, $totalFee, $outTradeNo, $sendName, $wishing, $actName) {$config = array (' mch_id ' = = $ This->mchid, ' appid ' = $this->appid, ' key ' and ' = ' $this->apikey, '); $unified = Array (' wxappid ' = = $config [' AppID '], ' send_name ' + $sendName, ' mch_id ' = = $config [' mch_id '], ' no Nce_str ' = Self::createnoncEstr (), ' Re_openid ' + $openid, ' Mch_billno ' and $outTradeNo, ' client_ip ' = ' 127.0.0.1 ', ' total_amount ' = Intval ($totalFee * 100),//unit to Sub ' total_num ' =>1,///////The total number of red envelopes issued ' wishing ' + $wishing,//Red envelopes Blessing words ' act_name ' and $actN AME,//Activity name ' remark ' + ' remark ',//notes information, such as for the Chinese attention to UTF8 encoded ' scene_id ' = ' product_2 ',//Issued red envelopes use the scene, red envelope amount greater than 200 must pass. HTTPS://PAY.WEIXIN.QQ.COM/WIKI/DOC/API/TOOLS/CASH_COUPON.PHP?CHAPTER=13_4&INDEX=3); $unified [' sign '] = Self::getsign ($unified, $config [' key ']); $RESPONSEXML = $this->curlpost (' Https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack ', self::arraytoxml ($unified)); $unifiedOrder = simplexml_load_string ($responseXml, ' simplexmlelement ', libxml_nocdata); if ($unifiedOrder = = = False) {die (' Parse XML error ');} if ($unifiedOrder->return_code! = ' SUCCESS ') {die ($unifiedO RDER->RETURN_MSG); } if ($unifiedOrder->result_code! = ' SUCCESS ') {die ($unifiedOrder->err_code);} return true; } public static function Curlget ($url = ', $options = Array ()) {$ch = Curl_init ($url); curl_setopt ($ch, Curlopt_returntransfer, 1); curl_setopt ($ch, Curlo Pt_timeout, 30); if (!empty ($options)) {Curl_setopt_array ($ch, $options);}//https request not to validate certificate and host curl_setopt ($ch, Curlopt_ssl_ Verifypeer, false); curl_setopt ($ch, Curlopt_ssl_verifyhost, false); $data = curl_exec ($ch); Curl_close ($ch); return $data; Public Function curlpost ($url = ", $postData =", $options = Array ()) {if (Is_array ($postData)) {$postData = Http_b Uild_query ($postData); } $ch = Curl_init (); curl_setopt ($ch, Curlopt_url, $url); curl_setopt ($ch, Curlopt_returntransfer, 1); curl_setopt ($ch, Curlopt_post, 1); curl_setopt ($ch, Curlopt_postfields, $postData); curl_setopt ($ch, Curlopt_timeout, 30); Sets the maximum number of seconds that curl is allowed to execute if (!empty ($options)) {Curl_setopt_array ($ch, $options)}//https request not to validate the certificate and host curl_setopt ($ch, Curl Opt_ssl_verifypeer, false); curl_setopt ($ch, Curlopt_ssl_verifyhost, false); The first method, cert and key, belongs to two. Pem files//The default format is PEM and can be commented Curl_setoPT ($ch, Curlopt_sslcerttype, ' PEM '); curl_setopt ($ch, CURLOPT_SSLCERT,GETCWD (). ' /cert/apiclient_cert.pem '); The default format is PEM, which can be annotated with curl_setopt ($ch, Curlopt_sslkeytype, ' PEM '); curl_setopt ($ch, CURLOPT_SSLKEY,GETCWD (). ' /cert/apiclient_key.pem '); The second way, two files to synthesize a. pem File//curl_setopt ($ch, CURLOPT_SSLCERT,GETCWD (). ' /all.pem '); $data = curl_exec ($ch); Curl_close ($ch); return $data; public static function Createnoncestr ($length = +) {$chars = ' abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 '; $str = "; for ($i = 0; $i < $length; $i + +) {$str. = substr ($chars, Mt_rand (0, strlen ($chars)-1), 1);} return $str; The public static function Arraytoxml ($arr) {$xml = "<xml>"; foreach ($arr as $key = = $val) {if (Is_numeric ($val ) {$xml. = "<". $key. ">". $val. "</". $key. ">"; } else $xml. = "<". $key. "><! [cdata[]. $val. "]]></". $key. ">"; } $xml. = "</xml>"; return $xml; } public static function Getsign ($params, $key) {Ksort($params, sort_string); $unSignParaString = Self::formatqueryparamap ($params, false); $SIGNSTR = Strtoupper (MD5 ($unSignParaString. "&key=". $key)); return $signStr; } protected static function Formatqueryparamap ($paraMap, $urlEncode = False) {$buff = ""; Ksort ($PARAMAP); foreach ($paraMap as $k = + $v) {if (null! = $v && "null"! = $v) {if ($urlEncode) {$v = UrlEncode ($v); } $buff. = $k. "=" . $v. "&"; }} $reqPar = '; if (strlen ($buff) > 0) {$reqPar = substr ($buff, 0, strlen ($buff)-1);} return $reqPar; }}?>
The above is the whole content of this article, thank you for reading. Read more about topic.alibabacloud.com!