Credits 与 VAS 接入

面板可显示当前生效套餐、可用 Credits 和剩余重置次数。商品区根据当前设备对应的有效套餐查询 VAS 商品,再显示匹配的报价。

准备接入

使用包含所需 Credits 方法的 @tuya-miniapp/cloud-api 版本,最低版本见各接口文档。用户须登录并具备当前设备访问权限。在小程序的开发设置中授权「小程序智能体开发能力」以查询账户、套餐和使用重置卡。查询商品、规格报价和订阅凭证还需授权「商城与增值服务」。小程序开发者平台

查询当前账户和可选套餐

用同一台设备的 devId 查询当前账户和可选套餐。

import {
  getPanelAgentCreditsAccount,
  getPanelAgentCreditsPlans,
} from '@tuya-miniapp/cloud-api';

export async function readCredits(devId: string) {
  const params = { devId };
  const [account, available] = await Promise.all([
    getPanelAgentCreditsAccount(params),
    getPanelAgentCreditsPlans(params),
  ]);
  return { account, available };
}
  • account.plan 表示设备当前生效的档位。已有付费档的 isSubscribed 可为 true,当前购买规格可取得时在 skuCode 返回。
  • account.remainingCredits 是十进制字符串,展示原值时直接使用。启用后的零余额为 "0"。reset.remaining 是设备当前可用的重置次数。
  • available.freePlan 是设备适用的免费档。available.plans 是当前有效的付费服务,沿用服务端顺序。按服务编码查某档权益可用 available.plans.find(plan => plan.externalCode === serviceCode)。

使用重置卡

当 account.subscriptionEnabled 为 true、account.plan.capacityCredits > 0 且 account.reset.remaining > 0 时,可启用重置按钮。用户确认后调用 resetPanelAgentCredits({ devId }),请求和账户刷新期间保持按钮禁用。接口与调用示例

  • 返回 true 时,余额恢复到当前套餐上限,已使用一次重置次数。余额已满时,成功调用也会扣次。
  • 返回 false 时,本次未消耗重置次数。

调用结束后,用 getPanelAgentCreditsAccount({ devId }) 刷新余额和剩余次数。遇到超时或断网时,先刷新账户,再由用户决定是否重试。

按商业模式查询商品

套餐查询返回 subscriptionEnabled: true 时,按 available.businessMode 选择商品绑定。核销使用当前设备的 PID,分销使用当前区域配置的公版 App ID。先用 getVasSpuList 取得商品编码。再调用 getMallInfoV2 获取商城、店铺、站点和币种,将这些参数与商品编码列表 commodityCodes 传给 getSkuListV2,查询当前商城下的 SKU 和报价。

商业模式bindingObjectTypebindingObjectCode
1 分销VasBindingObjectType.APP(2)当前区域的公版 App ID
2 核销VasBindingObjectType.PID(0)当前设备所属 PID
import {
  getMallInfoV2,
  getSkuListV2,
  getVasSpuList,
  VasBindingObjectType,
} from '@tuya-miniapp/cloud-api';
import type { GetPanelAgentCreditsPlansResult } from '@tuya-miniapp/cloud-api';

export async function readCreditProducts(
  available: GetPanelAgentCreditsPlansResult,
  device: { pid: string; publicAppId?: string }
) {
  if (!available.subscriptionEnabled) {
    return { subscriptionEnabled: false, products: [], quotes: null };
  }

  const distribution = available.businessMode === 1;
  const bindingObjectCode = distribution ? device.publicAppId : device.pid;
  if (!bindingObjectCode) throw new Error('Missing VAS binding code');

  const binding = {
    bindingObjectType: distribution ? VasBindingObjectType.APP : VasBindingObjectType.PID,
    bindingObjectCode,
    catalogCode: 'AGENT_RESOURCE',
  };
  const products = await getVasSpuList({ ...binding, needSkuList: true });
  if (!Array.isArray(products)) throw new Error('Invalid VAS product list');

  if (!products.length) return { subscriptionEnabled: true, products, quotes: null };

  try {
    const commodityCodes = Array.from(
      new Set(products.map(product => product.commodityCode).filter(Boolean))
    );
    if (!commodityCodes.length) throw new Error('Missing VAS commodity codes');

    const { mallCode, shopCode, siteCode, currency } = (await getMallInfoV2(binding)) ?? {};
    if (!mallCode || !shopCode || !siteCode || !currency) {
      throw new Error('Incomplete VAS mall information');
    }

    const mall = { mallCode, shopCode, siteCode, currency };
    const skus = await getSkuListV2({ ...binding, ...mall, commodityCodes });
    if (!Array.isArray(skus)) throw new Error('Invalid VAS SKU list');

    return {
      subscriptionEnabled: true,
      products,
      quotes: { status: 'ready' as const, mall, skus },
    };
  } catch (error) {
    return { subscriptionEnabled: true, products, quotes: { status: 'error' as const, error } };
  }
}

products 保存商品查询结果,返回的商品可附带用于关联的 SKU 元数据。quotes 保存规格报价查询结果。商品查询为空时跳过商城与规格查询。商城或规格调用失败时保留 products,并通过 quotes.error 返回错误。

筛选可展示的规格和报价

用 SKU V2 主能力或子能力的 externalCode 关联 available.plans,并限定 SKU 来自本次返回的商品。商品附带的 SKU 可补充同一规格的关联信息。quotes.status 为 ready 时,将 products、quotes.skus 和 available.plans 传给下面的函数,筛选匹配的 VAS 报价。

