easywechat之微信支付--在thinkPHP5中的使用


1. 准備工作

1.1 easywechat 安裝完成

未安裝移步至 -> http://www.cnblogs.com/flyphper/p/8484600.html

1.2 確定支付相關的配置參數已經配置好

<?php

return [
    /**
     * Debug 模式,bool 值:true/false
     *
     * 當值為 false 時,所有的日志都不會記錄
     */
    'debug'  => true,
    /**
     * 賬號基本信息,請從微信公眾平台/開放平台獲取
     */
    'app_id'  => '',         // AppID
    'secret'  => '',     // AppSecret
    'token'   => '',          // Token
    'aes_key' => '',                    // EncodingAESKey,安全模式下請一定要填寫!!!
    /**
     * 日志配置
     *
     * level: 日志級別, 可選為:
     *         debug/info/notice/warning/error/critical/alert/emergency
     * permission:日志文件權限(可選),默認為null(若為null值,monolog會取0644)
     * file:日志文件位置(絕對路徑!!!),要求可寫權限
     */
    'log' => [
        'level'      => 'debug',
        'permission' =>  0777,
        'file'       =>  LOG_PATH.'easywechat.log',
    ],
    /**
     * OAuth 配置
     *
     * scopes:公眾平台(snsapi_userinfo / snsapi_base),開放平台:snsapi_login
     * callback:OAuth授權完成后的回調頁地址
     */
    'oauth' => [
        'scopes'   => ['snsapi_userinfo'],
        'callback' => 'home/oauthallback',
    ],
    /**
     * 微信支付
     */
    'payment' => [
        'merchant_id'        => '', // 商戶號
        'key'                => '',
        'cert_path'          => '', // XXX: 絕對路徑!!!!(前往微信公眾平台上下載)
        'key_path'           => '',      // 同上
        // 'device_info'     => '',
        // 'sub_app_id'      => '',
        // 'sub_merchant_id' => '',
        // ...
    ],
    /**
     * Guzzle 全局設置
     *
     * 更多請參考: http://docs.guzzlephp.org/en/latest/request-options.html
     */
    'guzzle' => [
        'timeout' => 3.0, // 超時時間(秒)
        'verify' => true
    ]
];

2. 支付操作

2.1 添加訂單

wechat1.php

<?php
/**
 * ======================================
 *
 * Created by Super Demon W.
 * Author: \/Lin\/ 764582547@qq.com
 * Date: 2018/2/22
 * Time: 17:09
 *
 * =======================================
 */
namespace app\home\logic;

use think\Model;
use EasyWeChat\Foundation\Application;
use EasyWeChat\payment\Order;
use think\Config;

class Wechat1 extends Model {
    /**
     * 支付准備
     * @param $data
     * @param $openid
     * @return array
     */
    public function WeixinPrePay($data, $openid) {
        $options = Config::get('wechat');
        $app = new Application($options);
        $payment = $app->payment;
        $attributes = [
            'body' => '***-充值',
            'out_trade_no' => $data['order_sn'],
            'total_fee' => $data['money']*100,
            #'spbill_create_ip' => '***',
            'notify_url' => url('**/notify'), // 回調地址
            'trade_type' => 'JSAPI',
            'openid' => $openid,
        ];

        $order = new Order($attributes);
        $result = $payment->prepare($order);
        if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS') {
            $prepayId = $result->prepay_id;
            $json = $payment->configForPayment($prepayId);
            return ['status' => 200, 'msg' => '', 'data' => $json];
        } else {
            return ['status' => 400, 'msg' => '調起支付失敗,請稍后嘗試'];
        }
    }
}

2.2 添加訂單后調起支付

towxpay.php

namespace app\home\controller;
use app\home\logic\Wechat1;
use think\Session;
use think\Db;

public function towxpay() {
        $uid = Session::get('user_auth')['uid'];
        $money = input('recharge_money', '');
        $wechat = new Wechat1();
        $order_sn = MakeOrderSn(); // 設置訂單號
        # 添加訂單
        $data = array(
                // ...yourdata
        );
        $order_id = db('order')->insertGetId($data);
        if (!$order_id) {
            $this->error('訂單添加失敗');
        }
        $openid = db('member')->where('uid', $uid)->value('openid');
        $check = $wechat->WeixinPrePay($data, $openid);
        if ($check['status'] == 400) {
             $this->error($check['msg']);
        }
        session::set('zejc_order_id', $order_id);
        $this->assign('jsonData', $check['data']);
        return $this->fetch();  
    }

2.3 調取支付頁面

 towxpay.html

<html>
<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',{$jsonData},
                function(res){
                    if (res.err_msg == "get_brand_wcpay_request:ok") { // 支付成功
                        location.href = '***?type=success';
                    }
                    if(res.err_msg == "get_brand_wcpay_request:fail") { // 支付失敗
                        location.href = '***?type=fail';
                    }
                    if (res.err_msg == "get_brand_wcpay_request:cancel") { // 取消支付
                        location.href = '***?type=cancel';
                    }
                }
            );
        }

        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();
            }
        }
        callpay();
    </script>
</head>
<body>
<div align="center" style="color: #00a157; margin-top: 20%">
    支付中...
</div>
</body>
</html>

 注: 統一下單后返回prepay_id后要調用小程序支付函數,有最重要的一步,是需要再次簽名的,用統一下單返回的sign(簽名)是沒有用的。

================== 至此,微信支付結束 ===============


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM