![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLicmbw5CMzMDM5gTM1I2MwMWMxMDM4MDZ3MGZzAzM1ITN1kTNj9CX0JXZ252bj91Ztl2Lc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
php中文網最新課程
每日17點準時技術幹貨分享
業務場景描述:
使用者點選站點頁面的 "購買" --> 即彈出二維碼 --> 使用者用微信掃描二維碼 --> 根據微信的指引完成支付 --> 支付成功後頁面提示支付成功并跳轉
與微信之間的互動就三步:
1.傳參,請求微信統一下單接口,擷取支付二維碼
2.接收微信的通知 (微信通過上一步參數中的回調位址,把支付結果發送給我的伺服器)
3.請求微信檢視訂單的接口,如果支付成功就跳轉頁面
下面的記錄也基本按照上面的流程.
準備工作:
安裝 overtrue/laravel-wechat
composer require "overtrue/laravel-wechat:~5.0"
建立配置檔案:
php artisan vendor:publish --provider="Overtrue\LaravelWeChat\ServiceProvider"
修改應用根目錄下的 config/wechat.php 中對應的參數 (這部分直接 copy /paste 就行了) :
'payment' => [ 'default' => [ 'sandbox' => env('WECHAT_PAYMENT_SANDBOX', false), 'app_id' => env('WECHAT_PAYMENT_APPID', ''), 'mch_id' => env('WECHAT_PAYMENT_MCH_ID', 'your-mch-id'), 'key' => env('WECHAT_PAYMENT_KEY', 'key-for-signature'), 'cert_path' => env('WECHAT_PAYMENT_CERT_PATH', 'path/to/cert/apiclient_cert.pem'), // XXX: 絕對路徑!!!! 'key_path' => env('WECHAT_PAYMENT_KEY_PATH', 'path/to/cert/apiclient_key.pem'), // XXX: 絕對路徑!!!! 'notify_url' => env('WECHAT_PAYMENT_NOTIFY_URL',''), // 預設支付結果通知位址 ], // ... ],
需要配置的就是上面這個數組裡的内容,但其實都是需要在 .env 檔案中配置的:
# wechat_paymentWECHAT_PAYMENT_SANDBOX=false# 真正需要配置的就下面這四行WECHAT_PAYMENT_APPID=xxxxxxxxxxxxxxx // 自己的WECHAT_PAYMENT_MCH_ID=xxxxxxx // 自己的WECHAT_PAYMENT_KEY=xxxxxxxxxxxxxxxxxxxx // 自己的WECHAT_PAYMENT_NOTIFY_URL='test.abc.com/payment/notify' // 這個位址隻要是外網能夠通路到項目的任何位址都可以, 不是需要在微信那裡配置的那種, 現在還不知道怎麼定義沒關系, 後面用到的時候自然就有了SWAGGER_VERSION=3.0
安裝 Simple QrCode 生成二維碼的包 在 composer.json 檔案中添加如下:
"require": { "simplesoftwareio/simple-qrcode": "~2"}
在終端執行: composer update, 後面會用到. 以上是準備工作,下面開始按照流程 使用者點選 "購買" 下單 --> 彈出二維碼 這裡是請求了微信的 統一下單 接口. 我處理的邏輯是: 使用者發起購買請求時,先在建立支付日志裡建立一條記錄,等到使用者完成付款,再建立訂單記錄. 建立一個 PaymentController 專門處理微信支付的邏輯 (跟 OrderController 是兩碼事). 對于使用者點選 "購買" 的請求,我用 "place_order" 的方法處理,也就是在這裡請求微信的 [統一下單] 接口. 頁面上發起下單請求的部分 Html 部分: (二維碼的 modal 框就是根據 Bootstrap 的文檔寫的)
<button type="button" id="order" class="btn btn-secondary btn-block"> 掃碼支付button><div class="modal fade" id="qrcode" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog modal-sm" role="document"> <div class="modal-content bg-transparent" style="border:none"> <div class="modal-body align-items-center text-center"> <p class="modal-title" id="exampleModalLabel" style="color:white">微信掃碼支付p> <br> {{--生成的二維碼會放在這裡--}} <div id="qrcode2">div> div> div> div> div>
JS 部分:
$('#order').click(function () { /** 請求下單接口 **/ axios.get("/payment/place_order", { params: { id: "{{ $post->id }}" } }).then(function (response) { if (response.data.code == 200) { /** 把生成的二維碼放到頁面上 */ $('#qrcode2').html(response.data.html); /** 彈出二維碼 **/ $('#qrcode').modal('show'); /** 設定定時器, 即一彈出二維碼就開始不斷請求檢視支付狀态, 直到收到支付成功的傳回, 再終止定時器 **/ var timer = setInterval(function () { /** 在這裡請求微信支付狀态的接口 **/ axios.get('/payment/paid', { params: { 'out_trade_no':response.data.order_sn, } }).then(function (response) { if (response.data.code == 200) { /** 如果支付成功, 就取消定時器, 并重新加載頁面 */ window.clearInterval(timer); window.location.reload(); } }).catch(function (error) { console.log(error); }); }, 3000); } }).catch(function (error) { console.log(error); }); });
建立路由 這裡先把上面 JS 部分請求的兩個路由都先寫出來了,下面先說明第一個:
// 請求微信統一下單接口Route::get('/payment/place_order', '[email protected]_order')->name('web.payment.place_order');// 請求微信接口, 檢視訂單支付狀态Route::get('/payment/paid', '[email protected]')->name('web.payment.paid');PaymentController 裡的支付邏輯下面是具體的邏輯,使用者點選支付後,先建立一條記錄在 PayLog (用來記錄支付的詳細資訊,是以這裡還需要建 Paylog 的 model 和 migration, migration 的内容我附在最後了,都是微信傳回的字段,基本可以直接 copy 來用的)class PaymentController extends Controller{ // 請求微信接口的公用配置, 是以單獨提出來 private function payment(){ $config = [ // 必要配置, 這些都是之前在 .env 裡配置好的 'app_id' => config('wechat.payment.default.app_id'), 'mch_id' => config('wechat.payment.default.mch_id'), 'key' => config('wechat.payment.default.key'), // API 密鑰 'notify_url' => config('wechat.payment.default.notify_url'), // 通知位址 ]; // 這個就是 easywechat 封裝的了, 一行代碼搞定, 照着寫就行了 $app = Factory::payment($config); return $app; } // 向微信請求統一下單接口, 建立預支付訂單 public function place_order($id){ // 因為沒有先建立訂單, 是以這裡先生成一個随機的訂單号, 存在 pay_log 裡, 用來辨別訂單, 支付成功後再把這個訂單号存到 order 表裡 $order_sn = date('ymd').substr(time(),-5).substr(microtime(),2,5); // 根據文章 id 查出文章價格 $post_price = optional(Post::where('id', $id)->first())->pirce; // 建立 Paylog 記錄 PayLog::create([ 'appid' => config('wechat.payment.default.app_id'), 'mch_id' => config('wechat.payment.default.mch_id'), 'out_trade_no' => $order_sn, 'post_id' => $id ]); $app = $this->payment(); $total_fee = env('APP_DEBUG') ? 1 : $post_price; // 用 easywechat 封裝的方法請求微信的統一下單接口 $result = $app->order->unify([ 'trade_type' => 'NATIVE', // 原生支付即掃碼支付,商戶根據微信支付協定格式生成的二維碼,使用者通過微信“掃一掃”掃描二維碼後即進入付款确認界面,輸入密碼即完成支付。 'body' => '投資平台-訂單支付', // 這個就是會展示在使用者手機上巨款界面的一句話, 随便寫的 'out_trade_no' => $order_sn, 'total_fee' => $total_fee, 'spbill_create_ip' => request()->ip(), // 可選,如不傳該參數,SDK 将會自動擷取相應 IP 位址 ]); if ($result['result_code'] == 'SUCCESS') { // 如果請求成功, 微信會傳回一個 'code_url' 用于生成二維碼 $code_url = $result['code_url']; return [ 'code' => 200, // 訂單編号, 用于在目前頁面向微信伺服器發起訂單狀态查詢請求 'order_sn' => $order_sn, // 生成二維碼 'html' => QrCode::size(200)->generate($code_url), ]; } }}
與微信互動的第一步 (請求統一下單接口) 完成 接收微信的 通知 路由 微信根據上面請求中傳參的 notify_url 請求我的伺服器,發送支付結果給我,那麼必然是 post 請求:
Route::post('/payment/notify', '[email protected]');
取消 csrf 驗證 但是,微信伺服器發起的 post 請求無法通過 csrf token 驗證,是以必須取消用于微信的路由的驗證,在 app/Http/Middleware/VerifyCsrfToken 檔案中:
protected $except = [ // 'payment/notify' ];在 PaymentController.php 檔案中處理接收微信資訊的邏輯 // 接收微信支付狀态的通知 public function notify(){ $app = $this->payment(); // 用 easywechat 封裝的方法接收微信的資訊, 根據 $message 的内容進行處理, 之後要告知微信伺服器處理好了, 否則微信會一直請求這個 url, 發送資訊 $response = $app->handlePaidNotify(function($message, $fail){ // 首先檢視 order 表, 如果 order 表有記錄, 表示已經支付過了 $order = Order::where('order_sn', $message['out_trade_no'])->first(); if ($order) { return true; // 如果已經生成訂單, 表示已經處理完了, 告訴微信不用再通知了 } // 檢視支付日志 $payLog = PayLog::where('out_trade_no', $message['out_trade_no'])->first(); if (!$payLog || $payLog->paid_at) { // 如果訂單不存在 或者 訂單已經支付過了 return true; // 告訴微信,我已經處理完了,訂單沒找到,别再通知我了 } // return_code 表示通信狀态,不代表支付狀态 if ($message['return_code'] === 'SUCCESS') { // 使用者是否支付成功 if ($message['result_code'] === 'SUCCESS') { // 更新支付時間為目前時間 $payLog->paid_at = now(); $post_id = $payLog->post_id; // 聯表查詢 post 的相關資訊 $post_title = $payLog->post->title; $post_price = $payLog->post->price; $post_original_price = $payLog->post->original_price; $post_cover = $payLog->post->post_cover; $post_description = $payLog->post->description; $user_id = $payLog->post->user_id; // 建立訂單記錄 Order::create([ 'order_sn' => $message['out_trade_no'], 'total_fee' => $message['total_fee'], 'pay_log_id' => $payLog->id, 'status' => 1, 'user_id' => $user_id, 'paid_at' => $payLog->paid_at, 'post_id' => $post_id, 'post_title' => $post_title, 'post_price' => $post_price, 'post_original_price' => $post_original_price, 'post_cover' => $post_cover, 'post_description' => $post_description, ]); // 更新 PayLog, 這裡的字段都是根據微信支付結果通知的字段設定的(https://pay.weixin.qq.com/wiki/doc/api/native.php?chapter=9_7&index=8) PayLog::where('out_trade_no', $message['out_trade_no'])->update([ 'appid' => $message['appid'], 'bank_type' => $message['bank_type'], 'total_fee' => $message['total_fee'], 'trade_type' => $message['trade_type'], 'is_subscribe' => $message['is_subscribe'], 'mch_id' => $message['mch_id'], 'nonce_str' => $message['nonce_str'], 'openid' => $message['openid'], 'sign' => $message['sign'], 'cash_fee' => $message['cash_fee'], 'fee_type' => $message['fee_type'], 'transaction_id' => $message['transaction_id'], 'time_end' => $payLog->paid_at, 'result_code' => $message['result_code'], 'return_code' => $message['return_code'], ]); } } else { // 如果支付失敗, 也更新 PayLog, 跟上面一樣, 就是多了 error 資訊 PayLog::where('out_trade_no', $message['out_trade_no'])->update([ 'appid' => $message['appid'], 'bank_type' => $message['bank_type'], 'total_fee' => $message['total_fee'], 'trade_type' => $message['trade_type'], 'is_subscribe' => $message['is_subscribe'], 'mch_id' => $message['mch_id'], 'nonce_str' => $message['nonce_str'], 'openid' => $message['openid'], 'sign' => $message['sign'], 'cash_fee' => $message['cash_fee'], 'fee_type' => $message['fee_type'], 'transaction_id' => $message['transaction_id'], 'time_end' => $payLog->paid_at, 'result_code' => $message['result_code'], 'return_code' => $message['return_code'], 'err_code' => $message['err_code'], 'err_code_des' => $message['err_code_des'], ]); return $fail('通信失敗,請稍後再通知我'); } return true; // 傳回處理完成 }); // 這裡是必須這樣傳回的, 會發送給微信伺服器處理結果 return $response; }
上面有用到 pay_logs 表和 posts 表的聯表查詢,一篇 post 可以有多個 pay_logs, 是以是一對多的關系,在 PayLog.php 裡設定一下:
public function post(){ return $this->belongsTo(Post::class);}
與微信互動的第二步 (接收資訊), 完成 請求微信 檢視訂單 接口 請求微信檢視訂單狀态接口,路由在互動第一步已經寫過了
public function paid(Request $request){ $out_trade_no = $request->get('out_trade_no'); $app = $this->payment(); // 用 easywechat 封裝的方法請求微信 $result = $app->order->queryByOutTradeNumber($out_trade_no); if ($result['trade_state'] === 'SUCCESS') return [ 'code' => 200, 'msg' => 'paid' ]; }else{ return [ 'code' => 202, 'msg' => 'not paid' ]; } }
與微信互動的第三步 (檢視訂單狀态), 完成 附: pay_logs 表的 migration 由于此表的字段基本就是微信支付結果通知的字段,是以附在下面友善下次使用:
public function up(){ Schema::create('pay_logs', function (Blueprint $table) { $table->bigIncrements('id'); // 根據自身業務設計的字段 $table->integer('post_id')->default(0)->comment('文章id'); // 以下均是微信支付結果通知接口傳回的字段 $table->string('appid', 255)->default('')->comment('微信配置設定的公衆賬号ID'); $table->string('mch_id', 255)->default('')->comment('微信支付配置設定的商戶号'); $table->string('bank_type', 16)->default('')->comment('付款銀行'); $table->integer('cash_fee')->default(0)->comment('現金支付金額'); $table->string('fee_type', 8)->default('')->comment('貨币種類'); $table->string('is_subscribe', 1)->default('')->comment('是否關注公衆賬号'); $table->string('nonce_str', 32)->default('')->comment('随機字元串'); $table->string('openid', 128)->default('')->comment('使用者辨別'); $table->string('out_trade_no', 32)->default('')->comment('商戶系統内部訂單号'); $table->string('result_code', 16)->default('')->comment('業務結果'); $table->string('return_code', 16)->default('')->comment('通信辨別'); $table->string('sign', 32)->default('')->comment('簽名'); $table->string('prepay_id', 64)->default('')->comment('微信生成的預支付回話辨別,用于後續接口調用中使用,該值有效期為2小時'); $table->dateTime('time_end')->nullable()->comment('支付完成時間'); $table->integer('total_fee')->default(0)->comment('訂單金額'); $table->string('trade_type', 16)->default('')->comment('交易類型'); $table->string('transaction_id', 32)->default('')->comment('微信支付訂單号'); $table->string('err_code', 32)->default('')->comment('錯誤代碼'); $table->string('err_code_des', 128)->default('')->comment('錯誤代碼描述'); $table->string('device_info', 32)->default('')->comment('裝置号'); $table->text('attach')->nullable()->comment('商家資料包'); $table->nullableTimestamps(); }); }
以上,就是從頁面到下單到支付到頁面跳轉的全過程記錄。除了很久以前跟着 Laravel-china 教程做過一次,這算是真正第一次自己摸索,根據自己的需求做的一次。
網上分享的文章教程也很多,但都是大神級别的,很多地方都一筆帶過,對于我這種 junior 的感覺就是東一榔頭,西一棒槌,很難 follow.
我盡最大努力把筆記整理得細緻些,希望對跟我一樣的 beginner 有幫助。
看着是很長啊,但是,真的實作也真得這麼多内容吧,至少以我目前的水準是這樣的.
-END-
聲明:本文選自「 php中文網 」,搜尋「 phpcnnew 」即可關注!
▼