微信小程序云開發(fā) 生成帶參小程序碼流程
本文實例為大家分享了小程序生成帶參小程序碼的具體步驟,供大家參考,具體內容如下
生成帶參小程序碼流程
1、小程序端上傳生成二維碼所需的參數(shù)到云函數(shù)
2、云函數(shù)使用appid和appsecret請求access_token
3、云函數(shù)使用access_token + 小程序端上傳的參數(shù)生成二維碼
4、云函數(shù)將生成的二維碼返回到小程序端(或者存到數(shù)據(jù)庫返回fileID,小程序端用fileID進行獲取,后續(xù)生成先在數(shù)據(jù)庫查找,數(shù)據(jù)庫沒有再執(zhí)行生成操作,防止重復生成小程序碼文件)
小程序端上傳小程序碼所需的參數(shù)
wx.cloud.callFunction({
name: 'getImage', // 云函數(shù)名稱
data: { // 小程序碼所需的參數(shù)
page: "pages/xxxx/xxxx",
id: id,
},
complete: res => {
console.log('callFunction test result: ', res)
this.setData({ // 獲取返回的小程序碼
xcxCodeImageData: res.result,
})
}
})
云函數(shù)用appid和appsecret請求access_token
創(chuàng)建云函數(shù)getImage,并在對應云函數(shù)目錄中導入request 、request-promise、axios框架(用于數(shù)據(jù)請求),
npm install --save request // request框架 npm install --save request-promise // request框架promise風格 npm install --save axios // 數(shù)據(jù)請求框架,可將返回的數(shù)據(jù)類型設置為流`stream` # 備注:install 可以簡寫為 i ;save 作用是將這個庫添加到package.json里面
云函數(shù)文件中導入框架
const cloud = require('wx-server-sdk')
const axios = require('axios')
var rp = require('request-promise');
const fs = require('fs');
var stream = require('stream');
# 不需要全部導入,根據(jù)實際下面實際使用情況酌情導入
請求獲取 access_token
// request框架promise風格
rp('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=secret=appSecret'
.then(function(resultValue) {
console.log("請求 success:")
console.log(JSON.parse(resultValue))
})
.catch(function(err) {});
});
// Nodejs原生寫法
const http = require("https")
const url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=secret=appSecret"
http.get(url,(res)=>{
var resultValue = ""
res.on("data",(data)=>{
resultValue+=data
})
res.on("end",()=>{
console.log(resultValue)
})
}).on("error",(e)=>{
console.log(`獲取數(shù)據(jù)失敗: ${e.message}`)
})
獲取小程序碼
var options = {
method: 'POST',
url: 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' + access_token',
body: {
page: "pages/xxx/xxx
scene: "id=xxx"
},
json: true
};
rp(options)
.then(function(parsedBody) {
console.log(parsedBody) //小程序碼圖片數(shù)據(jù)
})
.catch(function(err) {});
服務端完整代碼一
var rp = require('request-promise');
const fs = require('fs');
var stream = require('stream');
// 請求微信access_token
rp('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=appid&secret=secret')
.then(function(resultValue) {
console.log("請求 success:" + resultValue)
console.log(JSON.parse(resultValue).access_token)
// 請求小程序碼
var http = require("http"),
data = {
// 小程序碼參數(shù)
"page": "pages/CardDetail/CardDetail",
"width": 300,
"scene": "id=W6MIjlJhFW5Pec-Y",
};
data = JSON.stringify(data);
var options = {
method: "POST",
host: "api.weixin.qq.com",
path: "/wxa/getwxacodeunlimit?access_token=" + JSON.parse(resultValue).access_token,
headers: {
"Content-Type": "application/json",
"Content-Length": data.length
}
};
var req = http.request(options, function (res) {
res.setEncoding("binary");
var imgData = '';
res.on('data', function (chunk) {
imgData += chunk;
});
res.on("end", function () {
// 將返回的圖片數(shù)據(jù)轉化成uploadFile方法fileContent參數(shù)所需的文件流形式,且本地輸出數(shù)據(jù)正常,可以試著用此方法執(zhí)行uploadFile進行獲取小程序碼,作者采用了方法二
var bufferStream = new stream.PassThrough();
bufferStream.end(new Buffer(imgData));
console.log('uploadFile方法fileContent參數(shù)所需的文件流----')
console.log(bufferStream)
// Sublime Text可以運行輸出到本地,且可以打開二維碼
// 本地存放路徑
var path = 'public/'+ Date.now() +'.png';
fs.writeFile(path, imgData, "binary", function (err) {
if (err) {
console.log("down fail");
}
console.log("down success");
});
});
});
req.write(data);
req.end();
})
.catch(function(err) {});
服務端完整代碼二(可直接粘貼使用)
const cloud = require('wx-server-sdk')
const axios = require('axios')
var rp = require('request-promise');
cloud.init()
// 云函數(shù)入口函數(shù)
exports.main = async (event, context) => {
console.log(event)
try {
const resultValue = await rp('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=appid&secret=secret')
const token = JSON.parse(resultValue).access_token;
console.log('------ TOKEN:', token);
const response = await axios({
method: 'post',
url: 'https://api.weixin.qq.com/wxa/getwxacodeunlimit',
responseType: 'stream',
params: {
access_token: token,
},
data: {
page: event.page,
width: 300,
scene: "id=" + event.id,
},
});
return await cloud.uploadFile({
cloudPath: 'xcxcodeimages/' + Date.now() + '.png',
fileContent: response.data,
});
} catch (err) {
console.log('>>>>>> ERROR:', err)
}
}
點擊查看:request框架相關文檔
點擊查看:axios框架相關文檔
點擊查看:小程序云開發(fā)文檔
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
使用coffeescript編寫node.js項目的方法匯總
Node.js 基于JavaScript編寫應用,JavaScript是我的主要開發(fā)語言。CoffeeScript是編譯為JavaScript的編程語言。CoffeeScript是一個非常高階的語言,將JavaScript、Ruby和Python中我最愛的部分結合在了一起。小編給大家介紹下使用coffeescript編寫node.js項目的方法2015-08-08

