微信支付的接入,若是不使用成熟的開發包,將是巨大的工做量。php
先在 laravel 項目中依賴 easywechat
這個包html
composer require "overtrue/laravel-wechat":"^4.0"
配置
在 .env 中添加微信支付的 key 配置laravel
WECHAT_PAYMENT_SANDBOX=false WECHAT_PAYMENT_APPID=wx64c*** WECHAT_PAYMENT_MCH_ID=150*** WECHAT_PAYMENT_KEY=ZZDDD*** WECHAT_PAYMENT_CERT_PATH=/home/secret/apiclient_cert.pem WECHAT_PAYMENT_KEY_PATH=/home/secret/apiclient_key.pem WECHAT_PAYMENT_NOTIFY_URL=https://www.mysite.com/gateway/wxpay/callback
php artisan vendor:publish --provider="Overtrue\LaravelWeChat\ServiceProvider"
,而後在 config/wechat.php 中能夠看到 easywecaht 能夠支持的所有配置。新建一個 App/Repositories/PayRepository.php小程序
<?php namespace App\Repositories; use App\User; use function EasyWeChat\Kernel\Support\generate_sign; class PayRepository { /** * 發起微信支付 * * @return Array */ public function pay(User $user) { $this->wxpay = app('easywechat.payment'); $unify = $this->wxpay->order->unify([ 'body' => $this->transfer->name . ' ' . $this->tickets->count() . '張票', 'out_trade_no' => '訂單號', 'total_fee' => bcmul('價格:單位元', 100), 'trade_type' => 'JSAPI', 'openid' => $user->openid, // 用戶的openid ]); if ($unify['return_code'] === 'SUCCESS' && !isset($unify['err_code'])) { $pay = [ 'appId' => config('wechat.payment.default.app_id'), 'timeStamp' => (string) time(), 'nonceStr' => $unify['nonce_str'], 'package' => 'prepay_id=' . $unify['prepay_id'], 'signType' => 'MD5', ]; $pay['paySign'] = generate_sign($pay, config('wechat.payment.default.key')); return $pay; } else { $unify['return_code'] = 'FAIL'; return $unify; } } }
新建一個 App/Http/Controllers/PayController.phpsegmentfault
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Repositories\PayRepository; use Illuminate\Support\Facades\Response; class PayController extends Controller { /** * PayRepository * * @var PayRepository */ protected $pay_repository; public function __construct(PayRepository $pay_repository) { $this->pay_repository = $pay_repository; } /** * 微信支付 * * @return Response */ public function pay() { $user = auth()->user(); $pay = $this->pay_repository->pay($user); return Response::success(['pay' => $pay]); } }
綁定路由 routes/api.phpapi
<?php Route::post('/buy/pay', 'PayController@pay')->name('pay');
在頁面 JS 裏面編輯支付邏輯bash
onPay: function (e) { wx.request({ url: '/api/buy/pay', method: 'POST', success: (res) => { if (res.data.pay.result_code != 'SUCCESS') { return wx.showModal({ content: res.data.pay.return_msg + res.data.pay.err_code_des, showCancel: false }); } res.data.pay.success = (res) => { wx.showModal({ content: '您已成功支付', showCancel: false }); }; res.data.pay.fail = (res) => { if (res.errMsg == 'requestPayment:fail cancel') { return wx.showToast({ icon: 'none', title: '用戶取消支付', }); } }; wx.requestPayment(res.data.pay); } }); },
在頁面按鈕上調用微信
<button ontap="onPay">支付</button>
關於回調處理請期待下一篇文章。~
回調處理請見下文:Laravel教程: 3分鐘實現小程序微信支付接入(下)——回調發貨邏輯app
若是你不添加.env,可能會報容器找不到這個應用的報錯。composer