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

首頁 > 語言 > PHP > 正文

PHP的微信支付接口使用方法講解

2024-05-05 00:07:15
字體:
來源:轉載
供稿:網友

在開發之中經常會使用到支付的功能,現在常用的兩種支付方式是支付寶和微信。相對而言,支付寶的文檔較為健全,并且配置和調用方式方式比較簡單,這里就不過多的描述。

首先去微信官網網站下去下載服務端的demo:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=11_1

這里雖然是官網提供的公眾號支付的demo,雖然微信支付的預下單等都可以在前端進行實現,不過官方還是建議在服務端進行處理。下載后,將其中的demo引入你的項目就好,注意的是如果是公眾號的支付用到的類文件WxPay.JsApiPay.php在文件中example目錄下。

接下來我們就可以進行引用了并實現。以thinkphp框架下進行調用為例(以下案例包括移動端以及公眾號支付以及公眾號獲取openid等功能)。以下代碼為了能夠更容易理解,將一些類中的方法提取了出來,寫的有點亂,請見諒。

  /* 微信APP下支付預下單 */  public function wxAppOrder(){    //TODO:首先獲取訂單詳情,例如傳遞過來訂單號或訂單id,獲取訂單的詳情信息,例如將取出的數據存放入$user_order_info數組,訂單中包含的商品在$user_order_product_info之中。    /* 向微信發起請求 */    vendor('WxpayAPI.lib.WxPay','','.Api.php');    vendor('WxpayAPI.lib.WxPay','','.Data.php');//生成數據    //統一下單輸入對象    $order_info= new WxPayUnifiedOrder();    $order_info->SetOut_trade_no($user_order_info['orderNo']);//商品訂單號    $body=$user_order_product_info['productName'];    //   $body=iconv('UTF-8', 'ISO-8859-1', $user_order_product_info['productName']);    $order_info->SetBody($body);//商品描述    $order_info->SetTrade_type('CNY');//人民幣    $order_info->SetTotal_fee(intval($user_order_info['sumPrice']*100));//總金額,以分為單位    $order_info->SetTrade_type('APP');//交易類型    $order_info->SetAppid(C('wxAPPID'));    $order_info->SetMch_id(C('wxMCHID'));    $order_info->SetNotify_url('你的回調地址');    $order_info->SetSign();    //進行統一支付    $wxpay=new WxPayApi();    $order_result=$wxpay->unifiedOrder($order_info);//統一下單    if ($order_result['return_code']=='FAIL') {      $arr=array(          'resultCode'=>'99',          'resultDesc'=>$order_result['return_msg'],          'resultObj'=>array(''=>''),      );      echo JSON($arr);      exit();    }    if ($order_result['result_code']=='SUCCESS') {    //預下單成功后,重新簽名返回給移動端      $wxpay_result=new WxPayResults();      $timestamp=time();      $wxpay_result->SetData('appid', $order_result['appid']);      $wxpay_result->SetData('partnerid', $order_result['mch_id']);      $wxpay_result->SetData('prepayid', $order_result['prepay_id']);      $wxpay_result->SetData('timestamp', $timestamp);      $wxpay_result->SetData('noncestr', $order_result['nonce_str']);      $wxpay_result->SetData('package', 'Sign=WXPay');      // $wxpay_result->SetData('key', C('wxKEY'));      //上方注釋的代碼是再簽名中必要的一步,只是這個包含在了微信demo的類中,如果像該項目中既有app支付,又有公眾號支付,最好是注釋類中代碼,并自己寫入      $resign_result=$wxpay_result->SetSign();      //處理返回數據      $result=array(          'appid'=>$order_result['appid'],//appid          'partnerid'=>$order_result['mch_id'],//商戶號          'prepayid'=>$order_result['prepay_id'],//與支付id          'package'=>'Sign=WXPay',          'noncestr'=>$order_result['nonce_str'],          'timestamp'=>$timestamp,          'sign'=>$resign_result,      );      $arr=array(          'resultCode'=>'00',          'resultDesc'=>'成功',          'resultObj'=>$result,      );      echo JSON($arr);      exit();    }else{      $arr=array(          'resultCode'=>'99',          'resultDesc'=>'失敗',          'resultObj'=>$order_result,      );      echo JSON($arr);      exit();    }  }  /* 微信支付回調函數 */  public function wxpayNotify(){    vendor('WxpayAPI.lib.Logwx','','.Log.php');//在回調中最好是引入日志進行記錄,在這里因為Log類與thinkphp中的log類重復,需要進行處理    $handle=new CLogFileHandler('./Public/wxlog.txt');    $log=Logwx::Init($handle);    $xml = $GLOBALS['HTTP_RAW_POST_DATA'];//獲取數據    vendor('WxpayAPI.lib.WxPay','','.Api.php');    vendor('WxpayAPI.lib.WxPay','','.Data.php');    $wxpay=new WxPayApi();    $notify=new WxPayNotifyReply();    $result=WxPayResults::Init($xml);//獲取數據并轉換為數組    if ($result['return_code']=='SUCCESS' && $result['result_code']=='SUCCESS') {//此字段是通信標識,非交易標識,交易是否成功需要查看result_code來判斷      //TODO:進行數據庫操作的業務邏輯處理,假設其成功與否的數據為$res      if ($res) {        $log->INFO('訂單:'.$result['out_trade_no'].'支付成功');        $notify->SetReturn_code('SUCCESS');        $notify->SetReturn_msg('OK');        $notify->SetSign();      }else{        $log->ERROR('微信支付失敗');        $notify->SetReturn_code('FAIL');        $notify->SetReturn_msg('客戶服務器錯誤');      }    }else{      $log->ERROR('微信回調返回錯誤');      $notify->SetReturn_code('FAIL');      $notify->SetReturn_msg('微信支付失敗');    }    //返回微信端    $wxpay->replyNotify($notify->ToXml());  }  /* 微信公眾賬號下單   * 獲取code等信息  * 跳轉至獲取信息  *  */  public function wxPubOrder(){    //此流程中    $orderId=$_GET['orderId'];    //注意:此處如果想要回調成功,需要在微信公眾平臺設置回調域名//   print_r('Location:https://open.weixin.qq.com/connect/oauth2/authorize?appid='.C('wxAPPID').'&redirect_uri='.'http://你的域名/Pay/getOpenid/orderId/'.$orderId.'&response_type=code&scope=snsapi_base&state=123#wechat_redirect');//   exit();    header('Location:https://open.weixin.qq.com/connect/oauth2/authorize?appid='.'*******'.'&redirect_uri='.urlencode('http://*****/Pay/getOpenid/orderId/'.$orderId).'&response_type=code&scope=snsapi_base&state=123#wechat_redirect');    exit();  }  /* 微信獲取openid,跳轉到微信同意下單接口 */  public function getOpenid(){    //code    $code=$_GET['code'];    $state=$_GET['state'];    $orderId=$_GET['orderId'];    $appid='******';    $appsecret='******';    //獲取openid    $get_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code';    $ch = curl_init();    curl_setopt($ch,CURLOPT_URL,$get_token_url);    curl_setopt($ch,CURLOPT_HEADER,0);    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);    $res = curl_exec($ch);    curl_close($ch);    $json_obj = json_decode($res,true);    $openId=$json_obj['openid'];//   跳轉到預下單    // echo $openId;exit();    $url='http://******/html5/#/pay/'.$orderId.'openid='.$openId;    header('Location:'.$url);  }  /* 微信公眾賬號統一下單 */  public function wxOrder(){    $orderId=$_GET['orderId'];    $openId=$_GET['openId'];    if (empty($orderId)||empty($openId)) {      $arr=array(          'resultCode'=>'66',          'resultDesc'=>'缺少參數',          'resultObj'=>array(),      );      echo JSON($arr);      exit();    }    //TODO:獲取訂單和訂單商品信息,分別存儲在$user_order_info中和$user_order_good_info中    if (empty($user_order_info)) {      $arr=array(          'resultCode'=>'99',          'resultDesc'=>'不存在該訂單',          'resultObj'=>array(),      );      echo JSON($arr);      exit();    }    /* 向微信發起請求 */    vendor('WxpayAPI.lib.WxPay','','.Api.php');    vendor('WxpayAPI.lib.WxPay','','.Data.php');//生成數據    //   vendor('WxpayAPI.lib.WxPay','','.JsApiPay.php');    //統一下單輸入對象    $order_info= new WxPayUnifiedOrder();    $wxpay=new WxPayApi();    $order_info->SetMch_id('***');//商戶號    $order_info->SetAppid('****');//微信號APPID//wx70a40dfa2711c4fe    $order_info->SetOut_trade_no($user_order_info['orderNo']);//商品訂單號    $order_info->SetBody($user_order_good_info['productName']);//商品描述    $order_info->SetTrade_type('CNY');//人民幣    $order_info->SetTotal_fee(intval($user_order_info['sumPrice']*100));//總金額,以分為單位    $order_info->SetTrade_type('JSAPI');//交易類型    $order_info->SetNonce_str($wxpay->getNonceStr(32));    $order_info->SetSpbill_create_ip('1.1.1.1');    //   $order_info->SetOpenid($user_info['openId']);    $order_info->SetOpenid($openId);    //TODO:    $order_info->SetNotify_url('http://****/Pay/wxpayNotify');    $order_info->SetSign();//設置簽名    //進行統一支付    $order_result=$wxpay->unifiedOrder($order_info);//統一下單    //同意下單后再加    if ($order_result['return_code']=='FAIL') {      $arr=array(          'resultCode'=>'99',          'resultDesc'=>$order_result['return_code'].':'.$order_result['return_msg'],          'resultObj'=>array(),      );      echo JSON($arr);      exit();    }    if ($order_result['result_code']=='SUCCESS') {      $jsapi = new WxPayJsApiPay();      $jsapi->SetAppid($order_result["appid"]);      $timeStamp = time();      $jsapi->SetTimeStamp("$timeStamp");      $jsapi->SetNonceStr(WxPayApi::getNonceStr());      $jsapi->SetPackage("prepay_id=" . $order_result['prepay_id']);      $jsapi->SetSignType("MD5");      $jsapi->SetPaySign($jsapi->MakeSign());      $order_result = $jsapi->GetValues();      //     print_r($order_result);exit();      $arr=array(          'resultCode'=>'00',          'resultDesc'=>'成功',          'resultObj'=>$order_result,      );      echo JSON($arr);      exit();    }else{      $arr=array(          'resultCode'=>'99',          'resultDesc'=>'失敗',          'resultObj'=>$order_result,      );      echo JSON($arr);      exit();    }    }

這就是一個支付的流程,在這之中會遇到很多問題,在此給出一個大多數會遇到的問題的解決方法的大概思路:

  • 1、APP統一下單后數據返回給前端,前端調用報簽名錯誤:首先驗證自己的秘鑰信息是否正確,要注意移動端和公眾號的是不同的,而類拿著key又去重新簽名,可以將微信官方提供的demo中的直接內部調用配置文件那里注釋掉
  • 2、在公眾號獲取openid的時候,顯示跨域:這個解決參考YII2框架中對于/yii::$app->response->header,中的remove方法,將報頭去掉即可。
  • 3、對于微信支付的配置,包括公眾號支付配置白名單、測試目錄啥的就不過多說了,請自行搜索資料

過程中肯定還遇到很多問題,這里不一一寫了,如果還有問題可以在評論中留言,大家一起討論學習,共同進步。

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對VeVb武林網的支持。


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

圖片精選

主站蜘蛛池模板: 玉溪市| 贡嘎县| 广水市| 苍南县| 富民县| 德兴市| 西昌市| 饶阳县| 寻乌县| 田林县| 聂荣县| 大兴区| 于都县| 永和县| 盐城市| 龙游县| 房山区| 蓝山县| 横峰县| 新宾| 宁强县| 连州市| 将乐县| 赤城县| 曲靖市| 紫云| 县级市| 石城县| 石景山区| 松原市| 宣汉县| 清徐县| 南阳市| 台南市| 嘉荫县| 吉安市| 宁城县| 崇礼县| 延川县| 阆中市| 和平县|