index.ts 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. const fetch = require('node-fetch')
  2. const FormData = require('form-data')
  3. const { createReadStream } = require('fs')
  4. const ROBOT_ID = 'cli_a13ad2afa438d00b'
  5. const ROBOT_ST = '4tK9LY9VbiQlY5umhE42dclBFo6t4p5O'
  6. const ROBOT_URL = 'https://open.feishu.cn/open-apis/bot/v2/hook/4a877590-334e-4212-9198-25e7768c64f9'
  7. const IMG_UPLOAD_URL = 'https://open.feishu.cn/open-apis/im/v1/images'
  8. const GET_ACCESS_TOKEN_URL = 'https://open.feishu.cn/open-apis/auth/v3/app_access_token/internal'
  9. async function getAccessToken() {
  10. const body = {
  11. app_id: ROBOT_ID,
  12. app_secret: ROBOT_ST
  13. }
  14. const response = await fetch(GET_ACCESS_TOKEN_URL, {
  15. method: 'post',
  16. body: JSON.stringify(body),
  17. headers: {'Content-Type': 'application/json'}
  18. })
  19. return await response.json()
  20. }
  21. async function uploadQr(access_token, imgPath) {
  22. const formData = new FormData()
  23. const file = createReadStream(imgPath)
  24. formData.append('image', file)
  25. formData.append('image_type', 'message')
  26. const response = await fetch(IMG_UPLOAD_URL, {
  27. method: 'post',
  28. headers: {
  29. authorization: `Bearer ${access_token}`
  30. },
  31. body: formData
  32. })
  33. return await response.json()
  34. }
  35. async function sendQrToFeishu(image_key, desc) {
  36. const schema = {
  37. msg_type: 'post',
  38. content: {
  39. post: {
  40. zh_cn: {
  41. title: '小程序预览二维码',
  42. content: [
  43. [
  44. {
  45. tag: 'img',
  46. image_key: image_key
  47. }
  48. ],
  49. [
  50. {
  51. tag: 'text',
  52. text: desc
  53. }
  54. ]
  55. ]
  56. }
  57. }
  58. }
  59. }
  60. const response = await fetch(ROBOT_URL, {
  61. method: 'post',
  62. headers: {'Content-Type': 'application/json'},
  63. body: JSON.stringify(schema),
  64. })
  65. return await response.json()
  66. }
  67. function PostPreViewQr(ctx) {
  68. ctx.register({
  69. name: 'onPreviewComplete',
  70. fn: ({ success, data, error }) => {
  71. // console.log('接收预览后数据', success, data, error)
  72. if (success) {
  73. const { qrCodeLocalPath } = data
  74. getAccessToken().then((res: any) => {
  75. const { code, tenant_access_token, msg } = res
  76. if (code !== 0)
  77. return Promise.reject({ code, msg })
  78. return tenant_access_token
  79. }).then(res => uploadQr(res, qrCodeLocalPath))
  80. .then((res: any) => {
  81. const { code , data, msg } = res
  82. if (code !== 0)
  83. return Promise.reject({ code , msg })
  84. const { image_key } = data
  85. return sendQrToFeishu(image_key, '票圈极速+')
  86. }).catch(err => {
  87. console.error(err)
  88. })
  89. }
  90. }
  91. })
  92. }
  93. export default PostPreViewQr