标签:key sig x64 oda 按钮 dal site repo Once
微信支付的接入,如果不使用成熟的开发包,将是巨大的工作量。
先在 laravel 项目中依赖 easywechat
这个包
composer require "overtrue/laravel-wechat":"^4.0"
配置
在 .env 中添加微信支付的 key 配置
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.php
<?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.php
<?php
Route::post('/buy/pay', 'PayController@pay')->name('pay');
在页面 JS 里面编辑支付逻辑
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>
关于回调处理请期待下一篇文章。
原文地址:https://segmentfault.com/a/1190000016177743
标签:key sig x64 oda 按钮 dal site repo Once
原文地址:https://www.cnblogs.com/lalalagq/p/9973673.html