PHPcms微信支付

weixin_33860722發表於2016-06-20

基本上按照官方給的sdk修改的沒有改動太多東西
微信支付有些麻煩 需要在微信公眾平臺上設定-支付授權目錄(重要)和-[網頁授權獲取使用者基本資訊](重要)
流程已經走通 因為各個專案的不同僅供參考吧
有好的建議請留言

2020867-cf79255884de143c.png
Paste_Image.png

1.去官網下載

2020867-657ce201b7e2c89d.png
Paste_Image.png

https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=11_1

2.重新建立目錄結構

2020867-6684abbcce045f10.png
Paste_Image.png

3.在模組方法中建立方法

注微信支付中獲取code和openid時容易丟失傳遞值 可以考慮cookie傳值

 public function wx_pay() {
    include PHPCMS_PATH . '/wxpay/lib/WxPay.Api.php';
    include PHPCMS_PATH . '/wxpay/WxPay.JsApiPay.php';
    include PHPCMS_PATH . '/wxpay/log.php';
    $logHandler = new CLogFileHandler(PHPCMS_PATH . "'/wxpay/logs/" . date('Y-m-d') . '.log');
    $log = Log::Init($logHandler, 15);
    //①、獲取使用者openid
    $tools = new JsApiPay();
    $openId = $tools->GetOpenid();
    $list['cate_name'] = param::get_cookie('cate_name');
    $list['amount'] = param::get_cookie('amount');
    $list['order_sn'] = param::get_cookie('order_sn');
    //②、統一下單
    $input = new WxPayUnifiedOrder();
    $input->SetBody($list['cate_name']);
    $input->SetAttach($list['cate_name']);
    $input->SetOut_trade_no($list['order_sn']);
    $input->SetTotal_fee($list['amount'] * 100);
    $input->SetTime_start(date("YmdHis"));
    $input->SetTime_expire(date("YmdHis", time() + 600));
    $input->SetGoods_tag("test");
    $input->SetNotify_url("http://www.www.com/wxpay/notify.php");
    $input->SetTrade_type("JSAPI");
    $input->SetOpenid($openId);
    $order = WxPayApi::unifiedOrder($input);
    $list['jsApiParameters'] = $tools->GetJsApiParameters($order);
    //var_dump($list);exit;
    include template('xxx', 'xxx', 'default');
}

4.前臺頁面

<!DOCTYPE html>
<html lang="en">

<head>
    <meta http-equiv="content-type" content="text/html;charset=utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/> 
    <title>支付</title>
    <script type="text/javascript">
        //呼叫微信JS api 支付
        function jsApiCall() {
            WeixinJSBridge.invoke(
                'getBrandWCPayRequest', 
                {$list[jsApiParameters]},
                function(res) {
                    WeixinJSBridge.log(res.err_msg);
                    if (res.err_msg == "get_brand_wcpay_request:ok") {
                        window.location.href = "";
                    } else {
                        //返回跳轉到訂單詳情頁面
                        alert(支付失敗);
                        window.location.href = "";
                    }
                }
            );
        }

        function callpay() {
            if (typeof WeixinJSBridge == "undefined") {
                if (document.addEventListener) {
                    document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
                } else if (document.attachEvent) {
                    document.attachEvent('WeixinJSBridgeReady', jsApiCall);
                    document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
                }
            } else {
                jsApiCall();
            }
        }
    </script>
</head>

<body>
    <div class="receive">
        <h2>微信支付</h2>
        <ul class="form-list">
        
            <p class="submit" type="button" onclick="callpay()">立即支付</p>
        </ul>
    </div>
</body>

</html>

5.回撥函式

經測試回撥連結不支援拼接連結 因為趕時間沒有進行其他的實現方法
回撥函式 /wxpay/notify.php

<?php

ini_set('date.timezone','Asia/Shanghai');
error_reporting(E_ERROR);
require_once "lib/WxPay.Api.php";
require_once 'lib/WxPay.Notify.php';
require_once 'log.php';

//初始化日誌
$logHandler= new CLogFileHandler("logs/".date('Y-m-d').'.log');
$log = Log::Init($logHandler, 15);

