index.js 1.9 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. // 云函数入口函数
  11. exports.main = async (event, context) => {
  12. const wxContext = cloud.getWXContext()
  13. const _openid = wxContext.OPENID
  14. const app = new TcbRouter({
  15. event
  16. });
  17. console.log('Event', event)
  18. app.use(async (ctx, next) => {
  19. ctx.data = {};
  20. await next();
  21. });
  22. app.router("getWxPhoneNumber", async (ctx, next) => {
  23. let {
  24. cloudID,
  25. encryptedData,
  26. errMsg,
  27. iv,
  28. session_key
  29. } = event
  30. console.log(event)
  31. let pc = new WXBizDataCrypt(APPID, session_key)
  32. let data = pc.decryptData(encryptedData, iv)
  33. ctx.body = {
  34. phone: data.phoneNumber,
  35. _openid
  36. }
  37. await next()
  38. })
  39. app.router("getOpenId", async (ctx, next) => {
  40. ctx.body = {
  41. openId: _openid
  42. }
  43. await next()
  44. })
  45. app.router("base", async (ctx, next) => {
  46. await next()
  47. })
  48. app.router("code2Session", async (ctx, next) => {
  49. let JSCODE = event.JSCODE
  50. let url = `https://api.weixin.qq.com/sns/jscode2session?appid=${APPID}&secret=${SECRET}&js_code=${JSCODE}&grant_type=authorization_code`
  51. let res = await got(url)
  52. let result = JSON.parse(res.body)
  53. ctx.body = {
  54. ...result,
  55. _openid
  56. }
  57. await next()
  58. })
  59. app.router("getAccessToken", async (ctx, next) => {
  60. let tokenUrl = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${APPID}&secret=${SECRET}`
  61. let res = await got(tokenUrl)
  62. let {
  63. access_token
  64. } = JSON.parse(res.body)
  65. console.log(access_token)
  66. ctx.data = {
  67. access_token
  68. }
  69. await next();
  70. });
  71. return app.serve();
  72. }