首頁 > 後端開發 > php教程 > php版微信js-sdk支付介面類別用法實例詳解

php版微信js-sdk支付介面類別用法實例詳解

墨辰丷
發布: 2023-03-28 20:40:02
原創
1945 人瀏覽過

這篇文章主要介紹了php版微信js-sdk支付接口類用法,結合實例形式分析了php版微信js-sdk支付接口類的定義與相關使用技巧,需要的朋友可以參考下

這個支付類別是根據官方的文件修改而來!主要實作產生JS API 、Native的package簽章包和Native回應的XML格式資料。註釋都標上了各方法的用意。由於package包簽名,略複雜,這個要自己多花時間去對應去看和log出文件來一一比較!當然只要用上教學的類,設定好對應的參數就可以正確的產生package參數等

#
<?php
if (isset($argc) && $argc >= 1 && $argv[0] == __FILE__) {
  //初始化pay的必要信息
  $pay = new WechatPay(array(
    WechatPay::APPID => &#39;wx99dabzpiuq83985b8&#39;,
    WechatPay::APPSERCER => &#39;ac12e7e4abaer63hkoa0cc36a9663fa&#39;,
    WechatPay::PARTNERKEY => &#39;bae4sfa3562rsfaq23s2045&#39;,
    WechatPay::PARTNERID => &#39;1268969802&#39;,
    WechatPay::PAYSIGNKEY => &#39;9Fqsxb3PK4IVOCEc4yCquy5zecS9LeeMjF2Nn4B4YKoOxPwaQdFwMezKT8oNlBYaWcuT&#39;,
    WechatPay::SIGNTYPE => &#39;sha1&#39;,
  ));
  //设置package 必要的参数 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_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的签名json
  print_r($pay->createJsApiPackage());
  //生成native XML
  print_r($pay->createNativePackage());
  //生成native URL
  print_r($pay->createNativeUrl("9701"));
}
登入後複製

JS API產生的package簽名套件參數:

{
  "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"
}
登入後複製

Native 回應的XML格式:

<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=wx9998ff5f4dede5b7&noncestr=VY7cVA6mtVrc1BVq&productid=9701&sign=43508b65b50eVq&productid=9701&sign=43508b65b50eVq&productid=9701&sign=43508b65b50eVq&productid=9701&sign=43508b65b50eVq&productid=9701&sign=43508b65b50eVq&productid=9701&sign=43508b65b50eVq&productid=9701&sign=43508b65b50e1d76589bed 3

無論哪種方式,我們都要透過setParams來設定必要初始化參數和商品價格和狀態等!

WechatPay class:

