想要在微信小程序中嵌入网页,需要以下几个步骤:
一、小程序设置
需要在微信小程序公众平台中添加业务域名。即把要嵌入小程序的网页的域名添加到业务域名中
登录微信小程序->开发->开发设置->业务域名,这个域名可以是https的也可以是http的,推荐使用https的。
二、修改小程序
1.在小程序新建个页面,准备嵌入网页,例如“webpage",里面的内容跟正常的小程序页面相同,js,wxml,json都有,在wxml添加代码即可:
<web-view src="http://www.abc.com/mobile"></web-view>
2.再新建个页面,准备做微信支付相关用的,例如”payforweb“,里面只写js以及json。
3.直接上代码:
pay.js:
let reqeustApi=getApp().globalData.requestURI; //指定默认的请求url
Page({
data: {
wxCode:'',//取openid用的code
ordercode:'',//接收商户的ordercode
payParam:{},//接收微信返回的统一下单的参数
},
onLoad: function (options) {
this.setData({
ordercode: options.ordercode,//网页端传的商户订单号
});
this.getCode();
},
// 取临时code
getCode:function(){
let that=this;
//1.先获取本地缓存中是否有openid
let OpenidInLocal=wx.getStorageSync('openid');
if(OpenidInLocal==''||OpenidInLocal==undefined){
//2.如果没有取openid,
wx.login({
success: res => {
// 发送 res.code 到后台换取 openId, sessionKey, unionId
this.setData({
wxCode:res.code
});
console.log('支付code:', this.data.wxCode);
this.getOpenid(function(){
//3.取到openid后调用取订单接口,
that.getPayinfo()
});
}
})
}else{
//3.取到openid后调用取订单接口,
that.getPayinfo()
}
},
// 取支付参数
getPayinfo:function(){
var self=this;
wx.request({
url:reqeustApi+'startalipay.html' ,//后台接口地址
data: {
open_id:wx.getStorageSync("openid"),
ordercode:ordercode
},
header: {
"Content-Type": "application/x-www-form-urlencoded"
},
method: 'POST',
success: function (res) {
self.setData({
payParam: res.data.data
});
// 调起支付
wx.requestPayment({
'timeStamp': self.data.payParam.timeStamp,//为字符串,否则报错
'nonceStr': self.data.payParam.nonceStr,
'package': self.data.payParam.package,
'signType': 'MD5',
'paySign': self.data.payParam.paySign,
'success': function (res) {
wx.navigateTo({
url: '/pages/index/index'
})
},
'fail': function (res) {
console.log('=======支付失败==========')
}
})
}
})
} ,
getOpenid(callbackFunc){
let self=this;
wx.request({
url: reqeustApi+'getwxopenid.php',//后台接口地址
data: {
'code': self.data.wxCode,
},
method:'GET',
success:function(res){
let tmpdata=res.data;
console.log(tmpdata);
if(tmpdata.status==200){
let data=tmpdata.data;
let openid=data.openid;
wx.setStorageSync('openid', openid)
callbackFunc();
}else{
wx.showToast({
title: '加载错误',
icon:'none'
})
}
}
});
}
})