index.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. // 云函数入口文件
  2. const cloud = require('wx-server-sdk')
  3. const TcbRouter = require("tcb-router")
  4. const got = require('got')
  5. const md5 = require("md5")
  6. const APPID = "wxf22759845920b6f3"
  7. const SECRET = "149873f78958781cd1693c1238deaebc"
  8. const WXBizDataCrypt = require('./WXBizDataCrypt')
  9. cloud.init()
  10. const db = cloud.database()
  11. const errorLogs = db.collection("huihenduo_error_log")
  12. // 云函数入口函数
  13. exports.main = async (event, context) => {
  14. const wxContext = cloud.getWXContext()
  15. const _openid = wxContext.OPENID
  16. const app = new TcbRouter({
  17. event
  18. });
  19. console.log('Event', event)
  20. app.use(async (ctx, next) => {
  21. ctx.data = {};
  22. await next();
  23. });
  24. app.router("base", async (ctx, next) => {
  25. await next()
  26. })
  27. app.router("code2Session", async (ctx, next) => {
  28. let JSCODE = event.JSCODE
  29. let url = `https://api.weixin.qq.com/sns/jscode2session?appid=${APPID}&secret=${SECRET}&js_code=${JSCODE}&grant_type=authorization_code`
  30. let res = await got(url)
  31. let result = JSON.parse(res.body)
  32. ctx.body = {
  33. ...result,
  34. _openid
  35. }
  36. await next()
  37. })
  38. app.router("getAccessToken", async (ctx, next) => {
  39. let tokenUrl = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${APPID}&secret=${SECRET}`
  40. let res = await got(tokenUrl)
  41. let {
  42. access_token
  43. } = JSON.parse(res.body)
  44. console.log(access_token)
  45. ctx.data = {
  46. access_token
  47. }
  48. await next();
  49. });
  50. app.router("sendMsg", async (ctx, next) => {
  51. let result = await cloud.openapi.subscribeMessage.send({
  52. "touser": _openid,
  53. "page": 'pages/index/index',
  54. "lang": 'zh_CN',
  55. "data": {
  56. "character_string2": {
  57. "value": '32℃'
  58. },
  59. "thing3": {
  60. "value": '地点'
  61. },
  62. "time4": {
  63. "value": '2020-05-20 11:55:33'
  64. },
  65. "thing5": {
  66. "value": '提示'
  67. }
  68. },
  69. "templateId": 'q1joCPFWjhAxSJtrZ30QFi_aA9LVva4PQZmBcxZIPhU',
  70. "miniprogramState": 'developer'
  71. })
  72. ctx.data = {
  73. result
  74. }
  75. await next();
  76. });
  77. return app.serve();
  78. }