import { QuotaPeriodUnit, VasOptionType } from '@tuya-miniapp/cloud-api';
import type {
  PanelAgentCreditsPlan,
  VasCommodity,
  VasSku,
  VasSkuV2,
} from '@tuya-miniapp/cloud-api';

type CreditsProduct = Omit<VasCommodity, 'skuList'> & {
  sellable?: boolean;
  skuList?: (VasSku & { sellable?: boolean })[];
};

function serviceCodes(sku: Pick<VasSku, 'capability' | 'subCapabilities'>) {
  return [sku.capability, ...(sku.subCapabilities ?? [])]
    .map(capability => capability?.externalCode)
    .filter(Boolean);
}

export function getCreditOffers(
  products: CreditsProduct[],
  skus: (VasSkuV2 & { sellable?: boolean })[],
  plans: PanelAgentCreditsPlan[]
) {
  const productsByCode = new Map(products.map(product => [product.commodityCode, product]));
  const listedBySku = new Map<
    string,
    { product: CreditsProduct; sku: NonNullable<CreditsProduct['skuList']>[number] }
  >();
  for (const product of products) {
    if (!Array.isArray(product.skuList)) continue;
    for (const sku of product.skuList) {
      if (sku.skuCode) listedBySku.set(sku.skuCode, { product, sku });
    }
  }

  const seen = new Set<string>();
  const offers = [];

  for (const sku of skus) {
    const listed = listedBySku.get(sku.skuCode);
    const product = sku.commodityCode ? productsByCode.get(sku.commodityCode) : listed?.product;
    const listedSku = listed?.product === product ? listed?.sku : undefined;
    if (
      !product ||
      !sku.skuCode ||
      seen.has(sku.skuCode) ||
      product.sellable === false ||
      sku.sellable === false ||
      listedSku?.sellable === false ||
      !Array.isArray(sku.priceList) ||
      !sku.priceList.length
    ) continue;

    let codes = serviceCodes(sku);
    if (!codes.length && listedSku) codes = serviceCodes(listedSku);
    const matches = plans.filter(plan => plan.externalCode && codes.includes(plan.externalCode));
    if (matches.length !== 1) continue;
    seen.add(sku.skuCode);

    for (const price of sku.priceList) {
      if (price?.price == null || String(price.price).trim() === '') continue;
      const amount = Number(price.price);
      if (
        ![VasOptionType.NORMAL, VasOptionType.SUBSCRIPTION].includes(price.optionType) ||
        ![QuotaPeriodUnit.YEAR, QuotaPeriodUnit.MONTH, QuotaPeriodUnit.DAY].includes(price.periodUnit) ||
        !Number.isInteger(price.periodValue) ||
        price.periodValue <= 0 ||
        !Number.isInteger(price.optionNo) ||
        price.optionNo < 0 ||
        !Number.isFinite(amount) ||
        amount < 0
      ) continue;

      offers.push({
        key: `${sku.skuCode}:${price.optionType}:${price.optionNo}`,
        commodityCode: product.commodityCode,
        skuCode: sku.skuCode,
        plan: matches[0],
        price,
      });
    }
  }
  return offers;
}
  • 规格筛选跳过缺少 skuCode、缺少价格列表、显式不可售、重复和匹配多个服务的项。价格筛选保留真实零价,跳过空白或无效价格。
  • optionType: 0 是单次购买,optionType: 2 是订阅。同一规格的合法报价按 skuCode、optionType 和 optionNo 区分。
  • 展示周期支持年(1)、月(2)、日(3)。3.5 将 30 日展示为 1 个月,将 365 日展示为 1 年。
示例当前有效服务VAS 返回的商品展示结果
分销发布版本已选 AA、BA 的匹配报价
核销命中配置组的 A、BA、CA 的单次购买和订阅报价可各显示一项。B 缺少商品,C 缺少匹配权益

查询订阅凭证

调用 getCredentialList 查询 AGENT_RESOURCE 凭证。对设备类型的凭证,用当前设备的 devId 或 uuid 匹配 objectId。匹配后读取 effectiveStartDate、effectiveEndDate、state 和可取得的 order.orderId。凭证接口文档

import { CredentialObjectType, getCredentialList } from '@tuya-miniapp/cloud-api';

export async function readCreditCredentials(device: { devId: string; uuid?: string }) {
  const ids = [device.devId, device.uuid].filter(Boolean);
  const credentials = await getCredentialList({ catalogCode: 'AGENT_RESOURCE' });
  return credentials.filter(
    credential =>
      credential.objectType === CredentialObjectType.DEVICE && ids.includes(credential.objectId)
  );
}

处理查询结果

结果面板处理
套餐查询返回 subscriptionEnabled: false当前业务未启用,跳过商品查询。businessMode: 0 表示关闭,null 表示未配置。
已启用且 remainingCredits: "0"正常显示当前套餐和零余额。
已启用且 plans: []显示暂无有效付费套餐。
商品查询成功且 products: []显示暂无商品。
商品查询返回商品且 quotes.status: 'ready',筛选后无报价保留商品查询结果,显示暂无匹配报价。
商品查询返回商品且 quotes.status: 'error'保留商品查询结果,显示商城或 SKU 报价查询错误并提供重试。
账户、套餐或商品查询失败处理原错误并提供适当的重试入口。