我們?cè)陂_發(fā)app常常需要接入支付功能,但是有時(shí)候出于包體積或?qū)徍说囊蛩?,并不想接入支付相關(guān)的sdk,這個(gè)時(shí)候,就可以考慮使用h5支付完成購(gòu)買服務(wù),只需要訪問后端返回的h5支付鏈接即可,便捷而簡(jiǎn)單。
話不多說,進(jìn)入正題!
1、開通h5支付
前往微信商戶平臺(tái) - 產(chǎn)品中心 - 我的產(chǎn)品 - 支付產(chǎn)品 - h5支付,申請(qǐng)開通h5支付,要審核1-7天,沒問題的話一般兩三天就能完成審核。
2、前端部分
2.1、請(qǐng)求h5支付接口
注意兩個(gè)點(diǎn):
1、先下單再進(jìn)行支付,下單邏輯不同的項(xiàng)目業(yè)務(wù)邏輯也不同,故這里不多做闡述;
2、微信h5支付返回的mweb_url,前端直接訪問,會(huì)報(bào)錯(cuò):商家參數(shù)格式有誤,請(qǐng)聯(lián)系商家解決。解決方案是需要設(shè)置正確的Refere,具體看下方代碼
// 發(fā)起支付請(qǐng)求, order_no為訂單號(hào)
requestPay(order_no) {
let that = this
// #ifdef APP-PLUS
// 我們的項(xiàng)目封裝了統(tǒng)一管理API的管理類,請(qǐng)求接口封裝每個(gè)項(xiàng)目不同,換成自己的方法即可
this.$api.apiH5Pay({
'order_no': order_no
}).then(res => {
if (res.data.code == 200) {
let data = res.data.data
let mweb_url = data.url
let msg = data.msg
let confirmText = data.confirm
uni.showModal({
title: '提示',
content: msg,
confirmText: confirmText,
showCancel: false,
success: function (res) {
if (res.confirm) {
console.log('用戶點(diǎn)擊已完成支付');
// 此處自行編寫相應(yīng)的業(yè)務(wù)邏輯代碼,如訂單狀態(tài)查詢或刷新用戶信息等
}
}
});
// app創(chuàng)建webview訪問服務(wù)端返回的h5支付鏈接
const platform = uni.getSystemInfoSync().platform
// 申請(qǐng)h5支付的域名,換成自己的
const domain = 'www.xxx.com'
// 創(chuàng)建一個(gè)webview
const webview = plus.webview.create('', 'https://' + domain);
// 通過webview打開鏈接,后面加referer表示該鏈接是從哪里打開的,請(qǐng)?zhí)顚懮暾?qǐng)h5支付的域名,比如:http://www.baidu.com,需要已備案
switch (platform) {
case 'android':
webview.loadURL(mweb_url, {'Referer': 'https://' + domain});
break;
case 'ios':
webview.loadURL(mweb_url, {'Referer': domain + '://'});
break;
default:
break;
}
}
}).catch(err => {
//
})
// #endif
},
2.2、 可能遇到的問題
可能會(huì)遇到iOS跳轉(zhuǎn)微信完成支付后無(wú)法自動(dòng)返回app,是因?yàn)閁rlSchemes沒有配置好。
解決方案:文章來源:http://www.zghlxwxcb.cn/news/detail-739922.html
點(diǎn)擊項(xiàng)目的manifest.json文件, App常用其它設(shè)置-UrlSchemes,將申請(qǐng)h5支付的域名輸入進(jìn)去作為返回app的scheme文章來源地址http://www.zghlxwxcb.cn/news/detail-739922.html
3、后端部分
3.1 支付接口
// app微信h5支付接口
public function h5Pay() {
// 訂單號(hào)
$order_no = request()->param("order_no");
// 我設(shè)計(jì)接口時(shí),做了統(tǒng)一控制,需要登錄的接口會(huì)自動(dòng)識(shí)別token是否有效,有效則會(huì)提前token中的userId。各位可以用各自的方案獲取下單的用戶信息
$userModel = User::get($this->userId);
$orderModel = Order::get(['order_no' => $order_no]);
if (empty($userModel) || empty($orderModel)) {
return RApi::error("沒有找到訂單");
}
// 值得一提:如果校驗(yàn)工具通過,卻提示簽名錯(cuò)誤,前往商戶平臺(tái)重新設(shè)置一下商戶支付密鑰就可以了,即使設(shè)置一模一樣的商戶支付密鑰也可以,微信的bug
$timeStamp = time();
$nonceStr = Self::createNoncestr();
$signType = 'MD5';
$outTradeNo = $order_no;
$body = $orderModel->body;//描述
$total_fee = $orderModel->total_fee * 100;
$openid = $userModel->app_openid;
//統(tǒng)一下單接口
$result = $this->unifiedorder($openid, $outTradeNo, $nonceStr, $total_fee, $body, 'MWEB');
// 前端主要用到mweb_url進(jìn)行支付, app訪問5支付鏈接時(shí),會(huì)自動(dòng)跳轉(zhuǎn)微信app進(jìn)行支付操作,這個(gè)時(shí)候比較友好的做法是,在我們的app購(gòu)買商品頁(yè)面,彈出一個(gè)提示,這里的示例,msg是提示的內(nèi)容,confirm是提示框按鈕文本,后端控制文案,會(huì)更靈活,當(dāng)你遇到變臉很快的產(chǎn)品和老板時(shí),他們突然要改個(gè)提示,總不能重新發(fā)一個(gè)提審包吧
return RApi::success([
'url' => $result['mweb_url'],
'msg' => '請(qǐng)前往微信完成付款',
'confirm' => '我已完成支付'
]);
}
3.2 微信訂單支付狀態(tài)查詢
public function orderquery() {
$order_no = request()->param("order_no");
$userModel = User::get($this->userId);
$orderModel = Order::get(['order_no' => $order_no]);
if (empty($orderModel)) {
return RApi::error("沒有找到訂單:" . $order_no);
}
$appid = ''; // 微信開放平臺(tái)創(chuàng)建的移動(dòng)應(yīng)用appid
$mch_id = ''; // 商戶號(hào)
$transaction_id = $orderModel->transaction_id;//微信訂單號(hào)
if (empty($transaction_id)) {
return RApi::error('微信訂單號(hào)為空', 201, []);
}
// 當(dāng)前時(shí)間
$time = time();
// 生成隨機(jī)字符串
$nonce_str = md5($time . mt_rand(00000,99999));
//API參數(shù)
$params = [
'appid' => $appid, //應(yīng)用ID
'mch_id' => $mch_id, //商戶號(hào)
'transaction_id' => $transaction_id, //商戶訂單號(hào)
'nonce_str' => $nonce_str, // 隨機(jī)字符串
];
//請(qǐng)求API
$url = 'https://api.mch.weixin.qq.com/pay/orderquery';
//生成簽名
$params['sign'] = $this->getSign($params);
$xmlData = $this->arrayToXml($params);
$result = $this->xmlToArray($this->postXmlCurl($xmlData, $url, 60));
// 請(qǐng)求失敗
if ($result['return_code'] === 'FAIL') {
return RApi::error('查詢失敗', 201, $result);
}
// 微信返回的訂單狀態(tài)是已完成支付
if ($result['return_code'] === 'SUCCESS'||$result['result_code'] === 'SUCCESS'||$result['trade_state'] === 'SUCCESS') {
// 查詢到訂單狀態(tài)的時(shí)候,如果已經(jīng)完成付款,數(shù)據(jù)庫(kù)表訂單狀態(tài)卻沒改變,則進(jìn)行商品發(fā)放并標(biāo)記已支付
if($orderModel->state!=1) {
// 假如數(shù)據(jù)庫(kù)狀態(tài)為未支付,此處添加業(yè)務(wù)代碼完成支付標(biāo)記操作
}
return RApi::success(1, '支付已完成');
}
// 查詢到了,但是訂單狀態(tài)為未完成支付
return RApi::success(0, '等待支付');
}
3.3 其余部分相關(guān)代碼塊
// 統(tǒng)一下單接口
private function unifiedorder($openid, $out_trade_no, $noncestr, $total_fee, $body = '' , $trade_type = 'JSAPI') {
$appid = ''; // 微信開放平臺(tái)創(chuàng)建的移動(dòng)應(yīng)用appid
$mch_id = ''; // 商戶號(hào)
$notify_url = 'https://www.xxx.com/pay/wxNotify'; // 改成自己的回調(diào)地址
$url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
$parameters = array(
'appid' => $appid, // 應(yīng)用id
'mch_id' => $mch_id, // 商戶號(hào)
'body' => $body, // 商品描述
'nonce_str' => $noncestr, // 隨機(jī)字符串
'notify_url' => $notify_url, // 通知地址 確保外網(wǎng)能正常訪問
'openid' => $openid, // 用戶微信openid
'out_trade_no'=> $out_trade_no, // 商戶訂單號(hào)
'spbill_create_ip' => $this->get_client_ip(), // 終端IP
'total_fee' => $total_fee, // 單位 分
'trade_type' => $trade_type // 交易類型
);
//統(tǒng)一下單簽名
$parameters['sign'] = $this->getSign($parameters);
$xmlData = $this->arrayToXml($parameters);
$result = $this->xmlToArray($this->postXmlCurl($xmlData, $url, 60));
//$return = $this->postXmlCurl($xmlData, $url, 60);
if (!isset($result['prepay_id']) || empty($result['prepay_id'])) {
// 統(tǒng)一下單失敗
return false
}
return $result;
}
// 生成簽名
private function getSign($Obj) {
foreach ($Obj as $k => $v) {
$Parameters[$k] = $v;
}
//簽名步驟一:按字典序排序參數(shù)
ksort($Parameters);
$String = $this->formatBizQueryParaMap($Parameters, false);
//簽名步驟二:在string后加入KEY
$String = $String . "&key=" . $this->mch_key;
//簽名步驟三:MD5加密
$String = md5($String);
//簽名步驟四:所有字符轉(zhuǎn)為大寫
$result_ = strtoupper($String);
return $result_;
}
// 格式化參數(shù)
private function formatBizQueryParaMap($paraMap, $urlencode)
{
$buff = "";
ksort($paraMap);
foreach ($paraMap as $k => $v) {
if ($urlencode) {
$v = urlencode($v);
}
$buff .= $k . "=" . $v . "&";
}
$reqPar = '';
if (strlen($buff) > 0) {
$reqPar = substr($buff, 0, strlen($buff) - 1);
}
return $reqPar;
}
// 數(shù)組轉(zhuǎn)xml
private function arrayToXml($arr) {
$xml = "<xml>";
foreach ($arr as $key => $val) {
if (is_numeric($val)) {
$xml .= "<" . $key . ">" . $val . "</" . $key . ">";
} else {
$xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
}
}
$xml .= "</xml>";
return $xml;
}
// xml轉(zhuǎn)數(shù)組
private function xmlToArray($xml) {
//禁止引用外部 xml 實(shí)體
libxml_disable_entity_loader(true);
$xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
$val = json_decode(json_encode($xmlstring), true);
return $val;
}
// xml提交post請(qǐng)求
private static function postXmlCurl($xml, $url, $second = 30)
{
$ch = curl_init();
//設(shè)置超時(shí)
curl_setopt($ch, CURLOPT_TIMEOUT, $second);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); //嚴(yán)格校驗(yàn)
//設(shè)置 header
curl_setopt($ch, CURLOPT_HEADER, FALSE);
//要求結(jié)果為字符串且輸出到屏幕上
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
//post 提交方式
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
curl_setopt($ch, CURLOPT_TIMEOUT, 40);
set_time_limit(0);
//運(yùn)行 curl
$data = curl_exec($ch);
//返回結(jié)果
if ($data) {
curl_close($ch);
return $data;
} else {
$error = curl_errno($ch);
curl_close($ch);
throw new WxPayException("curl 出錯(cuò),錯(cuò)誤碼:$error");
}
}
// 生成隨機(jī)字符串
public static function createNoncestr($length = 32) {
$chars = "abcdefghijklmnopqrstuvwxyz0123456789";
$str = "";
for ($i = 0; $i < $length; $i++) {
$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
}
return $str;
}
到了這里,關(guān)于uniapp 開發(fā)App使用微信H5支付解決方案(包含前后端,后端用的thinkphp)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!