溫馨提示×

溫馨提示×

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

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

PHP中微信H5支付開發(fā)的示例分析

發(fā)布時間:2021-08-05 14:24:24 來源:億速云 閱讀:230 作者:小新 欄目:開發(fā)技術(shù)

這篇文章主要為大家展示了“PHP中微信H5支付開發(fā)的示例分析”,內(nèi)容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學習一下“PHP中微信H5支付開發(fā)的示例分析”這篇文章吧。

首先,WxPay.Config.php配置文件主要包含了商戶appId、商戶號、商家key、異步回調(diào)URL、支付場景信息,如下:

class WxPayConfig
{
  public static $appid = '微信支付的公眾號appid';
  public static $mchid = '微信支付分配的商戶號';
  public static $key = '微信商戶自己設(shè)置的安全key';
  public static $notify_url = '商戶側(cè)接收微信支付異步通知的URL';
  public static $scene_info = '{"h6_info":{"type":"Wap","wap_url":" 發(fā)起微信H5支付H5的URL","wap_name":"支付"}}'; 
}

然后,封裝Weixin.class.php支付類,主要調(diào)用統(tǒng)一下單Api,這里不多說了,直接上代碼:

<?php
require_once "lib/WxPay.Config.php";
class Weixin
{
     /**
   * 微信H5下單付款
   *   @order 付款信息
     *   @bodys 付款內(nèi)容
   * */
     function getCode($order,$bodys){
          $url = "https://api.mch.weixin.qq.com/pay/unifiedorder";//微信傳參地址
          //1.獲取調(diào)用統(tǒng)一下單接口所需必備參數(shù)
    $appid =WxPayConfig::$appid;//微信公眾號appid
    $mch_id = WxPayConfig::$mchid;//微信支付商戶號
    $key = WxPayConfig::$key;//自己設(shè)置的微信商家key
    $out_trade_no = $order['order_sn'];//平臺內(nèi)部訂單號
    $nonce_str=MD5($out_trade_no);//隨機字符串
    $body = $bodys;//付款內(nèi)容
    $total_fee = $order['order_amount']*100;//付款金額,單位為分
    $spbill_create_ip = getIP(); //獲得用戶設(shè)備IP
    $attach = 'weixinh6';//附加數(shù)據(jù)(自定義,在支付通知中原樣返回)
    $notify_url = WxPayConfig::$notify_url; //異步回調(diào)地址,需外網(wǎng)可以直接訪問
    $trade_type = 'MWEB';//交易類型,微信H5支付時固定為MWEB
    $scene_info =WxPayConfig::$scene_info;//場景信息
          //2.將參數(shù)按照key=value的格式,并按照參數(shù)名ASCII字典序排序生成字符串
    $signA ="appid=$appid&attach=$attach&body=$body&mch_id=$mch_id&nonce_str=$nonce_str&notify_url=$notify_url&out_trade_no=$out_trade_no&scene_info=$scene_info&spbill_create_ip=$spbill_create_ip&total_fee=$total_fee&trade_type=$trade_type";
    //3.拼接字符串
          $strSignTmp = $signA."&key=$key";
          //4.MD5加密后轉(zhuǎn)換成大寫
    $sign = strtoupper(MD5($strSignTmp));
          //5.拼接成所需XML格式
    $post_data = "<xml> 
            <appid>$appid</appid> 
            <attach>$attach</attach> 
            <body>$body</body> 
            <mch_id>$mch_id</mch_id> 
            <nonce_str>$nonce_str</nonce_str> 
            <notify_url>$notify_url</notify_url> 
            <out_trade_no>$out_trade_no</out_trade_no> 
            <spbill_create_ip>$spbill_create_ip</spbill_create_ip> 
            <total_fee>$total_fee</total_fee> 
            <trade_type>$trade_type</trade_type>
            <scene_info>$scene_info</scene_info>
            <sign>$sign</sign> 
          </xml>";
          //6.以POST方式向微信傳參,并取得微信返回的支付參數(shù)
    $dataxml = httpRequest($url,'POST',$post_data);
    $objectxml = (array)simplexml_load_string($dataxml, 'SimpleXMLElement', LIBXML_NOCDATA); //將微信返回的XML轉(zhuǎn)換成數(shù)組
    return $objectxml;
  }
}

最后,PayMentController.class.php支付文件,支付文件接收前端發(fā)起支付的請求并處理后,調(diào)用Weixin.class.php支付類并接受結(jié)果后返回給前端(此處分享已經(jīng)去掉接口驗證等系列代碼邏輯):

public function getPay(){
     //1.引入支付類文件
     include_once "plugins/Payment/weixin/Weixin.class.php";
     $payment = new \Weixin();
     $order_id = I('order_id');
     //2.判斷參數(shù)是否為空
     if (!empty($order_id)){
          //3.根據(jù)訂單id查詢訂單是否存在
          $order = M('Order')->where(array('id'=>$order_id))->find();
          if ($order){//訂單存在
              //4.判斷該筆訂單是否已經(jīng)支付,如已支付則返回支付失敗并給出相應(yīng)提示
              if ($order['pay_status'] == '1'){
                   exit(json_encode(array('status'=>'205','msg'=>'該訂單已支付,請勿重復提交!')));
              }
              $bodys = '訂單:'.$order['order_sn'] . '支付';
              //5.調(diào)用支付類中封裝的支付方法并對應(yīng)傳參
              $result = $payment->getCode($order,$bodys);
              //6.當return_code和result_code均為SUCCESS,代表下單成功,將支付參數(shù)返回
              if($result['return_code'] == 'SUCCESS'){
                   if($result['result_code'] == 'SUCCESS'){
                        exit(json_encode(array('status'=>'0','msg'=>'下單成功,請支付!','result'=>$result['mweb_url'])));
                   }elseif($result['result_code'] == 'FAIL'){
                        exit(json_encode(array('status'=>'-201','msg'=>$result['err_code_des'])));
                   }
              }else{
        exit(json_encode(array('status'=>'-1','msg'=>'未知錯誤,請稍后重試!')));
                  }
          }else{
              //報錯:數(shù)據(jù)不存在
              exit(json_encode(array('status'=>'-200','msg'=>'訂單不存在,請核實后再提交!')));
          }
     }else{
          //報錯:缺少參數(shù)
          exit(json_encode(array('status'=>'-204','msg'=>'參數(shù)缺失,請核實!')));
     }
}

前端在接收到支付URL后執(zhí)行即可喚醒微信支付。

附一:獲取用戶終端設(shè)備ip方法

function getIP(){      
    if (getenv("HTTP_CLIENT_IP"))
       $ip = getenv("HTTP_CLIENT_IP");
    else if(getenv("HTTP_X_FORWARDED_FOR"))
        $ip = getenv("HTTP_X_FORWARDED_FOR");
    else if(getenv("REMOTE_ADDR"))
       $ip = getenv("REMOTE_ADDR");
    else $ip = "Unknow";
    return $ip;
}

######附二:CURL請求方法

/**
   * CURL請求
   * @param $url 請求url地址
   * @param $method 請求方法 get post
   * @param null $postfields post數(shù)據(jù)數(shù)組
   * @param array $headers 請求header信息
   * @param bool|false $debug 調(diào)試開啟 默認false
   * @return mixed
   */
  function httpRequest($url, $method, $postfields = null, $headers = array(), $debug = false) {
    $method = strtoupper($method);
    $ci = curl_init();
    /* Curl settings */
    curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
    curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
    curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 60); /* 在發(fā)起連接前等待的時間,如果設(shè)置為0,則無限等待 */
    curl_setopt($ci, CURLOPT_TIMEOUT, 7); /* 設(shè)置cURL允許執(zhí)行的最長秒數(shù) */
    curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
    switch ($method) {
      case "POST":
        curl_setopt($ci, CURLOPT_POST, true);
        if (!empty($postfields)) {
          $tmpdatastr = is_array($postfields) ? http_build_query($postfields) : $postfields;
          curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpdatastr);
        }
        break;
      default:
        curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method); /* //設(shè)置請求方式 */
        break;
    }
    $ssl = preg_match('/^https:\/\//i',$url) ? TRUE : FALSE;
    curl_setopt($ci, CURLOPT_URL, $url);
    if($ssl){
      curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE); // https請求 不驗證證書和hosts
      curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE); // 不從證書中檢查SSL加密算法是否存在
    }
    curl_setopt($ci, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ci, CURLOPT_MAXREDIRS, 2);/*指定最多的HTTP重定向的數(shù)量,這個選項是和CURLOPT_FOLLOWLOCATION一起使用的*/
    curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ci, CURLINFO_HEADER_OUT, true);
    $response = curl_exec($ci);
    $requestinfo = curl_getinfo($ci);
    if ($debug) {
      echo "=====post data======\r\n";
      var_dump($postfields);
      echo "=====info===== \r\n";
      print_r($requestinfo);
      echo "=====response=====\r\n";
      print_r($response);
    }
    curl_close($ci);
    return $response;
}

以上是“PHP中微信H5支付開發(fā)的示例分析”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學習更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細節(jié)

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

AI