index.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. }
  56. await next()
  57. })
  58. app.router("getAccessToken", async (ctx, next) => {
  59. let tokenUrl = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${APPID}&secret=${SECRET}`
  60. let res = await got(tokenUrl)
  61. let {
  62. access_token
  63. } = JSON.parse(res.body)
  64. console.log(access_token)
  65. ctx.data = {
  66. access_token
  67. }
  68. await next();
  69. });
  70. return app.serve();
  71. }