PHP realizes WeChat native payment (scan code payment) function

Source: Internet
Author: User
Tags cdata urlencode
This article is mainly for everyone to introduce the PHP implementation of the native payment, scan code payment function, with a certain reference value, interested in small partners can refer to

Many of the online PHP scan code payment Access tutorials are quite complex, and need to configure and introduce more files, I have a single file through the collation of the version, only 200 lines of code, I hope that you want to access the scan code to pay a little help and reference significance.

Run the file directly to get a picture of the payment QR code.

Things to keep in mind:

1. 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.
2. If prompt signature error can be verified by Payment Signature Verification tool: Public Platform payment Interface debugging tool

The code is as follows:

<?phpheader (' 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 ';  Public number AppID through the payment of merchant data after the mail sent $apikey = ' xxxxx '; Https://pay.weixin.qq.com Account Settings-security settings-api Security-api key-Set API Key $wxpay = new Wxpayservice ($mchid, $appid, $apiKey); $   Outtradeno = Uniqid ();     Your own commodity order number $payamount = 0.01;  Payment amount, Unit: yuan $ordername = ' payment test ';   Order title $notifyurl = ' https://www.xxx.com/wx/';   Callback address after successful payment (do not have a question mark) $payTime = time (); Payment Time $arr = $wxPay->createjsbizpackage ($payAmount, $outTradeNo, $orderName, $NOTIFYURL, $payTime);//Generate two-dimensional code, \ n = ' Http://qr.liantu.com/api.php?text= '. $arr [' Code_url '];echo '  "; class wxpayservice{protected $mchid;  protected $appid;  protected $apiKey;    Public function __construct ($mchid, $appid, $key) {$this->mchid = $mchid;    $this->appid = $appid;  $this->apikey = $key; * * * * * * * * * * * * @param float $totalFee The total cost of payment unit * @param string $outTradeNo Unique order number * @param/** String $orderName Order name * @param string $NOTIFYURL payment result notification URL do not have a question mark * @param string $timestamp order initiation time * @return Array */Public Function createjsbizpackage ($totalFee, $outTradeNo, $orderName, $NOTIFYURL, $timestamp) {$config = Arra    Y (' mch_id ' = = $this->mchid, ' appid ' = $this->appid, ' key ' = $this->apikey,);    $orderName = Iconv (' GBK ', ' UTF-8 ', $orderName);      $unified = Array (' appid ' = = $config [' AppID '], ' attach ' = ' pay ',//merchant packet, return as is, if you fill in Chinese, please note that convert to Utf-8 ' Body ' = $orderName, ' mch_id ' + $config [' mch_id '], ' nonce_str ' = Self::createnoncestr (), ' No Tify_url ' + $notifyUrl, ' out_trade_no ' + $outTradeNo, ' spbill_create_ip ' = ' 127.0.0.1 ', ' Total_    Fee ' + intval ($totalFee * 100),//unit to sub ' trade_type ' = ' NATIVE ',);    $unified [' sign '] = Self::getsign ($unified, $config [' key ']); $RESPONSEXML = Self::curlpost (' Https://api.mch.weixin.qq.com/pay/unIfiedorder ', Self::arraytoxml ($unified));    $unifiedOrder = simplexml_load_string ($responseXml, ' simplexmlelement ', libxml_nocdata);    if ($unifiedOrder = = = False) {die (' Parse XML error ');    } if ($unifiedOrder->return_code! = ' SUCCESS ') {die ($unifiedOrder->return_msg);    } if ($unifiedOrder->result_code! = ' SUCCESS ') {die ($unifiedOrder->err_code);    } $CODEURL = (array) ($unifiedOrder->code_url);    if (! $CODEURL [0]) exit (' Get code_url error '); $arr = Array ("appId" + = $config [' appId '], "timeStamp" + $timestamp, "Noncestr" and Self::createno Ncestr (), "package" = "prepay_id=".    $unifiedOrder->prepay_id, "signtype" = ' MD5 ', "code_url" and "= $CODEURL [0],);    $arr [' paysign '] = self::getsign ($arr, $config [' key ']);  return $arr; The Public Function notify () {$config = array (' mch_id ' = = $this->mchid, ' appid ' = = $this->appid  , ' key ' = $this->apikey,  );    $POSTSTR = $GLOBALS ["Http_raw_post_data"];    $POSTOBJ = simplexml_load_string ($postStr, ' simplexmlelement ', libxml_nocdata);    if ($POSTOBJ = = = False) {die (' Parse XML error ');    } if ($postObj->return_code! = ' SUCCESS ') {die ($postObj->return_msg);    } if ($postObj->result_code! = ' SUCCESS ') {die ($postObj->err_code);    } $arr = (array) $postObj;    unset ($arr [' sign ']); if (Self::getsign ($arr, $config [' key ']) = = = $postObj->sign) {echo ' <xml><return_code><![ cdata[success]]></return_code><return_msg><!      [cdata[ok]]></return_msg></xml> ';    return $POSTOBJ;  }}/** * Curl Get * * @param string $url * @param array $options * @return Mixed */public static function    Curlget ($url = ", $options = Array ()) {$ch = Curl_init ($url);    curl_setopt ($ch, Curlopt_returntransfer, 1);    curl_setopt ($ch, Curlopt_timeout, 30); if (!empty ($options)) {Curl_setopt_arrAy ($ch, $options);    }//https request does not validate the 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; The public static function curlpost ($url = ", $postData =", $options = Array ()) {if (Is_array ($postData)) {$p    Ostdata = Http_build_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 allows to execute if (!empty ($options)) {Curl_setopt_array ($ch, $options);    }//https request does not validate the 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 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;    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;    }/** * Get signature */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!

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.