微信小程序 云开发 生成带参小程序码 云函数网络请求(Node.js网络请求)

版权声明:微信公众号:Stevin的技术博客 https://blog.csdn.net/feng2qing/article/details/82914505

生成带参小程序码流程
1、小程序端上传生成二维码所需的参数到云函数
2、云函数使用appidappsecret请求access_token
3、云函数使用access_token + 小程序端上传的参数生成二维码
4、云函数将生成的二维码返回到小程序端(或者存到数据库返回fileID,小程序端用fileID进行获取,后续生成先在数据库查找,数据库没有再执行生成操作,防止重复生成小程序码文件)

小程序端上传小程序码所需的参数
  wx.cloud.callFunction({
  name: 'getImage',   // 云函数名称
  data: {    // 小程序码所需的参数
    page: "pages/xxxx/xxxx",
    id: id,
  },
  complete: res => {
    console.log('callFunction test result: ', res)
    this.setData({    // 获取返回的小程序码
      xcxCodeImageData: res.result,
    })
  }
})
云函数用appidappsecret请求access_token
创建云函数getImage,并在对应云函数目录中导入requestrequest-promiseaxios框架(用于数据请求),
npm install --save request  // request框架
npm install --save request-promise   // request框架promise风格
npm install --save axios   // 数据请求框架,可将返回的数据类型设置为流`stream`
# 备注:install 可以简写为 i ;save 作用是将这个库添加到package.json里面
云函数文件中导入框架
const cloud = require('wx-server-sdk')
const axios = require('axios')
var rp = require('request-promise');
const fs = require('fs');
var stream = require('stream');
# 不需要全部导入,根据实际下面实际使用情况酌情导入
请求获取 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(`获取数据失败: ${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)    //小程序码图片数据
 })
 .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 = {
    // 小程序码参数
    "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 () {
		
		// 将返回的图片数据转化成uploadFile方法fileContent参数所需的文件流形式,且本地输出数据正常,可以试着用此方法执行uploadFile进行获取小程序码,作者采用了方法二
        var bufferStream = new stream.PassThrough();
        bufferStream.end(new Buffer(imgData));
        console.log('uploadFile方法fileContent参数所需的文件流----')
        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()

// 云函数入口函数
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框架相关文档:https://www.npmjs.com/package/request
request框架promise风格相关文档:https://www.npmjs.com/package/request-promise
axios框架相关文档:https://www.npmjs.com/package/axios
小程序云开发文档:https://developers.weixin.qq.com/miniprogram/dev/wxcloud/basis/getting-started.html

扫码实时获取更多技术文章

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/feng2qing/article/details/82914505