h5内嵌⼩程序,调⽤⽀付功能在⼩程序中不能使⽤之前在浏览器中配置的⽀付功能,只能调⽤⼩程序专属的api进⾏⽀付。
因为需要在现在实现的基础上,再添加在⼩程序中调⽤⽀付功能,所以我的思路是这样的
1.
2.
3.
实现:
⾸先需要引⼊wx的解析⽂件
<script type="text/javascript" src="/index/js/jweixin-1.3.2.js"></script>
判断是不是在⼩程序中
var ua = LowerCase();
if(ua.match(/MicroMessenger/i)=="micromessenger") {
//ios的ua中⽆miniProgram,但都有MicroMessenger(表⽰是浏览器)
Env((res)=>{
if (res.miniprogram) {
console.log('在⼩程序内')
wx.miniProgram.navigateTo({
url: "/pages/prowxpay/prowxpay?info="+queryParam      //⼩程序的⽀付地址,queryParam是需要传递的商品id等数据
});
return false;
}else{
console.log('在内,但是不在⼩程序内')
return false;
}
})
}else{
console.log('在外')
return false;
}
在⼩程序⽀付的js⽂件中进⾏调⽤
var app = getApp();
Page({
data: {
bt: 'bt'
},
onLoad: function (options) {
var that = this;
if (ds_id) {
that.setLoading(options);
} else { wx.navigateBack();}
},
setLoading: function(a) {
var that = this
wx.login({
success: function(res) {
/
/ 成功会返回:
// {errMsg: "login:ok", code: "获取⽤户OpenID的ticket"}
}
})
},
getOpenId: function (jsCode,a) {
var that = this
url: baseURL + '/index/Xcxpay/login',  //baseURL引⼊的https地址
data: {
js_code: jsCode // wx.login()时得到的ticket
},
success: function (res) {
},
fail: function (res) {
console.log(res)
that.setData({
bt: ''
}),
wx.showModal({ title: "⽹络超时", content: "刷新重试", showCancel: !1 });
}
})
},
getPrePayId: function (openId, a) {var that = this
url: baseURL + '/index/Xcxpay/index?openid='+openId+'&goods_id=' + a.goods_id  ,
success: function (res) {
console.log(res.data);
if(res.data.status == 1) {
that.pay(res.data.data,a);
} else {
var msg = String(res.data.msg);
wx.showModal({
title: "提醒",
content: msg,
showCancel: !1,
success(res) {
firm) {
wx.navigateBack({
delta: 1
})
}
}
})
return false;
}
},
fail:function (res) {
console.log(res);
that.setData({
bt: ''
})
}
})
},
// data是服务端返回的JSON
// 加上success、fail回调后,正好符合wx.requestPayment()参数的格式
pay: function (res, a) {
console.log(res)
'timeStamp': res.timeStamp,
'nonceStr': Str,
'package': res.package,
'signType': 'MD5',
'paySign': res.paySign,
success: function (res) {
console.log(res)
url: baseURL + '/index/Xcxpay/callback?goods_id=' + a.goods_id + '&msg=' + Msg,
success: function(res){
console.log(res.data.status)
if(res.data.status == 1) {
wx.showToast({
title: '⽀付成功',
icon: 'success',
duration: 2000
})
setTimeout(()=>{
url: '/pages/order/order',
})
},2001)
}
},
fail: function(){}
})
},
fail: function (res) {
console.log('付款失败');
console.log(res)
wx.showModal({
title: '提醒',
content: '付款失败',
showCancel: false,
success:function(res){
firm) {
wx.navigateBack({
delta: 1
})
}
}
})
return
},
})
},
wdxreload: function(){
var pages = getCurrentPages();
var currentPage = pages[pages.length - 1]; //获取当前页⾯的对象
var url = ute; //当前页⾯url
var options = currentPage.options; //如果要获取url中所带的参数可以查看options
wx.navigateTo({ url: "/pages/wxpay/wxpay?goods_id=" + ds_id});
}
})
我对接的后台是php,下⾯附上代码
public function login() {
$appid='⼩程序的appId';
$secret='⼩程序的密钥';
$params = array(
'appid' => $appid,
'secret' => $secret,
'js_code' => $_GET['js_code'], // ⼩程序传来的ticket
'grant_type' => 'authorization_code',
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'api.weixin.qq/sns/jscode2session');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$output = curl_exec($ch);
if (false === $output) {
echo 'CURL Error:' . curl_error($ch);
}
echo $output;
}
//blog.csdn/u010505805/article/details/76861853
public function index(){
$order_id = isset($_GET['goods_id']) ? intval($_GET['goods_id']) : '';
$openid = $_GET['openid'];
小程序 字符串转数组$this->pub_index($openid,$order_id);
}
public function pub_index($openid,$order_id){
$appid='⼩程序appId';
$secret='⼩程序的密钥';
$url="h.weixin.qq/pay/unifiedorder";
$mch_id = '';//受理商ID(即⽀付商户号)
$mch_key = '';//商户⽀付密钥Key
$order = $orderinfo=Db::name('order_info')->where('order_code="'.$order_id.'"')->find();
$total_fee=$order['order_amount'] * 100;
$params = array(
'appid' => $appid,  // ⼩程序appid
'mch_id' => $mch_id,
'nonce_str' => (string)mt_rand(10000, 99999),  // 随机串,32字符以内
'body' => ' ',  // 商品名
'out_trade_no' => $order['order_code'],
//'out_trade_no' => substr( $order['order_code'].'A'.($order['order_amount']*100).'B' ,0,32),  //订单号32字符以内。串接后取前32位。多次⽀付时如果重复的话,会返回“重复下单”          'spbill_create_ip' => $_SERVER['REMOTE_ADDR'],
'notify_url' => '',  // ⽀付成功后的回调地址,由腾讯服务端回调
'trade_type' => 'JSAPI',
'openid' => $openid,  // ⼩程序传来的OpenID
'total_fee' =>(string)$total_fee,  // 订单费⽤,单位:分
);
//var_dump($params);die;
// 按照要求计算sign
ksort($params);
$sequence = '';
foreach ($params as $key => $value) {
$sequence .= "$key=$value&";
}
$sequence = $sequence . "key=".$mch_key;
//echo $sequence;die;
$params['sign'] = strtoupper(md5($sequence));
$xml =$this->arrayToXml($params);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$output = curl_exec($ch);
if (false === $output) {
echo 'CURL Error:' . curl_error($ch);
}
// 下单成功的话,返回个XML,⾥⾯包含prepayID,提取出来
$match=$this->xml_to_array($output);
//var_dump($match);die;
if($match['result_code']=='FAIL'){
$result['status']=3;
$result['msg']=$match['err_code_des'];
die(json_encode($result));
}
// 这⾥不是给⼩程序返回个prepayID,⽽是返回⼀个包含其他字段的JSON
// 这个JSON⼩程序⾃⼰也可以⽣成,放在服务端⽣成是出于两个考虑:
// 1. ⼩程序的appid不⽤写在⼩程序的代码⾥,appid、secret信息全部由服务器管理,⽐较安全
// 2. 计算paySign需要⽤到md5,⼩程序端使⽤的是JavaScript,没有内置的md5函数,放在服务端计算md5⽐较⽅便
@$prepayId = $match['prepay_id'];
if(!$match['prepay_id']){
$result['status']=4;
$result['msg']='prepay_id为空,请查看具体原因';
die(json_encode($result));
}
$response= array(
'appId' => $appid,        //⼩程序appid
'nonceStr' => (string) mt_rand(10000, 99999),          // 随机串,32个字符以内
'package' => (string)'prepay_id=' . $prepayId,
'signType' => 'MD5',
'timeStamp' => (string) time(),          // 时间戳,注意得是字符串形式的
);
$sequence = '';
foreach ($response as $key => $value) {
$sequence .= "$key=$value&";
}
$response['paySign'] = strtoupper(md5("{$sequence}key=".$mch_key));
//$info['aaa']=(string)$prepayId;
$result['status']=1;
$result['msg']='成功';
$result['data']=$response;
die(json_encode($result));
}
function callback(){
$order_id = $_GET['goods_id'];
$result = Db::name('')->where("order_code='".$order_id."'")->update(array('pay_status'=>1,'order_status'=>1,'pay_time'=>time(),'pay_id'=>1,'pay_name'=>'','pay_platform'=>'⼩程序⽀付'));
$orderinfo = Db::name("")->field('order_amount,add_time')->where("order_code='".$order_id."'")->find();
Db::name('order_log')->insert(array('order_code'=>$order_id,'type'=>'⼩程序⽀付','addtime'=>date('Y-m-d H:i:s',$orderinfo['add_time']),'paytime'=>date('Y-m-d H:i:s',time()),'order_amount'=>$orderinfo['order_amount'],'remark'=>'SUCCESS'        $data['status']=1;
die(json_encode($data));
}
function notify($data)
{
$inputdata = file_get_contents("php://input");
if (! empty($inputdata)) {
$payment = model('Payment')->get_payment("wxpay");
$postdata = json_decode(json_encode(simplexml_load_string($inputdata, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
/* 检查插件⽂件是否存在,如果存在则验证⽀付是否成功,否则则返回失败信息 */
// 端签名
$wxsign = $postdata['sign'];
unset($postdata['sign']);
// 附加参数
$attach = $postdata['attach'];
foreach ($postdata as $k => $v) {
$Parameters[$k] = $v;
}
// 签名步骤⼀:按字典序排序参数
ksort($Parameters);
$buff = "";
foreach ($Parameters as $k => $v) {
$buff .= $k . "=" . $v . "&";
}
$String;
if (strlen($buff) > 0) {
$String = substr($buff, 0, strlen($buff) - 1);
}
// 签名步骤⼆:在string后加⼊KEY
$String = $String . "&key=" . $payment['wxpay_key'];
// 签名步骤三:MD5加密
$String = md5($String);
// 签名步骤四:所有字符转为⼤写
$sign = strtoupper($String);
// 验证成功
if ($wxsign == $sign) {
// 交易成功
$returndata['return_code'] = 'SUCCESS';
} else {
$returndata['return_code'] = 'FAIL';
}
} else {
$returndata['return_code'] = 'FAIL';
$returndata['return_msg'] = '⽆数据返回';
}
// 数组转化为xml
$xml =$this->arrayToXml($returndata);
echo $xml;
exit();
}
function arrayToXml($arr)
{
$xml = "<xml>";
foreach ($arr as $key=>$val)
{
if (is_array($val)){
$xml.="<".$key.">".arrayToXml($val)."</".$key.">";
}else{
$xml.="<".$key.">".$val."</".$key.">";
}
}
$xml.="</xml>";
return $xml;
}
function xml_to_array($xml){
if(!$xml){
return false;
}
/
/将XML转为array
//禁⽌引⽤外部xml实体
libxml_disable_entity_loader(true);
$data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
return $data;
}
欢迎各位同仁交流~
加油哦~⼩王

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。