Credits and VAS integration
The panel can display the active plan, available Credits, and remaining resets. For the product section, query VAS products for the current device's eligible plans and display the matching offers.
Prepare for integration
Use a version of @tuya-miniapp/cloud-api that includes the Credits methods you need. See each API reference for its minimum version. The user must be signed in and have access to the current device. In the miniapp's Development Settings, authorize MiniApp Agent Development Capability for querying the account and plans and using resets. Authorize Mall & Value-Added Services to query products, SKU offers, and subscription credentials. Miniapp Developer Platform
Query the current account and available plans
Use the same device devId to query the current account and the available plans.
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 is the active plan for the device. An active paid plan can have isSubscribed: true. When the current purchase SKU is available, the account provides its skuCode.
account.remainingCredits is a decimal string. Use the string to display the exact balance. An enabled account with no remaining Credits returns "0". reset.remaining is the number of resets available to the device.
available.freePlan is the free plan applicable to the device. available.plans lists the eligible paid services in server order. To look up the benefits for a service code, use available.plans.find(plan => plan.externalCode === serviceCode).
Use a Credits reset
Enable the reset button when account.subscriptionEnabled is true, account.plan.capacityCredits > 0, and account.reset.remaining > 0. After the user confirms, call resetPanelAgentCredits({ devId }) and keep the button disabled until the request and account refresh finish. API reference and example
true means one reset was used and the balance was restored to the current plan limit. A successful call also uses a reset when the balance is already full.
false means the call used no resets.
Call getPanelAgentCreditsAccount({ devId }) after the request to refresh the balance and remaining resets. If the request times out or the connection drops, refresh the account before the user decides whether to retry.
Query products by business mode
Query products when the plans response has subscriptionEnabled: true. Use available.businessMode to choose the binding. Redemption uses the device PID. Distribution uses the public app ID configured for the current region. Call getVasSpuList for product codes, then call getMallInfoV2 for the mall, shop, site, and currency. Pass that context and the commodityCodes to getSkuListV2 to get SKUs and offers for the current mall.
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 contains the product query results, which can include SKU metadata for matching. quotes contains the SKU and offer query results. An empty product list skips the mall and SKU queries. If a mall or SKU query fails, quotes.error preserves the error alongside the returned products.
Filter displayable SKUs and offers
Match the externalCode of each SKU V2 main capability or sub-capability against available.plans. Keep SKUs associated with the products returned by the product query. SKU metadata attached to a product can supplement the match for the same SKU. When quotes.status is ready, pass products, quotes.skus, and available.plans to the following function to find matching VAS offers.
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;
}
- SKU filtering skips entries with a missing
skuCode or price list, explicit unavailability, duplicate SKU codes, or multiple service matches. Valid zero prices are retained. Blank and invalid prices are skipped.
optionType: 0 is a one-time purchase. optionType: 2 is a subscription. Identify eligible offers for the same SKU by skuCode, optionType, and optionNo.
- The supported display periods are year (
1), month (2), and day (3). Version 3.5 displays 30 days as one month and 365 days as one year.
Query subscription credentials
Call getCredentialList to query AGENT_RESOURCE credentials. For device credentials, match objectId to the current device's devId or uuid. Read effectiveStartDate, effectiveEndDate, state, and order.orderId when available. Credential API reference
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)
);
}
Handle query results