class PayNotifyCallBack extends WxPayNotify
{
function __construct()
{

    // $hostname = "localhost";
    // $database = "cmsv";
    // $username = "root";
    // $password = "root";


    $conn = mysql_connect($hostname, $username, $password) or trigger_error(mysql_error(),E_USER_ERROR); 
    mysql_select_db($database, $conn);
}
//查詢訂單
public function Queryorder($transaction_id)
{
    $input = new WxPayOrderQuery();
    $input->SetTransaction_id($transaction_id);
    $result = WxPayApi::orderQuery($input);
    Log::DEBUG("query:" . json_encode($result));
    if(array_key_exists("return_code", $result)
        && array_key_exists("result_code", $result)
        && $result["return_code"] == "SUCCESS"
        && $result["result_code"] == "SUCCESS")
    {
        return true;
    }
    return false;
}

//重寫回撥處理函式
public function NotifyProcess($data, &$msg)
{
    Log::DEBUG("call back:" . json_encode($data));
    $notfiyOutput = array();
    
    if(!array_key_exists("transaction_id", $data)){
        $msg = "輸入引數不正確";
        return false;
    }
    //查詢訂單,判斷訂單真實性
    if(!$this->Queryorder($data["transaction_id"])){
        $msg = "訂單查詢失敗";
        return false;
    }
    $order_sn = $data["out_trade_no"];
            $transaction_id = $data["transaction_id"];
    $amount = $data["total_fee"]/100;
    $query = "SELECT ...";
    $result = mysql_query($query); 
    $row = mysql_fetch_array($result);
    $time = time();
    Log::DEBUG("v2_code_order:" . json_encode($row));
    if($amount == $row['amount']){
        $sql2 = "SELECT id,code_sn FROM ...";
        $re = mysql_query($sql2); 
        $code = mysql_fetch_array($re);
        Log::DEBUG("code_ll:" . json_encode($code));
        $sql_code="UPDATE v2_code SET..";
        $code_up = mysql_query($sql_code);

        $sql_order="UPDATE v2_code_order SET ...'";
        $order_up = mysql_query($sql_order);
        Log::DEBUG("code_up:" . json_encode($code_up));
        Log::DEBUG("order_up:" . json_encode($order_up));

    }else{
        return false;
    }
    
    
    return true;
}
}

Log::DEBUG("begin notify");
$notify = new PayNotifyCallBack();
$notify->Handle(false);

6.微信支付掃碼支付(介面)

public function jsapi()
{
    include PHPCMS_PATH . '/wxpay/lib/WxPay.Api.php';
    include PHPCMS_PATH . '/wxpay/WxPay.JsApiPay.php';
    include PHPCMS_PATH . '/wxpay/WxPay.NativePay.php';
    include PHPCMS_PATH . '/wxpay/log.php';

    if ($_POST['user_name'] && $_POST['amount'] && $_POST['title'] && $_POST['user_id']) {
        $order_sn = date("YmdHis") . substr(time(), -3) . str_pad(mt_rand(1, 9999999), 7, '0', STR_PAD_LEFT);

        $order['order_sn']     = $order_sn;
        $order['amount']       = $_POST['amount'];
        $order['user_phone']   = $_POST['user_phone'];
        $order['user_id']      = $_POST['user_id'];
        $order['source']       = $_POST['source'];
        $order['user_address'] = $_POST['user_address'];
        $order['user_name']    = $_POST['user_name'];
        $order['cate_name']    = $_POST['title'];
        $order['cate_id']      = 101;
        $order['c_time']       = time();

        $re = 1;
        if ($re) {
            $notify = new NativePay();
            $input  = new WxPayUnifiedOrder();
            $input->SetBody($_POST['title']);
            $input->SetAttach($_POST['title']);
            $input->SetOut_trade_no($order_sn);
            $input->SetTotal_fee($_POST['amount'] * 100);
            $input->SetTime_start(date("YmdHis"));
            $input->SetTime_expire(date("YmdHis", time() + 600));
            $input->SetGoods_tag("xxxx");
            $input->SetNotify_url("http://www.xxxx.com/wxpay/notify.php");
            $input->SetTrade_type("NATIVE");
            $input->SetProduct_id(time());
            $result = $notify->GetPayUrl($input);
            $url    = $result["code_url"];

            $url = $result["code_url"];
        }
    }

相關文章