uniapp小程序生成小程序碼
發表時(shí)間:2020-11-27
發布人(rén):融晨科技
浏覽次數:100
文章目錄
- 前言
- 一、自測版本
- 二、線上(shàng)版本
- 三、測試
- 總結
前言
需求:用戶通過掃描小程序碼,直接跳轉到(dào)小程序的(de)登陸頁,并自動填充推薦碼
一、自測版本
用于(yú)前端自己測試如何生成小程序碼
<!-- 以(yǐ)圖片的(de)形式展示 -->
<image :src="maskData"></image>
onLoad(options) {
console.log('需要(yào / yāo)推薦碼',options)//打印出(chū)來(lái)是(shì) {scene: "code%3D2QQ"}
const scene = options.scene ? decodeURIComponent(options.scene) : ''
console.log('編譯出(chū)來(lái)的(de)scene',scene) //打印出(chū)來(lái)是(shì) code=3D2QQ
this.code = scene.split('=')[1]//打印出(chū)來(lái)是(shì) 3D2QQ
console.log('編譯出(chū)來(lái)的(de)推薦碼',this.code)
},
getData(e) {
//獲取accessToken
let that = this;
const APP_ID = 'xxx'; // 小程序appid
const APP_SECRET = 'xxxxx'; // 小程序app_secret
let access_token = '';
uni.request({
url: "https://api.weixin.qq.com/cgi-bin/token", //固定鏈接,不(bù)用改
data: {
grant_type: 'client_credential',
appid: APP_ID,
secret: APP_SECRET
},
success: function(res) {
console.log('獲取accessToken', res)
access_token = res.data.access_token;
// 接口B:适用于(yú)需要(yào / yāo)的(de)碼數量極多的(de)業務場景 生成的(de)是(shì)小程序碼
that.getQrCode(access_token);
}
})
},
//獲取二維碼
getQrCode(access_token) {
var that = this;
uni.request({
url: "https://api.weixin.qq.com/wxa/getwxacode?access_token=" + access_token,//固定鏈接,不(bù)用改
method: 'POST',
responseType: 'arraybuffer', //設置響應類型
data: {
path: 'pages/public/login?code=' + that.code, // 必須是(shì)已經發布的(de)小程序存在(zài)的(de)頁面(否則報錯)
width: 298,
auto_color: false, // 自動配置線條顔色,如果顔色依然是(shì)黑色,則說(shuō)明不(bù)建議配置主色調
line_color: {
"r": "0",
"g": "0",
"b": "0"
} // auto_color 爲(wéi / wèi) false 時(shí)生效,使用 rgb 設置顔色
},
success: function(res) {
console.log('獲取二維碼', res)
that.maskData = "data:image/PNG;BASE64," + uni.arrayBufferToBase64(res.data);//以(yǐ)圖片的(de)形式展示
}
})
}
二、線上(shàng)版本
原來(lái)以(yǐ)爲(wéi / wèi)很難的(de),壓力都在(zài)前端,等做完了(le/liǎo),測試體驗版的(de)時(shí)候,發現api.weixin.qq.com域名沒加進去,結果官方跟我說(shuō),不(bù)能加這(zhè)個(gè)域名,原因是(shì)前端不(bù)能直接用上(shàng)面的(de)方法自己去生成小程序碼,必須要(yào / yāo)通過後台服務器轉一下
// 給了(le/liǎo)個(gè)token,後端自己去實現自測版本中的(de)操作-生成小程序碼,返回圖片地(dì / de)址,前端直接展示圖片就(jiù)好了(le/liǎo),666
getData(e) {
this.$api
.qrcode({
token: this.token
})
.then(res => {
console.log('我的(de)推薦碼', res)
this.maskData = res
})
.catch(err => {
this.$api.msg(err)
});
三、測試
截取生成小程序碼的(de)圖片,用微信開發者工具的(de)“通過二維碼編譯”掃碼測試能不(bù)能拿到(dào)參數,并填充
總結
事情其實很簡單,沒必要(yào / yāo)想的(de)太複雜