微信小程序云函数发天气预报

1.开通腾讯云短信,注册签名、模板,拿到API接口。

2.开通心知天气API的免费版。

3.因为人数较多,涉及到自动推送且心知天气免费版的访问速度限制,首先要把通讯录导进云数据库里,而小程序的云数据库单次访问只能读20条数据,用云函数打破限制。

const cloud = require(wx-server-sdk)
cloud.init({env:your id})
exports.main = async (event, context) => {
  const db = cloud.database()
  let num = await db.collection(msg_Sendlist).count()
  num = count.total
  let all = []
  for (let i = 0; i < num; i += 20) {
    let list = await db.collection(your collection).skip(i).get()
    all = all.concat(list.data);
  }
  return all;
}

4.先获取通讯录,拿到人名手机号,再根据上传的位置获取天气,封装成数据推给短信平台

put(){
    //设置计时器循环,可以避免速度过快导致的发送不出去
    var index = 0
    console.log(index)
  var a=setInterval(function () {
    console.log(index)
    const element = array1[index];
  pname = element.name
  var city = element.city
  up[0] = pname//人名
  up[1]=city //地区
  phNum = element.phNum
  lat = element.lat
  lng =  element.lng
  var f=https://api.seniverse.com/v3/weather/daily.json?key= key value
  var g=&language=zh-Hans&unit=c&start=0&days=5
  var local = lat+":"+lng//发送人所在位置
  var url = f+local+g
  wx.request({
    url: url,
    success:res=>{
      var resdata = res.data.results[0]//获取结果写入数组
      var daliy = resdata.daily[0]
      up[2]=daliy.text_day+"-"+daliy.text_night//天气变化
      up[3]=daliy.high+"-"+daliy.low//气温变化
      up[4]=daliy.wind_speed//风速变化
      console.log(up)
      wx.cloud.callFunction({
        name:nodejs name,
        data:{
          phNum:"+86"+phNum,//向云端发送数据
          text:up
        },
        success:res=>{
          console.log("发送成功")
        },
        fail:console.error()
      })

    }
  })
  console.log(up)
  index++
  
  if(index>=array1.length)
  { 
      clearInterval(a) 
  }
  //循环执行代码
}, 4000)//此处设置访问时间间隔避免读取速度过快
  },

5.短信推送云函数,这个地方反复好几次,最后发现小程序端传的数组要在云函数端再封一下才可以

const cloud = require(wx-server-sdk)
cloud.init()
exports.main = async (event, context) => {
  var pn=[] //这里踩了坑,本来以为数组可以直接传进API,结果还要在云函数里再封一下
  var tx=[]
  pn[0] = event.phNum
  tx = event.text
  const tencentcloud = require("tencentcloud-sdk-nodejs")
  const smsClient = tencentcloud.sms.v20210111.Client
  const client = new smsClient({
  credential: {
    secretId:your id,
    secretKey:your key,
  },
  region: "ap-guangzhou",
  profile: {
    signMethod: "HmacSHA256",
    httpProfile: {
      reqTimeout: 30,
      endpoint: "sms.tencentcloudapi.com"
    },
  },
  })
  const params = {
  SmsSdkAppId:" your appid",
  SignName:" your signname",
  ExtendCode: "",
  SenderId: "",
  SessionContext: "",
  PhoneNumberSet: pn,
  TemplateId: " your id",
  TemplateParamSet: tx,
  }
  client.SendSms(params, function (err, response) {
  if (err) {
    console.log(err)
    return
  }
  console.log(response)
  })
}
经验分享 程序员 微信小程序 职场和发展