在微信内置浏览器中打开链接,调起微信支付
第一种需要openid的情况
<button class="but" @click="gobuy">微信支付</button>
import { setCookie, getCookie, isWeixin } from '../../utils/common' // 引用方法
async jsapi() {
var params = new URLSearchParams()
params.append('payment', 1)
params.append('userId', this.userId)
const { data: res } = await this.$http.post(
'后台jsapi接口地址',
params
)
if (res.status == 1001) {
this.handleGetDataSucc(res)
}
},
handleGetDataSucc(res) {// 微信内置浏览器调起微信支付
var vm = this
var data = res.data
if (data) {
// 下面是解决WeixinJSBridge is not defined 报错的方法
if (typeof WeixinJSBridge === 'undefined') {
// 微信浏览器内置对象。参考微信官方文档
if (document.addEventListener) {
document.addEventListener(
'WeixinJSBridgeReady',
vm.onBridgeReady(data),
false
)
} else if (document.attachEvent) {
document.attachEvent(
'WeixinJSBridgeReady',
vm.onBridgeReady(data)
)
document.attachEvent(
'onWeixinJSBridgeReady',
vm.onBridgeReady(data)
)
}
} else {
console.log('准备调用微信支付')
vm.onBridgeReady(data)
}
}
},
onBridgeReady(data) {
var vm = this
window.WeixinJSBridge.invoke(
'getBrandWCPayRequest',
{
// 下面参数内容都是后台返回的
appId: data.appId, // 公众号名称,由商户传入
timeStamp: data.timeStamp, // 时间戳
nonceStr: data.nonceStr, // 随机串
package: data.package, // 预支付id
signType: data.signType, // 微信签名方式
paySign: data.paySign, // 微信签名
},
function(res) {
// 使用以上方式判断前端返回,微信团队郑重提示:res.err_msg将在用户支付成功后返回ok,但并不保证它绝对可靠。
if (res.err_msg === 'get_brand_wcpay_request:ok') {
vm.$toast({
message: '支付成功',
})
vm.$router.replace({
name: 'purchaseSucceeded',
})
} else {
vm.$toast({
message: '支付失败',
})
}
}
)
},
async gobuy() {
if (isWeixin()) {// 判断知否在微信内置浏览器内,在的话则通过看有没有userId
if (getCookie('wx_userId')) {
this.jsapi() // 有userId的情况直接调用jsapi接口
} else {// 没有userId则要授权登录来获取
var code = this.$route.query.code //History 模式从url获取code
if (code) {
this.getRedirectUri(code) // 获取userId
} else {
//如果不存在code且url中不包含code,说明未授权,去微信授权
const appid = 'wx8443dafb90657072' // 公众号的唯一标识
//授权后重定向的回调链接地址, 请使用 urlEncode 对链接进行处理
const redirect_uri = encodeURIComponent(
'微信回调地址页面链接'
)
console.log(redirect_uri + '重定向')
//应用授权作用域:snsapi_userinfo(弹出授权页面,可通过openId拿到昵称、性别、所在地。)
const scope = 'snsapi_userinfo'
const urls = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirect_uri}&response_type=code&scope=${scope}&state=STATE#wechat_redirect `
window.location.href = urls
}
}
} else {// 不在微信内置浏览器,在其他浏览器或嵌入在app里,则进入其他支付页面
this.$router.push({
name: 'buy',
query: { userId: this.userId },
})
}
},
async getRedirectUri(code) {
console.log(code)
const { data: res } = await this.$http.get(
'获取userId后台接口',
{
params: {
code: code,
},
}
)
if (res.status == 1001) {
setCookie('wx_userId', JSON.stringify(res.data.id))
this.userId = getCookie('wx_userId')
}
},
不需要oepnId就不用授权登录,直接跳过授权登录代码
<button class="but" @click="gobuy">微信支付</button>
import { isWeixin } from '../../utils/common' // 引用方法
async jsapi() {
var params = new URLSearchParams()
params.append('payment', 1)
params.append('userId', this.userId)
const { data: res } = await this.$http.post(
'后台jsapi接口地址',
params
)
if (res.status == 1001) {
this.handleGetDataSucc(res)
}
},
handleGetDataSucc(res) {// 微信内置浏览器调起微信支付
var vm = this
var data = res.data
if (data) {
// 下面是解决WeixinJSBridge is not defined 报错的方法
if (typeof WeixinJSBridge === 'undefined') {
// 微信浏览器内置对象。参考微信官方文档
if (document.addEventListener) {
document.addEventListener(
'WeixinJSBridgeReady',
vm.onBridgeReady(data),
false
)
} else if (document.attachEvent) {
document.attachEvent(
'WeixinJSBridgeReady',
vm.onBridgeReady(data)
)
document.attachEvent(
'onWeixinJSBridgeReady',
vm.onBridgeReady(data)
)
}
} else {
console.log('准备调用微信支付')
vm.onBridgeReady(data)
}
}
},
onBridgeReady(data) {
var vm = this
window.WeixinJSBridge.invoke(
'getBrandWCPayRequest',
{
// 下面参数内容都是后台返回的
appId: data.appId, // 公众号名称,由商户传入
timeStamp: data.timeStamp, // 时间戳
nonceStr: data.nonceStr, // 随机串
package: data.package, // 预支付id
signType: data.signType, // 微信签名方式
paySign: data.paySign, // 微信签名
},
function(res) {
// 使用以上方式判断前端返回,微信团队郑重提示:res.err_msg将在用户支付成功后返回ok,但并不保证它绝对可靠。
if (res.err_msg === 'get_brand_wcpay_request:ok') {
vm.$toast({
message: '支付成功',
})
vm.$router.replace({
name: 'purchaseSucceeded',
})
} else {
vm.$toast({
message: '支付失败',
})
}
}
)
},
async gobuy() {
if (isWeixin()) {// 判断知否在微信内置浏览器内
this.jsapi()
} else {// 不在微信内置浏览器,在其他浏览器或嵌入在app里,则进入其他支付页面
this.$router.push({
name: 'buy',
query: { userId: this.userId },
})
}
}
common.js文件
// 时间戳转换
function timestampToTime(timestamp, type) {
const dt = new Date(parseInt(timestamp))
const y = dt.getFullYear()
const m = (dt.getMonth() + 1 + '').padStart(2, '0')
const d = (dt.getDate() + '').padStart(2, '0')
const hh = (dt.getHours() + '').padStart(2, '0')
const mm = (dt.getMinutes() + '').padStart(2, '0')
const ss = (dt.getSeconds() + '').padStart(2, '0')
if (type == 1) {
return `${y}/${m}/${d} ${hh}:${mm}:${ss}`
} else if (type == 2) {
return `${hh}:${mm}:${ss} `
} else {
return `${y}/${m}/${d} `
}
}
//设置cookie
function setCookie(c_name, value, expiredays) {
var exdate = new Date()
exdate.setDate(exdate.getDate() + expiredays)
document.cookie =
c_name +
'=' +
escape(value) +
(expiredays == null ? '' : ';expires=' + exdate.toGMTString())
}
//取回cookie
function getCookie(c_name) {
if (document.cookie.length > 0) {
var c_start = document.cookie.indexOf(c_name + '=')
if (c_start != -1) {
c_start = c_start + c_name.length + 1
var c_end = document.cookie.indexOf(';', c_start)
if (c_end == -1) c_end = document.cookie.length
return unescape(document.cookie.substring(c_start, c_end))
}
}
return ''
}
function usageScenario() {
var u = navigator.userAgent
return {
trident: u.indexOf('Trident') > -1, //IE内核
presto: u.indexOf('Presto') > -1, //opera内核
webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
android: u.indexOf('Android') > -1 || u.indexOf('Adr') > -1, //android终端
iPhone: u.indexOf('iPhone') > -1, //是否为iPhone或者QQHD浏览器
iPad: u.indexOf('iPad') > -1, //是否iPad
webApp: u.indexOf('Safari') == -1, //是否web应该程序,没有头部与底部
weixin: u.indexOf('MicroMessenger') > -1, //是否微信
qq: u.match(/\sQQ/i) == ' qq', //是否QQ
}
}
// 判断是否在微信
function isWeixin() {
return navigator.userAgent.toLowerCase().indexOf('micromessenger') !== -1
}
function phone() {
var u = navigator.userAgent
if (u.indexOf('Android') > -1 || u.indexOf('Linux') > -1) {
return 'android'
}
//ios方法
return 'ios'
}
// 微信授权登录获取code
function getUrlParam(name) {
var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
var r = window.location.search.substr(1).match(reg)
if (r != null) return unescape(r[2])
return null
}
function goToWechat(wechatID) {
var u = navigator.userAgent
if (u.indexOf('Android') > -1 || u.indexOf('Linux') > -1) {
window.android.wechat(wechatID)
} else {
//ios方法
window.webkit.messageHandlers.wechat.postMessage(wechatID)
}
}
//分享功能
function shareContent(data) {
var u = navigator.userAgent
if (u.indexOf('Android') > -1 || u.indexOf('Linux') > -1) {
window.android.share(
data.title,
data.url,
data.text,
data.imgUrl,
data.url,
1
)
} else {
//ios方法
window.webkit.messageHandlers.share.postMessage(data)
}
}
export {
timestampToTime,
setCookie,
getCookie,
isWeixin,
usageScenario,
phone,
getUrlParam,
goToWechat,
shareContent,
}