index.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  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 = "wxd8fe7909b3471a51"
  7. const SECRET = "c5aeac63ae791b76942d8d52261ef710"
  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("getWxPhoneNumber", async (ctx, next) => {
  25. let {
  26. cloudID,
  27. encryptedData,
  28. errMsg,
  29. iv,
  30. session_key
  31. } = event
  32. console.log(event)
  33. let pc = new WXBizDataCrypt(APPID, session_key)
  34. let data = pc.decryptData(encryptedData, iv)
  35. ctx.body = {
  36. phone: data.phoneNumber,
  37. _openid
  38. }
  39. await next()
  40. })
  41. app.router("getOpenId", async (ctx, next) => {
  42. ctx.body = {
  43. openId: _openid
  44. }
  45. await next()
  46. })
  47. app.router("sendError", async (ctx, next) => {
  48. delete event.$url
  49. delete event.userInfo
  50. let res = await errorLogs.add({
  51. data: {
  52. createTime: db.serverDate(),
  53. ...event,
  54. _openid,
  55. }
  56. })
  57. await next()
  58. })
  59. app.router("base", async (ctx, next) => {
  60. await next()
  61. })
  62. app.router("code2Session", async (ctx, next) => {
  63. let JSCODE = event.JSCODE
  64. let url = `https://api.weixin.qq.com/sns/jscode2session?appid=${APPID}&secret=${SECRET}&js_code=${JSCODE}&grant_type=authorization_code`
  65. let res = await got(url)
  66. let result = JSON.parse(res.body)
  67. ctx.body = {
  68. ...result,
  69. _openid
  70. }
  71. await next()
  72. })
  73. app.router("getAccessToken", async (ctx, next) => {
  74. let tokenUrl = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${APPID}&secret=${SECRET}`
  75. let res = await got(tokenUrl)
  76. let {
  77. access_token
  78. } = JSON.parse(res.body)
  79. console.log(access_token)
  80. ctx.data = {
  81. access_token
  82. }
  83. await next();
  84. });
  85. app.router("getOpenId", async (ctx, next) => {
  86. ctx.data = {
  87. openId: _openid
  88. }
  89. await next();
  90. });
  91. return app.serve();
  92. }