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

首頁 > 熱點 > 微信 > 正文

CodeIgniter框架集成微信掃碼支付SDK

2020-03-22 17:45:24
字體:
來源:轉載
供稿:網友
  • 版本:CI3.0

    微信掃碼支付:模式二

    下載官方demo:http://pay.weixin.qq.com/wiki/doc/api/native.php?chapter=11_1

    我是個小菜鳥,第一次研究這個,感覺無從下手,走了很多彎路后,也算是完成了?,F分享下希望對大家有幫助。

    首先下載官方demo,將文件當在libraries/ 并命名為 Wxpay。在ci配置文件config/ 下新建 wxpay_config.php 并完成配置。

    wxpay_config.php

    <?php defined('BASEPATH') OR exit('No direct script access allowed');	/**	 * TODO: 修改這里配置為您自己申請的商戶信息	 * 微信公眾號信息配置	 * 	 * APPID:綁定支付的APPID(必須配置,開戶郵件中可查看)	 * 	 * MCHID:商戶號(必須配置,開戶郵件中可查看)	 * 	 * KEY:商戶支付密鑰,參考開戶郵件設置(必須配置,登錄商戶平臺自行設置)	 * 設置地址:http://pay.weixin.qq.com/index.php/account/api_cert	 * 	 * APPSECRET:公眾帳號secert(僅JSAPI支付的時候需要配置, 登錄公眾平臺,進入開發者中心可設置),	 * 獲取地址:http://mp.weixin.qq.com/advanced/advanced?action=dev&t=advanced/dev&token=2005451881&lang=zh_CN	 * @var string	 */	$config['appid'] = '';	 	$config['mch_id'] = '';	 	$config['apikey'] = '';	 	$config['appsecret'] = '';	 	$config['sslcertPath'] =  APPPATH.'libraries/Wxpay/cert/apiclient_cert.pem';	 	$config['sslkeyPath'] = APPPATH.'libraries/Wxpay/cert/apiclient_key.pem';


    在libraries/ 下新建 CI_Wechatpay.php 。

    CI_Wechatpay.php

    <?phpdefined('BASEPATH') OR exit('No direct script access allowed');// 加載微信支付require_once APPPATH.'libraries/Wxpay/Wechatpay.php';/** * 為CI擴展微信支付類 */html' target='_blank'>class CI_Wechatpay extends WechatPay {   }

    在libraries/ 下新建Wechatpay.php 這是前輩封裝好的。盡情的享用吧,其實這里已經把所以核心都封裝起來了,所以demo中的文件只需要保留cert/ logs/ 、但libraries/Wxpay/example/log.php 這個很有用,所以要把它放在Wxpay/下。

    Wechatpay.php

    <?phpdefined('BASEPATH') OR exit('No direct script access allowed');class WechatPay {    const TRADETYPE_JSAPI = 'JSAPI',TRADETYPE_NATIVE = 'NATIVE',TRADETYPE_APP = 'APP';    const URL_UNIFIEDORDER = "http://api.mch.weixin.qq.com/pay/unifiedorder";    const URL_ORDERQUERY = "http://api.mch.weixin.qq.com/pay/orderquery";    const URL_CLOSEORDER = 'http://api.mch.weixin.qq.com/pay/closeorder';    const URL_REFUND = 'http://api.mch.weixin.qq.com/secapi/pay/refund';    const URL_REFUNDQUERY = 'http://api.mch.weixin.qq.com/pay/refundquery';    const URL_DOWNLOADBILL = 'http://api.mch.weixin.qq.com/pay/downloadbill';    const URL_REPORT = 'http://api.mch.weixin.qq.com/payitil/report';    const URL_SHORTURL = 'http://api.mch.weixin.qq.com/tools/shorturl';    const URL_MICROPAY = 'http://api.mch.weixin.qq.com/pay/micropay';    /**     * 錯誤信息     */    public $error = null;    /**     * 錯誤信息XML     */    public $errorXML = null;    /**     * 微信支付配置數組     * appid        公眾賬號appid     * mch_id       商戶號     * apikey       加密key     * appsecret    公眾號appsecret     * sslcertPath  證書路徑(apiclient_cert.pem)     * sslkeyPath   密鑰路徑(apiclient_key.pem)     */    private $_config;    /**     * @param $config 微信支付配置數組     */    public function __construct($config) {        $this->_config = $config;    }    /**     * JSAPI獲取prepay_id     * @param $body     * @param $out_trade_no     * @param $total_fee     * @param $notify_url     * @param $openid     * @return null     */    public function getPrepayId($body,$out_trade_no,$total_fee,$notify_url,$openid) {        $data = array();        $data["nonce_str"]    = $this->get_nonce_string();        $data["body"]         = $body;        $data["out_trade_no"] = $out_trade_no;        $data["total_fee"]    = $total_fee;        $data["spbill_create_ip"] = $_SERVER["REMOTE_ADDR"];        $data["notify_url"]   = $notify_url;        $data["trade_type"]   = self::TRADETYPE_JSAPI;        $data["openid"]   = $openid;        $result = $this->unifiedOrder($data);        if ($result["return_code"] == "SUCCESS" && $result["result_code"] == "SUCCESS") {            return $result["prepay_id"];        } else {            $this->error = $result["return_code"] == "SUCCESS" ? $result["err_code_des"] : $result["return_msg"];            $this->errorXML = $this->array2xml($result);            return null;        }    }    private function get_nonce_string() {        return substr(str_shuffle("abcdefghijklmnopqrstuvwxyz0123456789"),0,32);    }    /**     * 統一下單接口     */    public function unifiedOrder($params) {        $data = array();        $data["appid"] = $this->_config["appid"];        $data["mch_id"] = $this->_config["mch_id"];        $data["device_info"] = (isset($params['device_info'])&&trim($params['device_info'])!='')?$params['device_info']:null;        $data["nonce_str"] = $this->get_nonce_string();        $data["body"] = $params['body'];        $data["detail"] = isset($params['detail'])?$params['detail']:null;//optional        $data["attach"] = isset($params['attach'])?$params['attach']:null;//optional        $data["out_trade_no"] = isset($params['out_trade_no'])?$params['out_trade_no']:null;        $data["fee_type"] = isset($params['fee_type'])?$params['fee_type']:'CNY';        $data["total_fee"]    = $params['total_fee'];        $data["spbill_create_ip"] = $params['spbill_create_ip'];        $data["time_start"] = isset($params['time_start'])?$params['time_start']:null;//optional        $data["time_expire"] = isset($params['time_expire'])?$params['time_expire']:null;//optional        $data["goods_tag"] = isset($params['goods_tag'])?$params['goods_tag']:null;        $data["notify_url"] = $params['notify_url'];        $data["trade_type"] = $params['trade_type'];        $data["product_id"] = isset($params['product_id'])?$params['product_id']:null;//required when trade_type = NATIVE        $data["openid"] = isset($params['openid'])?$params['openid']:null;//required when trade_type = JSAPI        $result = $this->post(self::URL_UNIFIEDORDER, $data);        return $result;    }    private function post($url, $data,$cert = false) {        $data["sign"] = $this->sign($data);        $xml = $this->array2xml($data);        $ch = curl_init();        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);        curl_setopt($ch, CURLOPT_POST, 1);        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);        curl_setopt($ch, CURLOPT_URL, $url);        if($cert == true){            //使用證書:cert 與 key 分別屬于兩個.pem文件            curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');            curl_setopt($ch,CURLOPT_SSLCERT, $this->_config['sslcertPath']);            curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');            curl_setopt($ch,CURLOPT_SSLKEY, $this->_config['sslkeyPath']);        }        $content = curl_exec($ch);        $array = $this->xml2array($content);        return $array;    }    /**     * 數據簽名     * @param $data     * @return string     */    private function sign($data) {        ksort($data);        $string1 = "";        foreach ($data as $k => $v) {            if ($v && trim($v)!='') {                $string1 .= "$k=$v&";            }        }        $stringSignTemp = $string1 . "key=" . $this->_config["apikey"];        $sign = strtoupper(md5($stringSignTemp));        return $sign;    }    private function array2xml($array) {        $xml = "<xml>" . PHP_EOL;        foreach ($array as $k => $v) {            if($v && trim($v)!='')                $xml .= "<$k><![CDATA[$v]]></$k>" . PHP_EOL;        }        $xml .= "</xml>";        return $xml;    }    private function xml2array($xml) {        $array = array();        $tmp = null;        try{            $tmp = (array) simplexml_load_string($xml);        }catch(Exception $e){}        if($tmp && is_array($tmp)){            foreach ( $tmp as $k => $v) {                $array[$k] = (string) $v;            }        }        return $array;    }    /**     * 掃碼支付(模式二)獲取支付二維碼     * @param $body     * @param $out_trade_no     * @param $total_fee     * @param $notify_url     * @param $product_id     * @return null     */    public function getCodeUrl($body,$out_trade_no,$total_fee,$notify_url,$product_id){        $data = array();        $data["nonce_str"]    = $this->get_nonce_string();        $data["body"]         = $body;        $data["out_trade_no"] = $out_trade_no;        $data["total_fee"]    = $total_fee;        $data["spbill_create_ip"] = $_SERVER["SERVER_ADDR"];        $data["notify_url"]   = $notify_url;        $data["trade_type"]   = self::TRADETYPE_NATIVE;        $data["product_id"]   = $product_id;        $result = $this->unifiedOrder($data);        if ($result["return_code"] == "SUCCESS" && $result["result_code"] == "SUCCESS") {            return $result["code_url"];        } else {            $this->error = $result["return_code"] == "SUCCESS" ? $result["err_code_des"] : $result["return_msg"];            return null;        }    }    /**     * 查詢訂單     * @param $transaction_id     * @param $out_trade_no     * @return array     */    public function orderQuery($transaction_id,$out_trade_no){        $data = array();        $data["appid"] = $this->_config["appid"];        $data["mch_id"] = $this->_config["mch_id"];        $data["transaction_id"] = $transaction_id;        $data["out_trade_no"] = $out_trade_no;        $data["nonce_str"] = $this->get_nonce_string();        $result = $this->post(self::URL_ORDERQUERY, $data);        return $result;    }    /**     * 關閉訂單     * @param $out_trade_no     * @return array     */    public function closeOrder($out_trade_no){        $data = array();        $data["appid"] = $this->_config["appid"];        $data["mch_id"] = $this->_config["mch_id"];        $data["out_trade_no"] = $out_trade_no;        $data["nonce_str"] = $this->get_nonce_string();        $result = $this->post(self::URL_CLOSEORDER, $data);        return $result;    }    /**     * 申請退款 - 使用商戶訂單號     * @param $out_trade_no 商戶訂單號     * @param $out_refund_no 退款單號     * @param $total_fee 總金額(單位:分)     * @param $refund_fee 退款金額(單位:分)     * @param $op_user_id 操作員賬號     * @return array     */    public function refund($out_trade_no,$out_refund_no,$total_fee,$refund_fee,$op_user_id){        $data = array();        $data["appid"] = $this->_config["appid"];        $data["mch_id"] = $this->_config["mch_id"];        $data["nonce_str"] = $this->get_nonce_string();        $data["out_trade_no"] = $out_trade_no;        $data["out_refund_no"] = $out_refund_no;        $data["total_fee"] = $total_fee;        $data["refund_fee"] = $refund_fee;        $data["op_user_id"] = $op_user_id;        $result = $this->post(self::URL_REFUND, $data,true);        return $result;    }    /**     * 申請退款 - 使用微信訂單號     * @param $out_trade_no 商戶訂單號     * @param $out_refund_no 退款單號     * @param $total_fee 總金額(單位:分)     * @param $refund_fee 退款金額(單位:分)     * @param $op_user_id 操作員賬號     * @return array     */    public function refundByTransId($transaction_id,$out_refund_no,$total_fee,$refund_fee,$op_user_id){        $data = array();        $data["appid"] = $this->_config["appid"];        $data["mch_id"] = $this->_config["mch_id"];        $data["nonce_str"] = $this->get_nonce_string();        $data["transaction_id"] = $transaction_id;        $data["out_refund_no"] = $out_refund_no;        $data["total_fee"] = $total_fee;        $data["refund_fee"] = $refund_fee;        $data["op_user_id"] = $op_user_id;        $result = $this->post(self::URL_REFUND, $data,true);        return $result;    }    /**     * 下載對賬單     * @param $bill_date 下載對賬單的日期,格式:20140603     * @param $bill_type 類型     * @return array     */    public function downloadBill($bill_date,$bill_type = 'ALL'){        $data = array();        $data["appid"] = $this->_config["appid"];        $data["mch_id"] = $this->_config["mch_id"];        $data["bill_date"] = $bill_date;        $data["bill_type"] = $bill_type;        $data["nonce_str"] = $this->get_nonce_string();        $result = $this->post(self::URL_DOWNLOADBILL, $data);        return $result;    }    /**     * 獲取js支付使用的第二個參數     */    public function get_package($prepay_id) {        $data = array();        $data["appId"] = $this->_config["appid"];        $data["timeStamp"] = time();        $data["nonceStr"]  = $this->get_nonce_string();        $data["package"]   = "prepay_id=$prepay_id";        $data["signType"]  = "MD5";        $data["paySign"]   = $this->sign($data);        return $data;    }    /**     * 獲取發送到通知地址的數據(在通知地址內使用)     * @return 結果數組,如果不是微信服務器發送的數據返回null     *          appid     *          bank_type     *          cash_fee     *          fee_type     *          is_subscribe     *          mch_id     *          nonce_str     *          openid     *          out_trade_no    商戶訂單號     *          result_code     *          return_code     *          sign     *          time_end     *          total_fee       總金額     *          trade_type     *          transaction_id  微信支付訂單號     */    public function get_back_data() {        $xml = file_get_contents("php://input");        $data = $this->xml2array($xml);        if ($this->validate($data)) {            return $data;        } else {            return null;        }    }    /**     * 驗證數據簽名     * @param $data 數據數組     * @return 數據校驗結果     */    public function validate($data) {        if (!isset($data["sign"])) {            return false;        }        $sign = $data["sign"];        unset($data["sign"]);        return $this->sign($data) == $sign;    }    /**     * 響應微信支付后臺通知     * @param $return_code 返回狀態碼 SUCCESS/FAIL     * @param $return_msg  返回信息     */    public function response_back($return_code="SUCCESS", $return_msg=null) {        $data = array();        $data["return_code"] = $return_code;        if ($return_msg) {            $data["return_msg"] = $return_msg;        }        $xml = $this->array2xml($data);        print $xml;    }}

    接下來我是在 controller/order.php 文件下封裝個方法 這里也用到了log.php ,注意看使用方法。在調bug時非常好用。

    Order.php

           /**         * wxPay 微信支付接口         * @param $Id 訂單ID         * @author lyne         */        public function wxPay($id){            require_once (APPPATH.'libraries/Wxpay/log.php');            //初始化日志            $logHandler= new CLogFileHandler(APPPATH."libraries/Wxpay/logs/".date('Y-m-d').'.log');            Log::Init($logHandler, 15);            // 查預先生成的訂單信息            $this->load->model('order_model');            $o = $this->order_model->getMyOrderDetails($id);            // 調用微信掃碼支付接口配置信息            $this->load->config('wxpay_config');            $wxconfig['appid']=$this->config->item('appid');            $wxconfig['mch_id']=$this->config->item('mch_id');            $wxconfig['apikey']=$this->config->item('apikey');            $wxconfig['appsecret']=$this->config->item('appsecret');            $wxconfig['sslcertPath']=$this->config->item('sslcertPath');            $wxconfig['sslkeyPath']=$this->config->item('sslkeyPath');            //由于此類庫構造函數需要傳參,我們初始化類庫就傳參數給他吧            $this->load->library('CI_Wechatpay',$wxconfig);            $param['body']=$o['goods_name']; //"商品名稱(自行看文檔具體填什么)";            $param['attach']=$o['id']; // "我有個參數要傳我就穿了個id過來,這里不要有空格避免出錯";            $param['detail']=$o['order_code'];  //"我填了商品名稱加訂單號";            $param['out_trade_no']=$o['order_code']; //"商戶訂單號";            $param['total_fee']=$o['order_amount']*100; //"金額,記得乘以100,微信支付單位默認分";//如$total_fee*100            $param["spbill_create_ip"] =$_SERVER['REMOTE_ADDR'];//客戶端IP地址            $param["time_start"] = date("YmdHis");//請求開始時間            $param["time_expire"] = date("YmdHis", time() + 600);//請求超時時間 10分鐘            $param["goods_tag"] = urldecode('運費:') . $o['postage']; //商品標簽,自行填寫            $param["notify_url"] = "http://".$_SERVER['HTTP_HOST']."/wxnotify/"; //自行定義異步通知url            $param["trade_type"] = "NATIVE";//掃碼支付模式二            $param["product_id"] = $o['goods_id']; //正好有產品id就傳了個,看文檔說自己定義            //調用統一下單API接口            $result=$this->ci_wechatpay->unifiedOrder($param);//這里可以加日志輸出,            // 寫入日志            log::debug(json_encode($result));            //成功(return_code和result_code都為SUCCESS)就會返回含有帶支付二維碼鏈接的數據            $data=array();            if (isset($result["code_url"]) && !empty($result["code_url"])) {//二維碼圖片鏈接                $data['wxurl'] = $result["code_url"];                //這里傳遞商戶訂單號到掃碼視圖,是因為我想做跳轉,根據商戶號去查詢訂單是否支付成功,如果成功了就跳轉,定時輪詢微信服務器(這個誰有好的方法可以分享給我啊,表示感謝啦)                $data['orderno'] = $param['out_trade_no'];                // 寫入日志                                $this->assign('time_expire',strtotime($param["time_expire"])); //訂單失效時間                $this->assign('order_no',$data['orderno']);                $this->assign('wxurl',urlencode($data['wxurl'])); // 獲取到的二維碼地址                $this->display('wxpay/index.html');            }        }

    view/wxpay/index.html

    <!doctype html><html><head><meta charset="utf-8"><meta http-equiv="x-ua-compatible" content="ie=8" /><title>微信支付</title></head><body>    <div style="margin-left: 10px;color:#556B2F;font-size:30px;font-weight: bolder;">微信掃碼支付測試</div><br/>    <img alt="模式二掃碼支付" src="http://paysdk.weixin.qq.com/example/qrcode.php?data={{$wxurl}}" width="150"/>    <input type="hidden" name="orderNo" value="{{$order_no}}">    <input type="hidden" name="timeExpire" value="{{$time_expire}}"></body></html><script>    // 每3秒請求一次數據,然后判斷,跳轉     $(function(){    	timestamp = Date.parse( new Date())/1000; // 當前時間戳        orderno = $("input[name='orderNo']").val(); // 訂單編號        timeExpire = $("input[name='timeExpire']").val(); // 訂單失效時間        start = setInterval("checkstatus(orderno)", 3000);    });     function checkstatus(order_no){    	if(timestamp > timeExpire){  // 當前時間大于失效時間時,清除輪詢    		window.clearInterval(start);    	}else{	   $.ajax({	       // 這里調用wechatpay.php中的orderQuery接口查詢訂單狀態
    	       // 當返回值 trade_state == "SUCCESS"   這個時候可以修改你的訂單狀態了哦。
    	   });	        	}    }</script>


    OK!說的很細了,大家應該成功了吧。 歡迎大家發現問題并提出!共同解決。

    PHP編程

    鄭重聲明:本文版權歸原作者所有,轉載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯系我們修改或刪除,多謝。

  • 發表評論 共有條評論
    用戶名: 密碼:
    驗證碼: 匿名發表
    主站蜘蛛池模板: 巴南区| 庆元县| 南江县| 延吉市| 清水县| 时尚| 黑山县| 马公市| 厦门市| 疏勒县| 莒南县| 清丰县| 渝中区| 班玛县| 时尚| 昆明市| 衡阳市| 新竹县| 承德市| 名山县| 泰州市| 盱眙县| 永德县| 磐安县| 当雄县| 开平市| 蓝田县| 肥东县| 新民市| 宿迁市| 抚远县| 泗洪县| 句容市| 淳化县| 汝州市| 东乡| 墨脱县| 长乐市| 崇仁县| 潞西市| 新竹市|