1、微信支付
1.1、安裝依賴包
- 我這裏使用 EasyWeChat 實現微信支付,另外我附上之前我封裝的微信類。
- 詳細操作裏面寫的比較清楚,請先看這個:https://www.jianshu.com/p/d376d921bf16
1.2、準備工作
(1)需要去微信開放平臺註冊賬號
- appid(微信開放平臺上的應用id)
- mch_id(微信申請成功之後郵件中的商戶id)
- notify_url(支付成功後的回調地址)
- api_key(在微信商戶平臺上自己設定的api密鑰 32位)
- apiclient_cert.pem 和 apiclient_key.pem 證書
相關的申請流程可以參考網站: https://developers.weixin.qq.com/doc/oplatform/Mobile_App/WeChat_Pay/Vendor_Service_Center.html
(2)將對應的配置寫入配置文件中(配置文件可以參考我下面封裝的微信類)
(3)創建訂單表
- 關於訂單表,這裏給你們參考下我的
1.3、封裝 WechatServer.php
微信服務類
<?php
namespace app\common\service;
use EasyWeChat\Factory;
use EasyWeChat\MiniProgram\Application;
use think\Hook;
/**
* 微信服務
* @package app\common\service
*/
class WeChatService
{
//微信公衆號配置
private $officeConfig = [
'app_id' => 'asdasdasf23413', //測試號
'secret' => 'asdasdasr3421412412312312', //測試號
// 'app_id' => '515125141',
// 'secret' => '123131212asdasdsadasd',
// 指定 API 調用返回結果的類型:array(default)/collection/object/raw/自定義類名
'response_type' => 'array',
//...
];
//默認APP微信支付,修改appId和secret就可以換其他方式支付
private $appPayConfig= [
// 必要配置
'app_id' => 'asdasdasf23413',
'secret' => 'asdasdasr3421412412312312', //
'mch_id' => '515125141',
'key' => 'asdasdasdas', // API 密鑰
// 如需使用敏感接口(如退款、發送紅包等)需要配置 API 證書路徑(登錄商戶平臺下載 API 證書)
'cert_path' => PUBLIC_PATH . '/wechatCert/apiclient_cert.pem', // XXX: 絕對路徑!!!!
'key_path' => PUBLIC_PATH . '/wechatCert/apiclient_key.pem', // XXX: 絕對路徑!!!!
'notify_url' => '', // 你也可以在下單時單獨設置來想覆蓋它
'log' => [
'level' => 'debug',
'file' => PUBLIC_PATH . '/logs/pay_wechat.log',
],
];
//微信小程序配置
private $miniConfig = [
'app_id' => 'qwad312321312312',
'secret' => 'asdasdasdasdasdasdweqe',
// 下面爲可選項
// 指定 API 調用返回結果的類型:array(default)/collection/object/raw/自定義類名
'response_type' => 'array',
'log' => [
'level' => 'debug',
'file' => PUBLIC_PATH . '/logs/mini_wechat.log',
],
];
//開放平臺配置
private $openConfig = [
'app_id' => '開放平臺第三方平臺 APPID',
'secret' => '開放平臺第三方平臺 Secret',
'token' => '開放平臺第三方平臺 Token',
'aes_key' => '開放平臺第三方平臺 AES Key'
];
private $token = ''; //獲取小程序的ACCESS_TOKEN
private $isContract = false; //是否開啓支付中籤約
/**
* @ApiTitle (實例化)
*/
public function connect($type = 0)
{
//實例化對象
if ($type == 0) $app = Factory::miniProgram($this->miniConfig); //微信小程序
if ($type == 1) $app = Factory::officialAccount($this->officeConfig); //微信公衆號
if ($type == 3) $app = Factory::openPlatform($this->openConfig); //微信開放平臺
if ($type == 10) $app = Factory::payment($this->payConfig); //微信支付
if ($type == 11) {
$this->appPayConfig['app_id'] = 'wx652625123238453'; //小程序appId
$this->appPayConfig['secret'] = 'a51dsa5d1w22222wq5e3qw151q'; //小程序祕鑰
$app = Factory::payment($this->appPayConfig); //微信小程序支付
} else if ($type == 12 || $type == 13 || $type == 14) {
$this->appPayConfig['app_id'] = 'wx5a13sd5a1sd3as5d1'; //公衆號Id
$this->appPayConfig['secret'] = '5s1ad51as3d5w413d21a5w1w523'; //公衆號祕鑰
$app = Factory::payment($this->appPayConfig); //H5支付、生成支付二維碼
}
//獲取token
$accessToken = $app->access_token;
$this->token = $accessToken->getToken()['access_token']; // token 數組 token['access_token'] 字符串
return $app ?? false;
}
/**
* 統一下單
* @param int $payType 支付類型(10-APP微信支付 11-微信小程序支付 12-微信外部H5調起支付 13-生成微信支付二維碼 14-微信內部H5調起支付)
* @param string $body 描述
* @param string $oderNumber 訂單號
* @param float $amount 金額
* @param string $openid 公衆openid
* @return array|\EasyWeChat\Kernel\Support\Collection|object|\Psr\Http\Message\ResponseInterface|string
* @throws \EasyWeChat\Kernel\Exceptions\HttpException
* @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
* @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
* @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
* @throws \GuzzleHttp\Exception\GuzzleException
* @throws \Psr\SimpleCache\InvalidArgumentException
* @throws Exception
*/
public function unify($payType, $body, $oderNumber, $amount, $openid = '')
{
$app = (new WeChatService())->connect($payType);
if ($payType == 10) $tradeType = 'APP';
if ($payType == 11) $tradeType = 'JSAPI';
if ($payType == 12) $tradeType = 'MWEB';
if ($payType == 13) $tradeType = 'NATIVE';
if ($payType == 14) $tradeType = 'JSAPI';
$data = [
'body' => $body,
'out_trade_no' => $oderNumber,
'total_fee' => $amount * 100, // **單位:分**
'notify_url' => 'http://test.sulinks.com/api/Payment/wechatNotify', // 支付結果通知網址,如果不設置則會使用配置裏的默認地址
'trade_type' => $tradeType, // 請對應換成你的支付方式對應的值類型
// 'spbill_create_ip' => '', // 可選,如不傳該參數,SDK 將會自動獲取相應 IP 地址
// 'openid' => $openId, //從用戶額外表中取到openId
];
if ($payType == 11) {
//小程序
$uid = db('sulink_user_account')->where('order_number', $oderNumber)->value('from_id');
$openid = db('weixin_user')->where('uid', $uid)->value('routine_openid');
if (!$openid) throw new Exception('該用戶不存在openId');
$data['openid'] = $openid;
} else if ($payType == 12) {
//微信外部的H5頁面
$data['spbill_create_ip'] = '8.129.13.43';
} else if ($payType == 13) {
//生成微信支付二維碼
$data['product_id'] = $oderNumber;
} else if ($payType == 14) {
//微信內部的H5頁面
$data['openid'] = $openid;
if ($openid == '') throw new Exception('openid不得爲空!');
}
$result = $app->order->unify($data, $this->isContract);
//第二次驗籤
if ($result['return_code'] === 'SUCCESS') {
if ($result['result_code'] === 'SUCCESS') {
if ($payType == 10) {
$result = $app->jssdk->appConfig($result['prepay_id']); //第二次簽名
} else if ($payType == 11) {
//微信小程序
$result = $app->jssdk->bridgeConfig($result["prepay_id"], false);
unset($result['appId']);
$result['timeStamp'] = strval($result['timeStamp']);
} else if ($payType == 13) {
//微信二維碼支付
$result['code_url'] = (new QrcodeService())->create($result['code_url'], $oderNumber);
return $result;
} else if ($payType == 14) {
//微信內部H5
$result = $app->jssdk->sdkConfig($result["prepay_id"]);
return $result;
}
return $result;
} else {
throw new Exception($result['err_code_des']);
}
} else {
throw new Exception($result['return_msg']);
}
}
}
特別注意:
1、如果是 JSAPI類型支付時,unify
驗籤的這個方法必須要傳入用戶的openId
。
2、openId
可以在微信小程序授權的時候存入數據庫,然後取出來就可以傳入了。
3、微信內部H5頁面 支付用的 JSSDK 二次驗籤調用sdkConfig
方法。
4、微信小程序 支付用的 JSSDK 二次驗籤調用bridgeConfig
方法。
5、APP支付用的 JSSDK 二次驗籤調用appConfig
方法。
6、如果是生成 微信二維碼支付 時,unify
驗籤的這個方法必須要傳入商戶內部自定義的商品IDproduct_id
。
7、支付時候 需要確保描述body
、商戶訂單號out_trate_no
和 金額amount
和上一次提交微信的一致,否則會報錯201--商戶訂單號重複
。
8、微信內部H5頁面 支付所需要的openId
可以參考
1.4、第一步:創建訂單
/**
* @ApiTitle (用戶開通VIP創建不同的訂單)
* @ApiMethod (POST)
*/
public function createOrder()
{
//根據傳入內容或者查庫獲取相關的數據
//$amount 需要內部計算,不能傳入
//$userId 從Token中獲取用戶ID
//$orderNumber 需要生成隨機不重複的字符串,用於商戶內部訂單號
//生成資金流水記錄
Db::startTrans();
try {
// 具體業務數據表插入以及操作
//將數據插入資金錶
(new UserAccountModel)->insert([
'from_id' => $userId, //支付方ID(系統默認爲1)
'to_id' => 1, //收款方ID(系統默認爲1)
'type' => 1, //資金類型:1=VIP開通/升級,2=推薦提成,3=退款
'money' => $amount, //資金金額
'desc' => $subject, //相關描述
'pay_status' => 0, //支付狀態:0=未到賬,1=已到賬
'order_number' => $orderNumber, //訂單流水號
'create_time' => date('Y-m-d H:i:s', time()), //創建時間
]);
Db::commit();
} catch (\Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
$this->success('創建訂單成功!', ['order_number' => $orderNumber,]);
}
-
$amount
表示支付金額,需要根據具體業務計算,不能取 input 傳入的值。 -
pay_status
用於判斷訂單是否支付完成,這一步主要通過訂單查詢/異步調用時候成功的情況下才會變爲1 - 另外訂單表中需要有一個
is_deal
字段,用於判斷 是否處理(0=否,1=是)支付成功的操作 ,因爲 異步調用 有時候會出現問題,我們也需要在 調用支付寶查詢訂單 的時候通過這個字段去判斷是否處理從而去 更新訂單表。 - 其中需要去判斷是否有相同類型 未失效 的訂單,如果存在則直接使用原來的訂單號
1.5、第二步:獲取調起微信支付的參數
/**
* @ApiTitle (用戶支付訂單)
* @ApiMethod (POST)
*/
public function payAmount($orderNumber = '')
{
//支付類型 10-APP微信支付 11-微信小程序支付 12-微信外部H5調起支付 13-生成微信支付二維碼 14-微信內部H5調起支付 20-APP支付寶支付 21-PC支付寶支付 22-H5支付寶支付
$payType = intval(input('pay_type')) ?? 0;
$openid = input('openid') ?? '';
if ($payType == 14 && $openid == '') $this->error('openid必須傳入');
if ($orderNumber == '') $orderNumber = input('order_number') ?? 0; //內部訂單號
if (!$orderNumber) $this->error('訂單號不得爲空!');
//查看記錄表和資金錶 分別獲取金額/充值類型/用戶ID/備註
$userVipLog = (new UserVipLogModel)->where('order_number', $orderNumber)->find();
$user = $this->auth->getUser();
$amount = $userVipLog['amount'];
$userId = $userVipLog['user_id'];
$vipType = $userVipLog['vip_type'];
//判斷用戶是否爲該用戶
if ($userId != $this->auth->uid) $this->error('訂單不匹配!');
//獲取VIP標題
$newVip = (new VipLevelModel)->where('id', $userVipLog['vip_id'])->find();
//判斷是否可以開通會員
$hasCompanyCertify = $user['is_enterprise_certification'];
$hasCertify = $user['is_certification'];
if ($newVip['type'] == 10) {
//查看關聯的VIP
$linkVip = (new VipLevelModel)->where('id', $newVip['extend_vip'])->find();
//非企業無法開通企業會員
if ($linkVip['type'] == 2 && $hasCompanyCertify == 0) $this->error('請先企業認證!');
//非實名用戶無法開通會員
if ($linkVip['type'] == 1 && $hasCertify == 0) $this->error('請先實名認證!');
} else {
//非企業無法開通企業會員
if ($newVip['type'] == 2 && $hasCompanyCertify == 0) $this->error('請先企業認證!');
//非實名用戶無法開通會員
if ($newVip['type'] == 1 && $hasCertify == 0) $this->error('請先實名認證!');
}
//操作備註
if ($payType == 10 || $payType == 11 || $payType == 12 || $payType == 13 || $payType == 14) {
$payTypeText = '微信支付';
$accountType = 1;
} else if ($payType == 20 || $payType == 21 || $payType == 22) {
$payTypeText = '支付寶';
$accountType = 2;
} else {
throw new Exception('支付類型參數錯誤!');
}
if ($vipType == 1) $subject = $payTypeText . '方式開通' . $newVip['title'] . ',充值金額:' . $amount . '元';
if ($vipType == 2) $subject = $payTypeText . '方式續費' . $newVip['title'] . ',充值金額:' . $amount . '元';
if ($vipType == 3) $subject = $payTypeText . '方式升級' . $newVip['title'] . ',充值金額:' . $amount . '元';
//更新資金錶
(new UserAccountModel)->where('order_number', $orderNumber)->update([
'desc' => $subject, //相關描述
'pay_type' => $accountType, //支付方式:1=微信支付,2=支付寶,3=銀行卡,11=其他
]);
if ($accountType == 1) { //10-APP微信支付 11-微信小程序支付 12-微信外部H5調起支付 13-生成微信支付二維碼 14-微信內部H5調起支付
$result = (new WeChatService())->unify($payType, $subject, $orderNumber, $amount, $openid);
$result['order_number'] = $orderNumber;
$result['amount'] = $amount;
$this->success('調起微信支付成功', $result); //支付成功
} elseif ($accountType == 2) {
//20-APP支付寶支付 21-PC支付寶支付 22-H5支付寶支付
//訂單內容
$order = [
'out_trade_no' => $orderNumber,
'total_amount' => $amount,
'subject' => $subject,
];
$ailpayConfig = config('alipay');
if ($payType == 20) $alipay = Pay::alipay($ailpayConfig)->app($order); //app支付
if ($payType == 21) {
//PC支付
$ailpayConfig['return_url'] = 'http://test.sulinks.com/manage/home';
$alipay = Pay::alipay($ailpayConfig)->web($order);
}
if ($payType == 22) {
//手機網站支付
$ailpayConfig['return_url'] = 'http://test1.sulinks.com/#/pages/my/vip/success?order_num=' . $orderNumber . '&money=' . $amount;
$alipay = Pay::alipay($ailpayConfig)->wap($order);
}
$res = $alipay->getContent();
$this->success('調起支付寶支付成功', $res);
}
}
- 後端 只需要在調用微信支付地方調用這段方法即可。
- H5 支付、公衆號支付、掃碼支付、APP支付,全部都是用這個接口下單。
- 前端 微信支付參考文檔 https://pay.weixin.qq.com/wiki/doc/api/index.html。
- APP的
$res
是返回 給前端調起微信 的參數,如下:
{
"code": 1,
"msg": "成功",
"time": "1593600229",
"data": {
"appid": "wx23123124124",
"partnerid": "123123123123",
"prepayid": "wx531351531531515",
"noncestr": "5efc68e65d469",
"timestamp": 123123123,
"package": "Sign=WXPay",
"sign": "05FC29CD1DSDd341251B1C77"
}
}
1.6、查詢訂單
/**
* @ApiTitle (獲取訂單支付狀態)
* @ApiMethod (GET)
*/
public function getPayStatus()
{
$orderNumber = input('order_number'); //內部訂單流水號
$userAccount = (new UserAccountModel)->where('order_number', $orderNumber)->find();
if (!$userAccount) $this->error('不存在該訂單!');
//未處理:0=否,1=是(用於處理業務邏輯)
if ($userAccount->is_deal == 0) {
//微信異步調用異常情況下:
//支付成功根據支付方式:1=微信支付,2=支付寶,3=銀行卡,11=其他
if ($userAccount->pay_type == 1) {
//微信支付查看訂單
$app = (new WeChatService)->connect(10);
$res = $app->order->queryByOutTradeNumber($orderNumber);
if ($res['return_code'] === 'SUCCESS') { // return_code 表示通信狀態,不代表支付狀態
if ($res['result_code'] === 'SUCCESS') { //以下字段在return_code爲SUCCESS的時候有返回
if ($res['trade_state'] === 'SUCCESS') { //支付成功
$tradeNo = $res['transaction_id']; //微信支付訂單號
$totalFee = $res['total_fee']; //充值總金額
$timeEnd = $res['time_end']; //支付完成時間
//如果金額不匹配直接退出
if (($userAccount->money) != $totalFee / 100) goto S;
//支付成功
$this->paySuccess($orderNumber, $tradeNo, $timeEnd);
} else {
goto S;
}
}
}
} elseif ($userAccount->pay_type == 2) {
//支付寶查看訂單
$res = Pay::alipay(config('alipay'))->find($orderNumber);
$state = $res->trade_status; //訂單狀態
$outTradeNo = $res->out_trade_no; //自定義訂單號
$tradeNo = $res->trade_no; //支付寶訂單號
$totalAmount = $res->total_amount; //充值總金額
$appId = $res->app_id; //收款方的APPID
$payTime = $res->gmt_payment; //交易付款時間
if (!in_array($state, ['TRADE_SUCCESS', 'TRADE_FINISHED'])) goto S;
if (!$userAccount) goto S;
if ($userAccount['money'] != $totalAmount) goto S;
if ($appId != config('alipay.app_id')) goto S;
//支付成功
$this->paySuccess($outTradeNo, $tradeNo, $payTime);
}
}
S:
//需要再查一次訂單狀態
$userAccount = (new UserAccountModel)->where('order_number', $orderNumber)->find();
//返回數據前端
$data = [
'order_number' => $orderNumber,
'vip_title' => $vip['title'],
'pay_status' => $userAccount['pay_status'], //支付狀態:0=待支付,1=支付成功
'pay_type' => $userAccount['pay_type'], //支付方式:1=微信支付,2=支付寶,3=銀行卡,11=其他
];
$this->success('獲取訂單信息成功!', $data);
}
- 查詢訂單時候用到
is_deal
用於判斷異步接口是否調用處理,沒有則調用一次
1.7、微信異步操作
/**
* @ApiTitle (微信異步支付會員VIP)
* @ApiMethod (POST)
*/
public function wechatNotify()
{
$app = (new WeChatService())->connect(10);
$response = $app->handlePaidNotify(function ($message, $fail) {
$outTradeNo = $message['out_trade_no']; //自定義訂單號
//查詢是否存在訂單
$res = (new UserAccountModel)->where('order_number', $outTradeNo)->find();
// 如果訂單不存在 或者 訂單已經支付過了 或者 已經處理過
if (!$res || $res->pay_time || $res->pay_status == 1 || $res->is_deal == 1) return true;
if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信狀態,不代表支付狀態
if ($message['result_code'] === 'SUCCESS') { //以下字段在return_code爲SUCCESS的時候有返回
if ($message['trade_state'] === 'SUCCESS') { //以下字段在return_code 和result_code都爲SUCCESS的時候有返回
$tradeNo = $message['transaction_id']; //微信支付訂單號
$totalFee = $message['total_fee']; //充值總金額
$timeEnd = $message['time_end']; //支付完成時間
//如果金額不匹配直接退出
if (($res->money) != $totalFee / 100) return true;
//支付成功
$this->paySuccess($outTradeNo, $tradeNo, $timeEnd);
}
}
} else {
return $fail('通信失敗,請稍後再通知我');
}
return true;
});
$response->send(); // Laravel 裏請使用:return $response;
}
- 其中必須
trade_state
是SUCCESS
的時候纔算支付成功 - 其中
$this->paySuccess($outTradeNo, $tradeNo, $payTime);
用於 支付成功調用的接口 - 該接口主要根據(訂單號查詢到的)訂單業務類型 去調不同的方法,同時需要加入 併發鎖
1.8、支付成功的方法
/**
* @ApiTitle (支付成功的操作,需要鎖)
* @ApiInternal
* @param string $outTradeNo 商戶內部訂單號
* @param string $tradeNo 微信/支付寶訂單號
* @param string $payTime 支付時間
* @return bool|string
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\ModelNotFoundException
* @throws \think\exception\DbException
*/
private function paySuccess($outTradeNo, $tradeNo, $payTime)
{
//加鎖失敗!
if (!RedisService::lock('paySuccess_' . $outTradeNo)) return false;
//查詢訂單
$res = (new UserAccountModel)->where('order_number', $outTradeNo)->find();
if (!$res) return false;
Db::startTrans();
try {
//更新資金錶狀態
(new UserAccountModel)->where('order_number', $outTradeNo)->update([
'trade_no' => $tradeNo, //微信訂單號
'pay_time' => $payTime, //支付時間
'pay_status' => 1, //支付狀態:0=未到賬,1=已到賬
]);
//查看訂單類型 1=VIP開通/升級,2=推薦提成,3=退款
if ($res->type == 1 && $res->is_deal == 0) {
$res = $this->vipSuccess($res['from_id'], $outTradeNo);
if (!$res) throw new Exception('訂單狀態處理異常');
}
Db::commit();
} catch (\Exception $e) {
Db::rollback();
//記錄資金日誌
Log::warning($e->error());
return false;
}
return true;
}
-
$this->vipSuccess($res['from_id'], $outTradeNo);
是充值會員成功的方法
1.9、Redis鎖方法
- composer安裝
predis
,命令行:composer require predis/predis
,點擊查看鏈接。 - 新建一個
RedisServer.php
服務類
<?php
namespace app\common\service;
use app\common\controller\Api;
use Predis\Client;
class RedisService extends Api
{
//Redis併發鎖
const SU_REDIS_LOCK = 'redis::lock::'; //Redis併發鎖(後面跟對應業務的鎖名)
private static $prefix = '';
private static $client;
/**
* 單例模式獲取redis連接實例
* @return Client
*/
public static function connect()
{
if (!self::$client) {
self::$prefix = config('redis_prefix');
$config = [
'scheme' => 'tcp',
'host' => config('redis_host'),
'port' => config('redis_port'),
'timeout' => 60,
'read_write_timeout ' => 60,
];
//沒有配置密碼時,不傳入密碼項參數
if (config('redis_password')) $config['password'] = config('redis_password');
self::$client = new Client($config, ['prefix' => self::$prefix]);
}
return self::$client;
}
/**
* 添加自定義併發鎖
* 原理是redis的單線程操作
* @param string $lockName 鎖名
* @param int $expireTTL 過期時間
* @return bool 是否由當前調用加鎖成功
*/
public static function lock(string $lockName, int $expireTTL = 10)
{
$redis = self::connect();
$countKey = self::SU_REDIS_LOCK . $lockName;
$flag = false; //默認是加鎖失敗
$redisIncr = $redis->incr($countKey); //只有第一個操作的返回是1
if ($redisIncr === 1) {
$redis->expire($countKey, $expireTTL);
$flag = true; //只有第一次操作的纔算加鎖成功
}
return $flag;
}
/**
* 解除自定義併發鎖
* @param string $lockName 鎖名
* @return bool 是否成功
*/
public static function unlock(string $lockName)
{
$countKey = self::SU_REDIS_LOCK . $lockName;
return (bool)self::connect()->del([$countKey]);
}
}
微信調用的時候需要配置白名單,這樣纔可以調用微信內部的方法,例如查詢訂單的接口。
大功告成,其中調試也會遇到問題,我們可以在日誌中進行查看,日誌在配置中可以進行修改。
歡迎來指導和學習,如果有什麼問題可以在留言區留言並一起探討。
另外還有詳細的 TP5 實現支付寶APP/PC端統一下單支付(詳細步驟)