## uni-app 微信小程序生成二維碼帶參數
### 第一步: 獲取 access\_token
```
getToken() {
uni.showLoading({
title: '加載中',
mask: true
})
let APPID = '從后臺獲取'
let APPSECRET = '從后臺獲取'
uni.request({
url: `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${APPID}&secret=${APPSECRET}`,
method: "GET",
}).then((res) => {
if (res[1].data.expires_in != 7200) {
uni.showToast({
title: "分享失敗,請重新嘗試。",
icon: "none",
duration: 2000
})
uni.hideLoading();
return
}
console.log(res)
this.shareToken = res[1].data.access_token
uni.hideLoading();
}).catch(err => {
console.log(err)
uni.hideLoading();
})
},
```
- 這里需要注意的是,現在我們是在前端寫的,測試的時候設置成為不校驗域名,真是線上版本的時候,是不能這么寫的,因為涉及到機密的數據:APPID 和?APPSECRET,微信是強制不讓在前端做這個。
- 報錯: https://api.weixin.qq.com不在以下 request 合法域名列表中,請參考文檔:https://developers.weixin.qq.com/miniprogram/dev/framework/ability/network.html
- 所以必須在服務器上獲取token 然后再通過后臺的服務器返回 token給前端。(沒有服務器的也不要擔心,云開發可以解決這個難題,寫一個云函數來代替服務器返回token)
### 第二步:將要轉換的頁面和參數轉換為小程序碼
> 請求微信的接口的時候請求方式為post,要注意設置相應的數據格式為**arraybuffer**,請求完畢后將數值轉換為base64。
~~~
getWxCode() {
let that = this
let userId = uni.getStorageSync('userId') //這里是我要傳遞的參數
let scene='t/qrcode01*id/'+ userId; // 這里設置了渠道和分享人的信息
//let scene= 'id=123&name=jack' 也可以是這樣子的格式
console.log(scene)
uni.showLoading({
title: '加載中',
mask: true
})
uni.request({
url: `https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=${this.shareToken}`,
method: "POST",
data: {
scene: scene,
page: 'pages/index/index'
},
responseType: 'arraybuffer',
success: function(res) {
uni.hideLoading();
let src = wx.arrayBufferToBase64(res.data);
that.src2 = 'data:image/png;base64,' + src;
that.showQrcode = true //控制彈出框,展示二維碼
}
})
},
~~~
注意:**通過微信開發文檔將頁面轉換為帶參數的小程序碼(一定要保證當前小程序有線上版本)**
最后連貫起來就是:
~~~
createQrCode() {
console.log("生成專屬二維碼")
if(this.src2){
this.showQrcode = true
} else {
this.showQrcode = false
this.getToken()
}
},
~~~
頁面中如果獲取傳遞的參數呢?
~~~
onLoad: function (options) {
let scene = decodeURIComponent(options.scene)
console.log(scene)
},
~~~
- 前端指南
- 基礎
- HTML、HTTP、web綜合問題
- css部分
- 學習指南
- 開發指南
- css指南
- JavaScript
- 視圖、文件
- canvas
- 二維碼的生成
- 64碼及圖片
- weui
- Promise
- 第三方js
- 網絡請求
- 字符串,數組,時間
- 時間類
- Css
- 布局封裝
- 媒體布局
- 九宮格圖片自適應
- 兩行顯示,且省略
- uni-app
- uniapp踩坑指南
- 表單類
- 商品規格
- 頁面操作
- H5端返回按鈕不顯示
- H5解決瀏覽器跨域問題
- uView——Waterfall 瀑布流
- uniapp中使用復制功能(復制文本到粘貼板)
- 動態導航欄的實現
- React
- React基礎
- 微信小程序
- 上傳多圖
- uni-app 微信小程序生成小程序碼二維碼帶參數
- 小程序分享圖片給好友,到朋友圈,保存到本地
- 緩存封裝
- Vue
- 深度作用選擇器deep
- 使用js實現列表無限循環滾動(橫向)
- js 無限循環垂直滾動列表
- 可視化
- AntV
- 玫瑰圖