a QR code pops up --> the user scans the QR code using WeChat --> completes the payment according to WeChat's instructions --> after the payment is successful, the page prompts that the payment is successful and jumps"/> a QR code pops up --> the user scans the QR code using WeChat --> completes the payment according to WeChat's instructions --> after the payment is successful, the page prompts that the payment is successful and jumps">
Home >PHP Framework >Laravel >(easywechat + Laravel 5.8) Organize the whole process of WeChat scan code payment on PC
Business scenario description:
The user clicks "Purchase" on the site page --> A QR code pops up --> The user scans the QR code using WeChat --> ; Complete the payment according to WeChat's instructions --> After the payment is successful, the page will prompt that the payment is successful and jump
The interaction with WeChat is in three steps:
1 . Pass parameters, request WeChat unified ordering interface, and obtain the payment QR code
2. Receive notifications from WeChat (WeChat sends the payment results to my server through the callback address in the parameters of the previous step)
3. Request WeChat to view the order interface. If the payment is successful, the page will jump.
The following records basically follow the above process.
Preparation work:
Installationovertrue/laravel-wechat
composer require "overtrue/laravel-wechat:~5.0"
Create configuration file:
php artisan vendor:publish --provider="Overtrue\LaravelWeChat\ServiceProvider"
Modify the corresponding config/wechat.php in the application root directory Parameters (just copy /paste this part):
'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',''), // 默认支付结果通知地址 ], // ... ],
What needs to be configured is the content in the above array, but in fact they all need to be configured in the .env file:
# wechat_payment WECHAT_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
Installation Simple QrCode Generate QR code package
Add the following in the composer.json file:
"require": { "simplesoftwareio/simple-qrcode": "~2" }
Execute in the terminal: composer update , will be used later.
---------------------------------------------- ----The above is the preparation work, let’s start following the process--------------------------------------------- --
The user clicks "Purchase" Place an order --> Pop-up QR code
Here is the request for WeChatUnified order Interface.
The logic I process is:
When the user initiates a purchase request, first create a record in the payment log, wait until the user completes the payment, and then create an order record.
Create a new PaymentController specifically to handle the logic of WeChat payment (which is different from the OrderController). For the user's request to click "Purchase", I use the "place_order" method to process it, that is, request WeChat's [Unified Order] interface here.
The part on the page that initiates the order request
Html part:
(The modal box of the QR code is written according to the Bootstrap document)
<button type="button" id="order" class="btn btn-secondary btn-block"> 扫码支付 </button> <!-- 二维码, 随便放在当前页面的那里都可以, 因为是通过 axios 控制, 请求成功后才会弹出的 --> <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 part:
$('#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); }); });
Create route
Here, first put the two routes requested in the JS part above It’s written, let’s first explain the first one:
// 请求微信统一下单接口 Route::get('/payment/place_order', 'PaymentController@place_order')->name('web.payment.place_order'); // 请求微信接口, 查看订单支付状态 Route::get('/payment/paid', 'PaymentController@paid')->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), ]; } } }
----------- The first step in interacting with WeChat (requesting a unified ordering interface) Completed------ -----
Receive notifications from WeChat
Routing
WeChat requests according to the above The notify_url of the upload parameter requests my server to send the payment result to me, so it must be a post request:
Route::post('/payment/notify', 'paymentController@notify');
Cancel csrf verification
However, the WeChat server initiated The post request cannot pass csrf token verification, so the verification of the route used for WeChat must be cancelled. In the app/Http/Middleware/VerifyCsrfToken file:
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; }
The above is a joint table query using the pay_logs table and the posts table. A post can have multiple pay_logs, so it is a one-to-many relationship. Set it in PayLog.php:
public function post() { return $this->belongsTo(Post::class); }
--------------- Interact with WeChat The second step (receiving information), complete --------------
Request WeChatView orderInterface
Request WeChat to view the order status interface, the routing has been written in the first step of interaction
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' ]; } }
----------------The third step of interacting with WeChat (Check order status), completed----------------
Attachment: migration of pay_logs table
Since the fields in this table are basically WeChat payment The fields for the result notification are attached below for easy use next time:
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(); }); }
The above is a record of the entire process from page to order to payment to page jump. Except for following the Laravel-china tutorial once a long time ago, this is the first time I really explored it myself and made it according to my own needs. There are many articles and tutorials shared on the Internet, but they are all at the master level, and many places are mentioned in one stroke. For a junior like me, it feels like a hammer in one place and a mallet in the other. It is difficult to follow. I tried my best to organize the notes in detail. , I hope it will be helpful to beginners like me. It looks very long, but it really requires so much content, at least at my current level.
The above is the detailed content of (easywechat + Laravel 5.8) Organize the whole process of WeChat scan code payment on PC. For more information, please follow other related articles on the PHP Chinese website!