<?php
class WechatPay {
  const
    BANK_TYPE = &#39;bank_type&#39;,
    BODY = &#39;body&#39;,
    PARTNER = &#39;partner&#39;,
    OUT_TRADE_NO = &#39;out_trade_no&#39;,
    TIMESTAMP = &#39;timestamp&#39;,
    TOTAL_FEE = &#39;total_fee&#39;,
    FEE_TYPE = &#39;fee_type&#39;,
    NOTIFY_URL = &#39;notify_url&#39;,
    SPBILL_CREATE_IP = &#39;spbill_create_ip&#39;,
    INPUT_CHARSET = &#39;input_charset&#39;,
    APPID = &#39;appid&#39;,
    APPSERCER = &#39;appsercer&#39;,
    PAYSIGNKEY = &#39;appkey&#39;,
    PARTNERID = &#39;partnerid&#39;,
    PARTNERKEY = &#39;partnerkey&#39;,
    SIGNTYPE = &#39;signtype&#39;;
  public
    $params = array(), $partnerid = &#39;&#39;;
  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::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 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    $str ="";
    for ( $i = 0; $i < $length; $i++ ) {
      $str.= substr($chars, mt_rand(0, strlen($chars)-1), 1);
    }
    return $str;
  }
  public function checkParams(){
    //必要的9个参与签名的参数
    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_FEE] == null || $this->params[self::FEE_TYPE] == null ||
      $this->params[self::NOTIFY_URL] == null || $this->params[self::SPBILL_CREATE_IP] == null || $this->params[self::INPUT_CHARSET] == null
    ) {
      return false;
    }
    return true;
  }
  /*
   * 生成package包
   * @params 初始化类时用setParams方法定义必要的9个参数
   * 排序后格式化url query形式 再md5SignUtil类签名,再给合URL
   */
  protected function getPackageSign(){
    try {
      if (null == $this->_partnerkey || "" == $this->_partnerkey ) {
        throw new Exception("密钥不能为空!" . "<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());
    }
  }
  /*
   * 生成签名方法
   * @params appid appkey package timestamp noncestr 等参数而native事例代码中加上retcode reterrmsg两个参数
   */
  public function getPaySign($signObj){
    foreach ($signObj as $k => $v){
      $signParams[strtolower($k)] = $v;
    }
    try {
      if ($this->_appkey == "") {
        throw new Exception("APPKEY为空!" . "<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 签名 其中nonceStr是作为订单号 灌穿整个支付流程
  public function createJsApiPackage(){
    try {
      if($this->checkParams() == false) {
        throw new Exception("生成package参数缺失!" . "<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());
    }
  }
  /*
   * 构建发货状态数组 主要三个参数openid transid orderid
   */
  public function createDeliverPost(Array $params) {
    $deliver = array();
    $deliver[&#39;appid&#39;] = $this->_appid;
    $deliver[&#39;openid&#39;] = $params[&#39;openid&#39;];
    $deliver[&#39;transid&#39;] = $params[&#39;transid&#39;];
    $deliver[&#39;out_trade_no&#39;] = $params[&#39;out_trade_no&#39;];
    $deliver[&#39;deliver_timestamp&#39;] = current_time(&#39;timestamp&#39;);
    $deliver[&#39;deliver_status&#39;] = 1;
    $deliver[&#39;deliver_msg&#39;] = &#39;OK&#39;;
    $deliver[&#39;app_signature&#39;] = $this->getPaySign($deliver);
    $deliver[&#39;sign_method&#39;] = &#39;sha1&#39;;
    return $deliver;
  }
  /*
   * 生成扫描或者点击原生URL后,响应的XML格式
   * @params $retcode $reterrmsg 定义该商品的状态
   */
  public function createNativePackage($retcode = 0, $reterrmsg = "ok") {
    try {
      if ($this->checkParams() == false && $retcode == 0) {  //如果是正常的返回, 检查财付通的参数
        throw new Exception("生成package参数缺失!" . "<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());
    }
  }
  /*
   * 生成原生URL 以订单号为参数 这是灌穿整个支付流程
   */
  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;
  }
  /*
   * 取IP地址
   */
  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("财付通签名key不能为空!" . "<br>");
      }
      if (null == $content) {
        throw new Exception("财付通签名内容不能为空" . "<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);
    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;
  }
  //订单号,可根据实际自定义
  static public function createOrderNo() {
    $nonce = CommonUtil::createNoncestr(4);
    return strtoupper(date(&#39;ymds&#39;).substr(microtime(),2,4).$nonce);
  }
  //随机字符串
  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 = &#39;&#39;;
    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 = &#39;&#39;;
    if (strlen($buff) > 0) {
      $reqPar = substr($buff, 0, strlen($buff)-1);
    }
    return $reqPar;
  }
  /*
   * 输出一级数组的xml格式
   */
  public function arrayToXml($arr) {
    $xml = "<xml>";
    foreach ($arr as $key=>$val) {
      if ($key == &#39;TimeStamp&#39; || $key == &#39;RetCode&#39;) {
        $xml.="<".$key.">".$val."</".$key.">";
      } else
        $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
    }
    $xml .= "</xml>";
    return $xml;
  }
}
登入後複製

#總結:以上就是這篇文章的全部內容,希望能對大家的學習有所幫助。

相關推薦:

php curl取得到json物件並轉成陣列array的方法

PHP實作可精確驗證身分證號碼的工具類別

Thinkphp實作簡訊驗證註冊功能的方法

以上是php版微信js-sdk支付介面類別用法實例詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板