index.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. const crypto = require('crypto')
  2. const createConfig = require('uni-config-center')
  3. const config = createConfig({
  4. pluginId: 'uni-cms'
  5. }).config()
  6. const unlockRecordDBName = 'uni-cms-unlock-record'
  7. // 定义云函数
  8. exports.main = async function (event) {
  9. // 解构 event 对象
  10. const {trans_id, extra: _extra, sign} = event
  11. let extra = {}
  12. try {
  13. extra = JSON.parse(_extra)
  14. } catch (e) {}
  15. // 如果 adConfig 或 securityKey 配置项不存在,则抛出错误引导用户配置参数
  16. if (!config.adConfig || !config.adConfig.securityKey) throw new Error('请先配置adConfig.securityKey')
  17. // 如果 extra.article_id 不存在,则返回 null
  18. if (!extra.article_id) return null
  19. // 签名验证
  20. const reSign = crypto.createHash('sha256').update(`${config.adConfig.securityKey}:${trans_id}`).digest('hex')
  21. if (sign !== reSign) {
  22. console.log('签名错误', `${config.adConfig.securityKey}:${trans_id}`)
  23. return null
  24. }
  25. // 获取数据库实例
  26. const db = uniCloud.database()
  27. // 查询解锁记录
  28. const unlockRecord = await db.collection(unlockRecordDBName).where({
  29. trans_id
  30. }).get()
  31. // 如果已经解锁过了,则返回 null
  32. if (unlockRecord.data.length) {
  33. console.log('已经解锁过了')
  34. return null // 已经解锁过了
  35. }
  36. // 添加解锁记录
  37. await db.collection(unlockRecordDBName).add({
  38. unique_id: extra.unique_id,
  39. unique_type: extra.unique_type,
  40. article_id: extra.article_id,
  41. trans_id,
  42. create_date: Date.now()
  43. })
  44. console.log('解锁成功')
  45. // 应广告规范,需返回 isValid 为 true
  46. return {
  47. isValid: true
  48. }
  49. }