PHP micro-Letter Js-sdk Payment Interface Class Usage example _php tips

Source: Internet
Author: User
Tags cdata explode getmessage md5 openid php class sha1 urlencode

This article describes the PHP version of micro-letter Js-sdk Payment Interface class usage. Share to everyone for your reference, specific as follows:

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__) {//initialization of pay necessary information $pay = new WeChat Pay (Array (wechatpay::appid => ' wx99dabzpiuq83985b8 ', Wechatpay::appsercer => ' ac12e7e4abaer63hkoa0cc36a9663 FA ', Wechatpay::P artnerkey => ' bae4sfa3562rsfaq23s2045 ', Wechatpay::P artnerid => ' 1268969802 ', WechatPay ::P aysignkey => ' 9fqsxb3pk4ivocec4ycquy5zecs9leemjf2nn4b4ykooxpwaqdfwmezkt8onlbyawcut ', WechatPay::SIGNTYPE =
  > ' SHA1 ',);
  Set package 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 signed 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 ', A Ppsercer = ' Appsercer ', Paysignkey = ' Appkey ', Partnerid = ' Partnerid ', Partnerkey = ' Partnerkey ', Signtyp
  E = ' 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;
    The 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]; The Public Function SetParams ($param, $paramValue) {$this->params[commonutil::trimstring ($param)] = Commonutil::tr
  Imstring ($paramValue);
  The Public Function Getparams ($param) {return $this->params[$param]; } protected function Createnoncestr ($length =) {$chars = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz
    0123456789 ";
    $str = "";
    for ($i = 0; $i < $length; $i + +) {$str. = substr ($chars, Mt_rand (0, strlen ($chars)-1), 1);
  return $str; The Public Function Checkparams () {//required 9 signed parameters 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 * @params Initialize the class with the SetParams method to define the necessary 9 parameters * Sort the Format URL query form again Md5signutil class signature, and then to the URL * * prote cted 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 and 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 the entire payment process as the order number fills the public function createjsapipackage () {try {if ($this->checkpa Rams () = = 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 Shipping status Array three parameters OpenID TRANSID OrderID/Public Function Createdeliverpost (array $params) {$deli
    ver = 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, the response of the XML format * @params $retcode $reterrmsg Define the status of the product */Public Function createnativepackage ($retcode = 0, $reterrmsg = "OK") {try {if ($this->checkparams () = = False && $retcode = = 0) {//If it is normal to 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 Com MoNutil ();
    $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;
        /* * 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 exc Eption ("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 ()); The 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 custom static public function Createorderno () {$nonce = Commonutil::createnoncestr (4); Return Strtoupper (Date (' Ymds '). substr (Microtime (), 2,4). $nonce); }//random string static public function createnoncestr ($length =) {$chars = "abcdefghijklmnopqrstuvwxyzabcdefghijkl
    MNOPQRSTUVWXYZ0123456789 ";
    $str = "";
    for ($i = 0; $i < $length; $i + +) {$str. = substr ($chars, Mt_rand (0, strlen ($chars)-1), 1);
  return $str;
    The 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;
    The static function trimstring ($value) {$ret = null;
      if (null!= $value) {$ret = $value;
      if (strlen ($ret) = = 0) {$ret = null;
  } return $ret;
    The 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;
    The 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 an array of levels/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;

 }
}

For more information on PHP related content readers can view the site topics: "PHP micro-credit Development Skills summary", "PHP coding and transcoding Operation skills Summary", "PHP Network Programming Skills Summary", "PHP basic Grammar Introductory Course", "PHP string (String) Usage Summary", "php+ MySQL Database operations Introduction tutorial and PHP Common database operation Skills Summary

I hope this article will help you with the PHP program design.

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.