Php WeChat js-sdk payment Interface Class usage example, js-sdk example

Source: Internet
Author: User
Tags get ip openid

Php js-sdk payment Interface Class usage example, js-sdk example

This example describes the usage of the php js-sdk payment interface class. We will share this with you for your reference. The details are as follows:

This payment class is modified according to the official document! It mainly generates js api, Native package signature package, and Native response XML format data. The comments indicate the intention of each method. Because the package signature is slightly complicated, it takes more time to compare it with the log files! Of course, as long as you use the tutorial class and set the corresponding parameters, you can generate the package parameters correctly.

<? Phpif (isset ($ argc) & $ argc> = 1 & $ argv [0] = _ FILE __) {// required information for initial pay $ pay = new WechatPay (array (WechatPay: APPID => 'wx99dabzpiuq83985b8', WechatPay: APPSERCER => 'hangzhou', WechatPay :: PARTNERKEY => 'bae4sfa3562rsfaq23s2045', WechatPay ',)); // set the required package parameters for jsapi native $ pay-> setParams (WechatPay: BANK_TYPE, "WX"); $ pay-> setParams (WechatPay: BODY, "test"); $ pay-> setParams (WechatPay: PARTNER, $ pay-> partnerid); $ pay-> setParams (WechatPay: OUT_TRADE_NO, commonUtil :: createNoncestr (); $ pay-> setParams (WechatPay: total_timeout, "1"); $ pay-> setParams (WechatPay: FEE_TYPE, "1 "); $ pay-> setParams (WechatPay: TIMESTAMP, time (); $ pay-> setParams (WechatPay: yy_url, "http://www.demo.com/notify"); $ pay-> setParams (WechatPay:: SPBILL_CREATE_IP, "127.0.0.1"); $ pay-> setParams (WechatPay: INPUT_CHARSET, "UTF-8 "); // JSAPI signature json print_r ($ pay-> createJsApiPackage (); // generate native XML print_r ($ pay-> createNativePackage ()); // generate native URL print_r ($ pay-> createNativeUrl ("9701 "));}

Parameters of the package signature package generated by js api:

{  "appId":"wx9998ff5f4dede5b7",  "package":"bank_type=WX&body=test&fee_type=1&input_charset=UTF-8&notify_url=http%3A%2F%2Fwww.demo.com%2Fnotify&out_trade_no=Vf5qsSwtu0hc2loH&partner=wx9998ff5f4dede5b7&spbill_create_ip=127.0.0.1&timestamp=1409295711&total_fee=1&sign=FEE0167BD0D89A88BF6850590EA889B6",  "timeStamp":1409295711,  "nonceStr":"Vf5qsSwtu0hc2loH",  "paySign":"f816264c750923863c370a1739640244b0c2d39c",  "signType":"sha1"}

XML format of Native response:

<xml>  <AppId><![CDATA[wx9998ff5f4dede5b7]]></AppId>  <Package>    <![CDATA[bank_type=WX&body=test&fee_type=1&input_charset=UTF-8&notify_url=http%3A%2F%2Fwww.demo.com%2Fnotify&out_trade_no=GDl3what4sALDEAd&partner=wx9998ff5f4dede5b7&spbill_create_ip=127.0.0.1&timestamp=1409296124&total_fee=1&sign=BF949B85570644B939B369FD44B0C4A9]]>  </Package>  <TimeStamp>1409296124</TimeStamp>  <NonceStr><![CDATA[GDl3what4sALDEAd]]></NonceStr>  <RetCode>0</RetCode>  <RetErrMsg><![CDATA[ok]]></RetErrMsg>  <AppSignature><![CDATA[ca4a2467b817a62c38a9801fcf451f51692027bf]]></AppSignature>  <SignMethod><![CDATA[sha1]]></SignMethod></xml>

Native URL:

Weixin: // wxpay/bizpayurl? Appid = wx9998ff5f4de5b7 & noncestr = VY7cVA6mtVrc1BVq & productid = 9701 & sign = signature & timestamp = 1409296323

Either way, we need to use setParams to set the required initialization parameters and product prices and statuses!

WechatPay class:

<? Phpclass WechatPay {const BANK_TYPE = 'Bank _ type', BODY = 'body', PARTNER = 'passer', OUT_TRADE_NO = 'out _ trade_no ', TIMESTAMP = 'timestamp ', total_character = 'total _ charset', FEE_TYPE = 'your _ type', yy_url = 'your Y _ url', SPBILL_CREATE_IP = 'spbill _ create_ip', INPUT_CHARSET = 'input _ charset ', APPID = 'appid ', APPSERCER = 'appsercer', PAYSIGNKEY = 'appkey', PARTNERID = 'ererid', PARTNERKEY = 'partne Rkey', SIGNTYPE = 'signtype'; public $ params = array (), $ partnerid = ''; static protected $ _ instance; protected $ _ appid, $ _ appkey, $ _ signtype, $ _ partnerkey, $ _ appsercer; static public function getInstance (array $ options = array () {if (empty (self: $ _ instance )) {self: $ _ instance = new self ($ options);} return self: $ _ instance;} public function _ construct (array $ options = array ()) {$ this-> _ appi D = $ options [self: APPID]; $ this-> _ appkey = $ options [self: PAYSIGNKEY]; $ this-> _ signtype = $ options [self :: SIGNTYPE]; $ this-> _ partnerkey = $ options [self: PARTNERKEY]; $ this-> _ appsercer = $ options [self: APPSERCER]; $ this-> partnerid = $ options [self: APPID];} public function setParams ($ param, $ paramValue) {$ this-> params [CommonUtil :: trimString ($ param)] = CommonUtil: trimString ($ paramValue);} public Function getParams ($ param) {return $ this-> params [$ param];} protected function createNoncestr ($ length = 16) {$ chars = "Callback "; $ str = ""; for ($ I = 0; $ I <$ length; $ I ++) {$ str. = substr ($ chars, mt_rand (0, strlen ($ chars)-1), 1) ;}return $ str ;} public function checkParams () {// nine required signature parameters, if ($ this-> params [self: BANK_TYPE] = null | $ This-> params [self: BODY] = null | $ this-> params [self: PARTNER] = null | $ this-> params [self :: OUT_TRADE_NO] = null | $ this-> params [self: total_rows] = null | $ this-> params [self :: FEE_TYPE] = null | $ this-> params [self: policy_url] = null | $ this-> params [self :: SPBILL_CREATE_IP] = null | $ this-> params [self: INPUT_CHARSET] = null) {return false;} return true;}/** generate a package * @ params When initializing the class, use the setParams method to define the nine required parameters * after sorting, format the url query Form, and then use the md5SignUtil class signature, and then combine the URL */protected function getPackageSign () {try {if (null ==$ this-> _ partnerkey | "" ==$ this-> _ partnerkey) {throw new Exception ("the key cannot be blank! ". "<Br>") ;}$ commonUtil = new CommonUtil (); ksort ($ this-> params); $ unSignParaString = $ commonUtil-> formatUrlQuery ($ this-> params, false); $ paraString = $ commonUtil-> formatUrlQuery ($ this-> params, true); $ md5SignUtil = new MD5SignUtil (); return $ paraString. "& sign = ". $ md5SignUtil-> sign ($ unSignParaString, commonUtil: trimString ($ this-> _ partnerkey);} catch (Exception $ e) {echo ($ e-> getMessage ()); }/** Signature generation method * @ params appid appkey package timestamp noncestr and other parameters. In the native example code, add the retcode reterrmsg parameters */public function getPaySign ($ signObj) {foreach ($ signObj as $ k => $ v) {$ signParams [strtolower ($ k)] = $ v ;} try {if ($ this-> _ appkey = "") {throw new Exception ("APPKEY is blank! ". "<Br>") ;}$ signParams ["appkey"] = $ this-> _ appkey; ksort ($ signParams, SORT_STRING); $ commonUtil = new CommonUtil (); $ signString = $ commonUtil-> formatPayUrlQuery ($ signParams, false); return sha1 ($ signString);} catch (Exception $ e) {echo ($ e-> getMessage () ;}// js api signature where nonceStr is used as the order number for filling the entire payment process public function createJsApiPackage () {try {if ($ this-> checkParams () = false) {throw new Ti On ("generating package parameters missing! ". "<Br>") ;}$ payObj ["appId"] = $ this-> _ appid; $ payObj ["package"] = $ this-> getPackageSign (); $ payObj ["timeStamp"] = $ this-> getParams (self: TIMESTAMP); $ payObj ["nonceStr"] = $ this-> getParams (self: OUT_TRADE_NO ); $ payObj ["paySign"] = $ this-> getPaySign ($ payObj); $ payObj ["signType"] = $ this-> _ signtype; return json_encode ($ payObj);} catch (Exception $ e) {die ($ e-> getMessage ();}/** build three major shipping status Arrays Parameter openid transid orderid */public function createDeliverPost (Array $ params) {$ deliver = array (); $ deliver ['appid '] = $ this-> _ appid; $ deliver ['openid'] = $ params ['openid']; $ deliver ['transid'] = $ params ['transid']; $ deliver ['out _ trade_no '] = $ params ['out _ trade_no']; $ deliver ['Deliver _ timestamp'] = current_time ('timestamp '); $ deliver ['Deliver _ status'] = 1; $ deliver ['Deliver _ msg '] =' OK '; $ deliver ['App _ signature '] = $ this-> getPaySign ($ deliver); $ deliver ['sign _ method'] = 'sha1'; return $ deliver ;} /** generate a scan or click the native URL. the XML format of the response * @ params $ retcode $ reterrmsg defines the status of the product */public function createNativePackage ($ retcode = 0, $ reterrmsg = "OK") {try {if ($ this-> checkParams () = false & $ retcode = 0) {// if the response is normal, check the caifu Tong parameter throw new Exception ("the generated package parameter is missing! ". "<Br>") ;}$ nativeObj ["AppId"] = $ this-> _ appid; $ nativeObj ["Package"] = $ this-> getPackageSign (); $ nativeObj ["TimeStamp"] = $ this-> getParams (self: TIMESTAMP); $ nativeObj ["NonceStr"] = $ this-> getParams (self: OUT_TRADE_NO ); $ nativeObj ["RetCode"] = $ retcode; $ nativeObj ["RetErrMsg"] = $ reterrmsg; $ nativeObj ["AppSignature"] = $ this-> getPaySign ($ nativeObj ); $ nativeObj ["SignMethod"] = $ this-> _ signtype; $ CommonUtil = new CommonUtil (); $ xml = $ commonUtil-> arrayToXml ($ nativeObj); exit ($ xml);} catch (Exception $ e) {echo ($ e-> getMessage () ;}/ ** generate a native URL with the order number as the parameter. This is the entire payment process */public function createNativeUrl ($ productid) {$ commonUtil = new CommonUtil (); $ nativeObj ["appid"] = $ this-> _ appid; $ nativeObj ["productid"] = urlencode ($ productid ); $ nativeObj ["timestamp"] = time (); $ nativeObj ["nonceStr"] = CommonUtil: createNoncestr (); $ nativeObj ["sign"] = $ this-> getPaySign ($ nativeObj); $ nativeString = $ commonUtil-> formatPayUrlQuery ($ nativeObj, false ); return "weixin: // wxpay/bizpayurl? ". $ NativeString;}/** get IP Address */public function getIp () {switch (true) {case! Empty ($ _ SERVER ["HTTP_CLIENT_IP"]): $ ip = $ _ SERVER ["HTTP_CLIENT_IP"]; break; case! Empty ($ _ SERVER ["HTTP_X_FORWARDED_FOR"]): $ ip = $ _ SERVER ["HTTP_X_FORWARDED_FOR"]; break; case! Empty ($ _ SERVER ["REMOTE_ADDR"]): $ ip = $ _ SERVER ["REMOTE_ADDR"]; break; default: $ ip = "127.0.0.1 ";} return $ ip ;}} class MD5SignUtil {public function sign ($ content, $ key) {try {if (null = $ key) {throw new Exception ("caifu Tong signature key cannot be blank! ". "<Br>");} if (null = $ content) {throw new Exception ("caifutong signature content cannot be blank ". "<br>") ;}$ signStr = $ content. "& key = ". $ key; return strtoupper (md5 ($ signStr);} catch (Exception $ e) {echo ($ e-> getMessage ());}} public static function verifySignature ($ content, $ sign, $ md5Key) {$ signStr = $ content. "& key = ". $ md5Key; $ calculateSign = strtolower (md5 ($ signStr); $ tenpaySign = strtolower ($ sign); retu Rn $ calculateSign ==$ tenpaySign;} class CommonUtil {public function genAllUrl ($ toURL, $ paras) {$ allUrl = null; if (null = $ toURL) {die ("toURL is null");} if (strripos ($ toURL ,"? ") =" ") {$ AllUrl = $ toURL ."? ". $ Paras;} else {$ allUrl = $ toURL. "&". $ paras;} return $ allUrl;} // order number, which can be customized according to the actual static public function createOrderNo () {$ nonce = CommonUtil: createNoncestr (4 ); return strtoupper (date ('ymds '). substr (microtime (), 2, 4 ). $ nonce);} // random string static public function createNoncestr ($ length = 16) {$ chars = "regular"; $ str = ""; for ($ I = 0; $ I <$ Length; $ I ++) {$ str. = substr ($ chars, mt_rand (0, strlen ($ chars)-1), 1) ;}return $ str ;} public function splitParaStr ($ src, $ token) {$ resMap = array (); $ items = explode ($ token, $ src); foreach ($ items as $ item) {$ paraAndValue = explode ("= ", $ item); if ($ paraAndValue! = "") {$ ResMap [$ paraAndValue [0] = $ paraAndValue [1] ;}return $ resMap;} static function trimString ($ value) {$ ret = null; if (null! = $ Value) {$ ret = $ value; if (strlen ($ ret) = 0) {$ ret = null ;}} return $ ret ;} public function formatUrlQuery ($ paraMap, $ urlencode) {$ buff = ""; ksort ($ paraMap, SORT_STRING); foreach ($ paraMap as $ k => $ v) {if (null! = $ V & "null "! = $ V & "sign "! = $ K) {if ($ urlencode) {$ v = urlencode ($ v);} $ buff. = $ k. "= ". $ v. "&" ;}}$ reqPar = ''; if (strlen ($ buff)> 0) {$ reqPar = substr ($ buff, 0, strlen ($ buff) -1);} return $ reqPar;} public function formatPayUrlQuery ($ paraMap, $ urlencode) {$ buff = ""; ksort ($ paraMap, SORT_STRING ); foreach ($ paraMap as $ k =>v v) {if ($ urlencode) {$ v = urlencode ($ v) ;}$ buff. = strtolower ($ k ). "= ". $ v. "&" ;}$ ReqPar = ''; if (strlen ($ buff)> 0) {$ reqPar = substr ($ buff, 0, strlen ($ buff)-1 );} return $ reqPar;}/** output xml format of the first-level array */public function arrayToXml ($ arr) {$ xml = "<xml> "; foreach ($ arr as $ key => $ val) {if ($ key = 'timestamp' | $ key = 'retcode') {$ xml. = "<". $ key. "> ". $ val. "</". $ key. ">";} else $ xml. = "<". $ key. "> <! [CDATA [". $ val. "]> </". $ key. ">" ;}$ xml. = "</xml>"; return $ xml ;}}

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.