前言
遇到了一個需求,想要掃碼后,進(jìn)入微信小程序的某一個頁面,這就要求二維碼攜帶參數(shù)。
微信小程序開發(fā)文檔很簡單,但不太具體。
經(jīng)百度和折騰,在express中成功獲得了帶參數(shù)的二維碼。
總結(jié)以下幾步,供參考。
1.express項目中引入http請求工具
為什么要在服務(wù)端引入這個工具?因為還需要用這個工具去找微信服務(wù)端拿access_token接口憑證,來保證安全。
筆者用的是axios。cmd進(jìn)入根目錄,npm安裝。
# npm i axios --save
肯定需要寫一個獲得二維碼的接口。在寫這個接口的文件中引入axios即可,接口路由的寫法不具體展開介紹。
import express from 'express';import axios from 'axios'; //引入axios庫let qrcode= express.Router();qrcode.post('/getQrode',async (req,res)=>{ try { ... //待寫接口內(nèi)容區(qū)域 } catch (error) { throw error; }})export default qrcode;引入了庫,定義了路由,也定義了一個post接口。第一步準(zhǔn)備完畢。
2.獲取access_token
找微信服務(wù)端拿access_token,需要用上剛剛引入的axios工具了。
通過官方文檔介紹,獲取access_token需要三個參數(shù),一個常量grant_type,兩個變量分別是appid和secret(注冊小程序的時候就會獲得)
修改接口即可獲得access_token
import express from 'express';import axios from 'axios';let qrcode= express.Router();qrcode.post('/share',async (req,res)=>{ try { let appid = 'wxc********b7a'; let secret = '2bfa**************e8682'; let url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${secret}` axios.get(url).then(res2=>{ //access_token就在res2中 let access_token = res2.data.access_token; //待繼續(xù)補(bǔ)充區(qū)域 }); } catch (error) { console.log(error) }})export default qrcode;拿到了access_token接口憑證了,繼續(xù)下一步。
3.獲取二維碼的二進(jìn)制數(shù)據(jù)
閱讀文檔,得知需要進(jìn)一步傳參,請求微信服務(wù)端獲取二維碼的buffer數(shù)據(jù)。
需要攜帶的參數(shù)可以寫在scene中。其他參數(shù)文檔中介紹的已經(jīng)很具體。
然而,這里有兩個坑要注意!
第一個坑:access_token參數(shù)要寫在url中,不然請求后會報未傳access_token的錯。
第二個坑:要設(shè)置響應(yīng)格式,否則請求回來的buffer數(shù)據(jù)總是被編譯成String字符串,造成文件損壞,就無法轉(zhuǎn)化為正常圖片(這個折磨了我好久)
import express from 'express';import axios from 'axios';let qrcode = express.Router();qrcode.post('/share',async (req,res)=>{ try { let appid = 'wxc********b7a'; let secret = '2bfa**************e8682'; let url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${secret}` axios.get(url).then(res2=>{ let scene = req.body._id;//開發(fā)者自己自定義的參數(shù) axios( { headers:{"Content-type":"application/json"}, method: 'post', responseType: 'arraybuffer', url: 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='+access_token+'', data:{ scene:scene, page:'pages/infor/main', width: 280 } } ).then(res3=>{ //請求到的二維碼buffer就在res3中 //待完善區(qū)域 }) }); } catch (error) { console.log(error) }})export default qrcode;
新聞熱點
疑難解答