收藏
回答

subscribeMessage.send在本地调试调用成功,放到云函数上定时调用失败?

发送失败 ocWl613KCk-rpE5K-qgsq4NKjFk4: CloudSDKError: errCode: -501007 invalid parameters | errMsg: subscribeMessage.send:fail missing wxCloudApiToken 请前往云开发AI小助手查看问题:https://tcb.cloud.tencent.com/dev#/helper/copilot?q=INVALID_PARAM

回答关注问题邀请回答
收藏

2 个回答

  • 云开发小助手CloudBase
    云开发小助手CloudBase
    09-28

    错误码 -501007的含义是 ​​“订阅消息接口调用权限不足”​​,通常由以下原因导致:

    1. 订阅消息模板未关联​

    在小程序后台的 ​​“订阅消息” > “公共模板库”​​ 中,需将模板关联到当前小程序,否则云端无权调用。

    2.​​OpenID 无效或未授权​

    定时触发的云函数中,传入的 openid可能无效,或该用户未主动授权订阅消息。


    09-28
    有用
    回复
  • showms
    showms
    09-28

    代码怎么写的

    09-28
    有用
    回复 1
    • 阿辉
      阿辉
      09-28
      const cloud = require('wx-server-sdk');
      // 初始化云开发环境
      cloud.init({
        env: "cloudbase-2g4hs94ga004ac65"
      });
      const db = cloud.database();
      exports.main = async (event, context) => {
        console.log('开始执行每日签到提醒推送...');
        try {
          // 查询需要提醒的用户
          const users = await db.collection('subscribe_users')
            .where({
              'templates.TEMPLATE_ID_SIGNIN_REMINDER.remain': db.command.gt(0)
            }).limit(1000).get();
            // const users = await db.collection('subscribe_users').get()
          console.log(`找到 ${users.data.length} 个需要提醒的用户`);
          if (users.data.length === 0) {
            return { success: true, message: '没有需要提醒的用户', count: 0 };
          }
          const results = [];
          let successCount = 0;
          let failCount = 0;
          // 批量发送提醒
          for (const user of users.data) {
            try {
              // 检查用户今日是否已签到
              const today = new Date().toISOString().split('T')[0];
              const date = new Date();
              const time = date.getHours()+":"+date.getMinutes();
              const signinRecord = await db.collection('daily_signin')
                .where({
                  openid: user.openid,
                  date: today
                }).get();
              // 如果已签到,跳过提醒
              if (signinRecord.data.length > 0) {
                console.log(`用户 ${user.openid} 今日已签到,跳过提醒`);
                continue;
              }
              // 发送订阅消息
              await cloud.openapi.subscribeMessage.send({
                touser: user.openid,
                templateId: '2sv7THelPe2CwSV_hzJHE5fQfOpE5syBLrZ2lizD7Z8',
                page: 'index',
                data: {
                  thing5: { value: '每日签到提醒' },
                  date4: { value: today+" "+ time},
                  thing7: { value: '记得来签到领取奖励哦~' }
                }
              });
              // 扣减订阅次数(一次性订阅)
              await db.collection('subscribe_users').doc(user.openid).update({
                data: {
                  'templates.TEMPLATE_ID_SIGNIN_REMINDER.remain': 0
                   }
              });
              successCount++;
              results.push({ openid: user.openid, status: 'success' });
              console.log(`成功发送提醒给用户: ${user.openid}`);
              // 添加延迟避免频率限制
              await new Promise(resolve => setTimeout(resolve, 100));
            } catch (error) {
              failCount++;
              results.push({
                openid: user.openid,
                status: 'failed',
                error: error.errCode || error.message
              });
              console.error(`发送失败 ${user.openid}:`, error);
              // 如果是订阅失效,清零剩余次数
              if (error.errCode === 43101) {
                await db.collection('subscribe_users').doc(user.openid).update({
                  data: {
                    'templates.TEMPLATE_ID_SIGNIN_REMINDER.remain': 0
                  }
                });
              }
            }
          }
          const summary = {
            success: true,
            total: users.data.length,
            successCount: successCount,
            failCount: failCount,
            results: results
          };
          console.log('推送完成:', summary);
          return summary;
        } catch (error) {
          console.error('推送任务执行失败:', error);
          return {
            success: false,
            error: error.message,
            code: error.errCode
          };
        }
      };
      09-28
      回复
登录 后发表内容