开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第1天
需要判断公众号环境或APP环境展示内容
1. 首先是微信浏览器环境
如果是微信公众号环境需要需要展示
许多复杂的业务场景,需要通过网页形式来提供服务,这时需要用到:
1.网页授权获取用户基本信息:通过该接口,可以获取用户的基本信息(获取用户的 OpenID 是无需用户同意的,获取用户的基本信息则需用户同意)
2.微信JS-SDK:是开发者在网页上通过 JavaScript 代码使用微信原生功能的工具包,开发者可以使用它在网页上录制和播放微信语音、监听微信分享、上传手机本地图片、拍照等许多能力。
首先判断是否是浏览器环境
v-if="windows"
data() {
return {window: window}
}
使用微信的JS-SDK
npm install jweixin-module --save
common文件夹新建js文件,我这里命名jwx.js
jwx内容
var jweixin = require('jweixin-module');
export default {
//判断是否在微信中
isWechat: function() {
var ua = window.navigator.userAgent.toLowerCase();
if (ua.match(/micromessenger/i) == 'micromessenger') {
//console.log('是微信客户端')
return true;
} else {
//console.log('不是微信客户端')
return false;
}
},
}
main.js 文件里引入
import jwx from '@/common/jwx'
Vue.prototype.$jwx = jwx
在需要的页面直接调用
if (this.$jwx && this.$jwx.isWechat()) { //注意这里的isWeChat要带括号
//检查是否是微信环境
}
2. 然后需要微信授权登录
onLoad() {
if (this.$jwx && this.$jwx.isWechat()) {
this.checkWeChatCode() //通过微信官方接口获取code之后,会重新刷新设置的回调地址【redirect_uri】
}
}
methods: {
//检查浏览器地址栏中微信接口返回的code
checkWeChatCode() {
let code = this.getUrlCode('code')
if (code) {
//这里如果有邀请码可以在上面判断力加uni.getStorageSync('inviteCode')
this.wechatLogin(code)
} else if (!code) {
this.getWeChatCode()
}
},
//方法:用来提取code
getUrlCode(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, '' ])[1]replace(/\+/g, '%20')) || null
},
//请求微信接口,用来获取code
getWeChatCode() {
let local = encodeURIComponent(window.location.href); //获取当前页面地址作为回调地址
let appid = 'wx2c547986a4a174a1' //申请的公众号appid
//通过微信官方接口获取code之后,会重新刷新设置的回调地址【redirect_uri】
window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
appid + "&redirect_uri=" + local + "&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect"
},
wechatLogin(code) {
let that = this
uni.hideLoading();
//把code传给后端
that.$post({
module: 'Wechat',
interface: 1000,
data: {
code: code, //code、openid要啥给啥
openid: code,
//有邀请码传邀请码 inviteCode: uni.getStorageSync('inviteCode'),
}
}).then((res => {
uni.setStorageSync('token', res.accessToken)
uni.showToast({
title: '登录成功',
})
//有邀请码的话清除一下uni.removeStorageSync('inviteCode')
setTimeout(() => {
//如果登录要去付款,判断传参跳转首页还是支付页面就可
if(type='pay') {
uni.navigateTo({
url: '/my/page/settle/payment'
})
}else{
uni.switchTab({
url: '/pages/home/index'
})
}
},1000)
}))
},
}
3. 如果是APP
<view v-if="window">微信授权登录</view>
<view v-else>
app页面内容
</view>
然后就是支付了
这里登录成功进入首页,有个扫码付款的正好记录下
引入qrcode
let qrcode = require('../../utils/common/reqrcode.js');
<u-icon name="scan" @click="ScanCode()"></u-icon>
//这里识别二维码边框要大,不然识别失败,不知道啥原因,生成二维码的时候给二维码加个边框就可以了
ScanCode() {
// 判断是浏览器还是app,true为浏览器,false为app
if ( ) {
let that = this
uni.chooseImage({
count: 1, //默认9 上传数量
success: res => {
let url = res.tempFilePaths[0];
qrcode.qrcode.decode(url);
qrcode.qrcode.callback = function (imgMsg) {
if (imgMsg == 'Failed to load the image' || imgMsg ==
'error decoding QR Code') {
uni.showToast({
title: '识别二维码失败,请重新上传!',
icon: 'none'
})
} else {
console.log(imgMsg);
window.location = imgMsg
}
}
}
})
} else {
uni.scanCode({
success: (res) => {
let result = res.result.split(",");
uni.navigateTo({
url: this.gotoCodeUrl[result[1]] + result[0],
});
},
});
}
},
刚好又看到个APP更新
//获取版本信息
getHomeInfo() {
if (window == undefined) {
this.$post({
module: 'Utils',
interface: 1002,
data: {
platform: 1,
version: this.version
}
}).then(res => {
if (res.newVersion) {
this.newVersion = res.newVersion
this.isShowPopup = true
}
})
}
},
<u-popup v-model="isShowPopup" mode="center" :closeable="newVersion.isForced == 0?true:false">
<view class="popup">
<view>发现新版本:{{ newVersion.version }}</view>
<view>更新日志</view>
<view>{{ newVersion.desc }}</view>
<view class="popup-button">
<u-button @click="isShowPopup = false" type="default" v-show="newVersion.isForced == 0">暂不升级
</u-button>
<u-button @click="createDownload(newVersion.upgradeUrl)" type="success">立即更新</u-button>
</view>
</view>
</u-popup>
data() {
return {
version: '1.0.0', //当前版本
isShowPopup: false, //展示弹窗
newVersion: {}
}
}
methods: {
createDownload(url) {
//用plus,app能直接用
var dtask = plus.downloader.createDownload(url, {},
function (d, status) {
uni.showToast({
title: '下载完成',
mask: false,
duration: 1000
});
// 下载完成
console.log('status: ' + status);
if (status == 200) {
console.log('下载成功:' + d.filename);
console.log('plus.io.convertLocalFileSystemURL(d.filename): ' + plus.io
.convertLocalFileSystemURL(d.filename))
plus.runtime.install(plus.io.convertLocalFileSystemURL(d.filename), {}, function (success) {
uni.showToast({
title: '安装成功',
mask: false,
duration: 1500
});
}, function (error) {
uni.showToast({
title: '安装失败-01',
mask: false,
duration: 1500
});
})
} else {
uni.showToast({
title: '更新失败-02',
mask: false,
duration: 1500
});
}
});
try {
dtask.start(); // 开启下载的任务
var prg = 0;
var showLoading = plus.nativeUI.showWaiting("正在下载"); //创建一个showWaiting对象
dtask.addEventListener('statechanged', function (task, status) {
console.log('自动更新测试1:', task)
console.log('自动更新测试2:', status)
// 给下载任务设置一个监听 并根据状态 做操作
switch (task.state) {
case 1:
showLoading.setTitle("正在下载");
break;
case 2:
showLoading.setTitle("已连接到服务器");
break;
case 3:
prg = parseInt((parseFloat(task.downloadedSize) / parseFloat(task.totalSize)) *
100);
showLoading.setTitle(" 正在下载" + prg + "% ");
break;
case 4:
plus.nativeUI.closeWaiting();
//下载完成
break;
}
});
} catch (err) {
console.log('错误信息', err)
plus.nativeUI.closeWaiting();
}
},
}