PHP version Micro-JS-SDK Payment Interface Class Example

Source: Internet
Author: User
Tags foreach cdata explode getmessage md5 openid strlen urlencode

This payment class is based on official documentation changes! The main implementation of the generation of JS API, native package signature package and native response of the XML format data. Comments are marked with the intent of each method. Due to the package package signature, slightly complex, this should spend time to their own to see and log out of the file to one by one contrast! Of course, as long as you use the tutorial class, set the corresponding parameters can be the correct generation of package parameters, etc.
<?php
if (Isset ($ARGC) && $argc >= 1 && $argv [0] = = __file__) {
Necessary information to initialize pay
$pay = new Wechatpay (Array (
Wechatpay::appid => ' Wx99dabzpiuq83985b8 ',
Wechatpay::appsercer => ' Ac12e7e4abaer63hkoa0cc36a9663fa ',
Wechatpay::P artnerkey => ' bae4sfa3562rsfaq23s2045 ',
Wechatpay::P artnerid => ' 1268969802 ',
Wechatpay::P aysignkey => ' 9fqsxb3pk4ivocec4ycquy5zecs9leemjf2nn4b4ykooxpwaqdfwmezkt8onlbyawcut ',
Wechatpay::signtype => ' SHA1 ',
));
Set package the necessary parameters Jsapi native are universal
$pay->setparams (Wechatpay::bank_type, "WX");
$pay->setparams (wechatpay::body, "test");
$pay->setparams (wechatpay::P artner, $pay->partnerid);
$pay->setparams (Wechatpay::out_trade_no, Commonutil::createnoncestr ());
$pay->setparams (Wechatpay::total_fee, "1");
$pay->setparams (Wechatpay::fee_type, "1");
$pay->setparams (Wechatpay::timestamp, Time ());
$pay->setparams (Wechatpay::notify_url, "http://www.demo.com/notify");
$pay->setparams (wechatpay::spbill_create_ip, "127.0.0.1");
$pay->setparams (Wechatpay::input_charset, "UTF-8");

Jsapi's signature JSON
Print_r ($pay->createjsapipackage ());

Generate native XML
Print_r ($pay->createnativepackage ());

Generate native URL
Print_r ($pay->createnativeurl ("9701"));
}
JS API generated Package signature Package parameters:
{
"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 for Native responses:
<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>

URL link for native:
weixin://wxpay/bizpayurl?appid=wx9998ff5f4dede5b7&noncestr=vy7cva6mtvrc1bvq&productid=9701&sign= 43508b65b50e1d7e1089be66d55a709469155d73&timestamp=1409296323
Either way, we have to use SetParams to set the necessary initialization parameters and commodity prices and status!

Wechatpay class:
<?php
Class Wechatpay {
Const
Bank_type = ' Bank_type ',
BODY = ' body ',
PARTNER = ' PARTNER ',
Out_trade_no = ' Out_trade_no ',
TIMESTAMP = ' TIMESTAMP ',
Total_fee = ' Total_fee ',
Fee_type = ' Fee_type ',
Notify_url = ' Notify_url ',
spbill_create_ip = ' Spbill_create_ip ',
Input_charset = ' Input_charset ',
APPID = ' APPID ',
Appsercer = ' Appsercer ',
Paysignkey = ' Appkey ',
Partnerid = ' Partnerid ',
Partnerkey = ' Partnerkey ',
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->_appid = $options [Self::appid];
$this->_appkey = $options [self::P aysignkey];
$this->_signtype = $options [Self::signtype];
$this->_partnerkey = $options [self::P artnerkey];
$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 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$str = "";
for ($i = 0; $i < $length; $i + +) {
$str. = substr ($chars, Mt_rand (0, strlen ($chars)-1), 1);
}
return $str;
}

Public Function Checkparams () {
Required 9 parameters to participate in signature
if ($this->params[self::bank_type] = = NULL | | $this->params[self::body] = = NULL | | $this->params[self::P artner ] = = NULL | |
$this->params[self::out_trade_no] = = NULL | | $this->params[self::total_fee] = = NULL | | $this->params[self::fee_type] = = NULL | |
$this->params[self::notify_url] = = NULL | | $this-&GT;PARAMS[SELF::SPBILL_CREATE_IP] = = NULL | | $this->params[self::input_charset] = = NULL
) {
return false;
}
return true;
}

/*
* Generate Package Package
* Define the necessary 9 parameters with the SetParams method when initializing a class @params
* Sort after format URL query form again Md5signutil class signature, and then give the URL
*/
protected function getpackagesign () {
try {
if (null = = $this->_partnerkey | | "" = = $this->_partnerkey) {
throw new Exception ("Key cannot be empty!") " . " <br> ");
}
$commonUtil = new Commonutil ();
Ksort ($this->params);
$unSignParaString = $commonUtil->formaturlquery ($this->params, false);
$paraString = $commonUtil->formaturlquery ($this->params, true);
$MD 5SignUtil = new Md5signutil ();
Return $paraString. "&sign=". $MD 5signutil->sign ($unSignParaString, commonutil::trimstring ($this->_partnerkey));
catch (Exception $e) {
Echo ($e->getmessage ());
}
}

/*
* Generate Signature method
* @params AppID appkey package timestamp noncestr parameters native case code plus retcode reterrmsg two parameters
*/
Public Function Getpaysign ($SIGNOBJ) {
foreach ($signObj as $k => $v) {
$signParams [Strtolower ($k)] = $v;
}
try {
if ($this->_appkey = "") {
throw new Exception ("Appkey is empty!") " . " <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 an order number to fill the entire payment process
Public Function Createjsapipackage () {
try {
if ($this->checkparams () = = False) {
throw new Exception ("Generate Package parameter 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 the shipping status array three main parameters 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 on the native URL after the response of the XML format
* @params $retcode $reterrmsg Define the status of the item
*/
Public Function createnativepackage ($retcode = 0, $reterrmsg = "OK") {
try {
if ($this->checkparams () = = False && $retcode = = 0) {//If normal return, check Tenpay parameters
throw new Exception ("Generate Package parameter 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 native URL with order number as 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;
}

/*
* Take 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 ("Tenpay signature key cannot be empty!") " . " <br> ");
}
if (null = = $content) {
throw new Exception ("Tenpay signature content cannot be empty." "<br>");
}
$SIGNSTR = $content. "&key=". $key;
Return Strtoupper (MD5 ($SIGNSTR));
catch (Exception $e) {
Echo ($e->getmessage ());
}
}

public static function VerifySignature ($content, $sign, $md 5Key) {
$SIGNSTR = $content. "&key=". $MD 5Key;
$calculateSign = Strtolower (MD5 ($SIGNSTR));
$tenpaySign = Strtolower ($sign);
return $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, 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 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$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) {
if ($urlencode) {
$v = UrlEncode ($v);
}
$buff. = Strtolower ($k). "=" . $v. "&";
}
$reqPar = ';
if (strlen ($buff) > 0) {
$reqPar = substr ($buff, 0, strlen ($buff)-1);
}
return $reqPar;
}

/*
* Output the 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.