溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何編寫PHP微信支付類demo

發(fā)布時間:2021-09-29 09:43:57 來源:億速云 閱讀:118 作者:iii 欄目:開發(fā)技術(shù)

本篇內(nèi)容主要講解“如何編寫PHP微信支付類demo”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強(qiáng)。下面就讓小編來帶大家學(xué)習(xí)“如何編寫PHP微信支付類demo”吧!

<?php
class WxpayService
{
  protected $mchid;
  protected $appid;
  protected $key;
  public function __construct($mchid, $appid, $key)
  {
    $this->mchid = $mchid; // 微信支付商戶號 PartnerID 通過微信支付商戶資料審核后郵件發(fā)送
    $this->appid = $appid; //公眾號APPID 通過微信支付商戶資料審核后郵件發(fā)送
    $this->key = $key;   //https://pay.weixin.qq.com 帳戶設(shè)置-安全設(shè)置-API安全-API密鑰-設(shè)置API密鑰
  }
  /**
   * @param string $openid 調(diào)用【網(wǎng)頁授權(quán)獲取用戶信息】接口獲取到用戶在該公眾號下的Openid
   * @param float $totalFee 收款總費(fèi)用 單位元
   * @param string $outTradeNo 唯一的訂單號
   * @param string $orderName 訂單名稱
   * @param string $notifyUrl 支付結(jié)果通知url 不要有問號
   *   https://mp.weixin.qq.com/ 微信支付-開發(fā)配置-測試目錄
   *   測試目錄 http://mp.izhanlue.com/paytest/  最后需要斜線,(需要精確到二級或三級目錄)
   * @return string
   */
  public function createJsBizPackage($openid, $totalFee, $outTradeNo, $orderName, $notifyUrl, $timestamp)
  {
    $config = array(
      'mch_id' => $this->mchid,
      'appid' => $this->appid,
      'key' => $this->key,
    );
    $unified = array(
      'appid' => $config['appid'],
      'attach' => '支付',             //商家數(shù)據(jù)包,原樣返回
      'body' => $orderName,
      'mch_id' => $config['mch_id'],
      'nonce_str' => self::createNonceStr(),
      'notify_url' => $notifyUrl,
      'openid' => $openid,            //rade_type=JSAPI,此參數(shù)必傳
      'out_trade_no' => $outTradeNo,
      'spbill_create_ip' => '127.0.0.1',
      'total_fee' => intval($totalFee * 100),       //單位 轉(zhuǎn)為分
      'trade_type' => 'JSAPI',
    );
    $unified['sign'] = self::getSign($unified, $config['key']);
    $responseXml = self::curlPost('https://api.mch.weixin.qq.com/pay/unifiedorder', self::arrayToXml($unified));
    /*
    <xml>
    <return_code><![CDATA[SUCCESS]]></return_code>
    <return_msg><![CDATA[OK]]></return_msg>
    <appid><![CDATA[wx00e5904efec77699]]></appid>
    <mch_id><![CDATA[1220647301]]></mch_id>
    <nonce_str><![CDATA[1LHBROsdmqfXoWQR]]></nonce_str>
    <sign><![CDATA[ACA7BC8A9164D1FBED06C7DFC13EC839]]></sign>
    <result_code><![CDATA[SUCCESS]]></result_code>
    <prepay_id><![CDATA[wx2015032016590503f1bcd9c30421762652]]></prepay_id>
    <trade_type><![CDATA[JSAPI]]></trade_type>
    </xml>
    */
    $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);
      /*
      NOAUTH 商戶無此接口權(quán)限
      NOTENOUGH 余額不足
      ORDERPAID 商戶訂單已支付
      ORDERCLOSED 訂單已關(guān)閉
      SYSTEMERROR 系統(tǒng)錯誤
      APPID_NOT_EXIST   APPID不存在
      MCHID_NOT_EXIST MCHID不存在
      APPID_MCHID_NOT_MATCH appid和mch_id不匹配
      LACK_PARAMS 缺少參數(shù)
      OUT_TRADE_NO_USED 商戶訂單號重復(fù)
      SIGNERROR 簽名錯誤
      XML_FORMAT_ERROR XML格式錯誤
      REQUIRE_POST_METHOD 請使用post方法
      POST_DATA_EMPTY post數(shù)據(jù)為空
      NOT_UTF8 編碼格式錯誤
      */
    }
    //$unifiedOrder->trade_type 交易類型 調(diào)用接口提交的交易類型,取值如下:JSAPI,NATIVE,APP
    //$unifiedOrder->prepay_id 預(yù)支付交易會話標(biāo)識 微信生成的預(yù)支付回話標(biāo)識,用于后續(xù)接口調(diào)用中使用,該值有效期為2小時
    //$unifiedOrder->code_url 二維碼鏈接 trade_type為NATIVE是有返回,可將該參數(shù)值生成二維碼展示出來進(jìn)行掃碼支付
    $arr = array(
      "appId" => $config['appid'],
      "timeStamp" => $timestamp,
      "nonceStr" => self::createNonceStr(),
      "package" => "prepay_id=" . $unifiedOrder->prepay_id,
      "signType" => 'MD5',
    );
    $arr['paySign'] = self::getSign($arr, $config['key']);
    return $arr;
  }
  public function notify()
  {
    $config = array(
      'mch_id' => $this->mchid,
      'appid' => $this->appid,
      'key' => $this->key,
    );
    $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
    //error_log($postStr, 3, './str.txt');
    /*
    $postStr = '<xml>
    <appid><![CDATA[wx00e5904efec77699]]></appid>
    <attach><![CDATA[支付測試]]></attach>
    <bank_type><![CDATA[CMB_CREDIT]]></bank_type>
    <cash_fee><![CDATA[1]]></cash_fee>
    <fee_type><![CDATA[CNY]]></fee_type>
    <is_subscribe><![CDATA[Y]]></is_subscribe>
    <mch_id><![CDATA[1220647301]]></mch_id>
    <nonce_str><![CDATA[a0tZ41phiHm8zfmO]]></nonce_str>
    <openid><![CDATA[oU3OCt5O46PumN7IE87WcoYZY9r0]]></openid>
    <out_trade_no><![CDATA[550bf2990c51f]]></out_trade_no>
    <result_code><![CDATA[SUCCESS]]></result_code>
    <return_code><![CDATA[SUCCESS]]></return_code>
    <sign><![CDATA[F6F519B4DD8DB978040F8C866C1E6250]]></sign>
    <time_end><![CDATA[20150320181606]]></time_end>
    <total_fee>1</total_fee>
    <trade_type><![CDATA[JSAPI]]></trade_type>
    <transaction_id><![CDATA[1008840847201503200034663980]]></transaction_id>
    </xml>';
    */
    $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) {
      // $mch_id = $postObj->mch_id; //微信支付分配的商戶號
      // $appid = $postObj->appid; //微信分配的公眾賬號ID
      // $openid = $postObj->openid; //用戶在商戶appid下的唯一標(biāo)識
      // $transaction_id = $postObj->transaction_id;//微信支付訂單號
      // $out_trade_no = $postObj->out_trade_no;//商戶訂單號
      // $total_fee = $postObj->total_fee; //訂單總金額,單位為分
      // $is_subscribe = $postObj->is_subscribe; //用戶是否關(guān)注公眾賬號,Y-關(guān)注,N-未關(guān)注,僅在公眾賬號類型支付有效
      // $attach = $postObj->attach;//商家數(shù)據(jù)包,原樣返回
      // $time_end = $postObj->time_end;//支付完成時間
      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請求 不驗證證書和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 curlPost($url = '', $postData = '', $options = array())
  {
    if (is_array($postData)) {
      $postData = 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); //設(shè)置cURL允許執(zhí)行的最長秒數(shù)
    if (!empty($options)) {
      curl_setopt_array($ch, $options);
    }
    //https請求 不驗證證書和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 = 16)
  {
    $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;
  }
  /**
   * 例如:
   * appid:  wxd930ea5d5a258f4f
   * mch_id:  10000100
   * device_info: 1000
   * Body:  test
   * nonce_str: ibuaiVcKdpRxkhJA
   * 第一步:對參數(shù)按照 key=value 的格式,并按照參數(shù)名 ASCII 字典序排序如下:
   * stringA="appid=wxd930ea5d5a258f4f&body=test&device_info=1000&mch_i
   * d=10000100&nonce_str=ibuaiVcKdpRxkhJA";
   * 第二步:拼接支付密鑰:
   * stringSignTemp="stringA&key=192006250b4c09247ec02edce69f6a2d"
   * sign=MD5(stringSignTemp).toUpperCase()="9A0A8659F005D6984697E2CA0A9CF3B7"
   */
  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;
  }
}

到此,相信大家對“如何編寫PHP微信支付類demo”有了更深的了解,不妨來實際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI