国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > PHP > 正文

PHP微信H5支付開發實例

2024-05-05 00:04:43
字體:
來源:轉載
供稿:網友

最近由于業務所需,對接了微信H5支付,然而微信支付對這塊并沒有現成的demo可用,所以就必須自己老老實實對照開發文檔去寫咯!但這對于剛接觸的童鞋來說,坑多多少少還是有的,所以尋思著把自己的經驗分享出來,畢竟現成的用的還是多巴適的嘛! 

好了,官方文檔的那一套就不多說了,詳情見官方文檔。 

在這里,我主要分成了三個文件:WxPay.Config.php(支付配置文件)、Weixin.class.php(支付類)以及PayMentController.class.php(支付文件)。

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

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

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

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

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

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

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

附一:獲取用戶終端設備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數據數組   * @param array $headers 請求header信息   * @param bool|false $debug 調試開啟 默認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); /* 在發起連接前等待的時間,如果設置為0,則無限等待 */    curl_setopt($ci, CURLOPT_TIMEOUT, 7); /* 設置cURL允許執行的最長秒數 */    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); /* //設置請求方式 */        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重定向的數量,這個選項是和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;}

好了,一點點菜鳥心得,有不當之處歡迎留言指證交流,一起成長!

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。


注:相關教程知識閱讀請移步到PHP教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 广水市| 饶平县| 商都县| 依安县| 池州市| 思南县| 文山县| 东乌珠穆沁旗| 蒲城县| 丹阳市| 政和县| 开阳县| 华蓥市| 渝北区| 武山县| 扎鲁特旗| 安平县| 泸水县| 綦江县| 隆德县| 曲松县| 孝感市| 巴林左旗| 辰溪县| 邳州市| 梓潼县| 凉山| 安徽省| 余干县| 蓬溪县| 黄冈市| 宜良县| 儋州市| 汕尾市| 烟台市| 巴林左旗| 合肥市| 林芝县| 吴旗县| 廊坊市| 尚志市|