/** * Youidian Payment SDK - Server Module * 用于服务端集成,包含签名、订单创建、回调解密等功能 */ /** * Order status response */ interface OrderStatus { orderId: string; status: "PENDING" | "PAID" | "CANCELLED" | "REFUNDED" | "FAILED" | "EXPIRED"; paidAt?: string; channelTransactionId?: string; } type SubscriptionAction = "NEW" | "UPGRADE" | "DOWNGRADE"; type SubscriptionIntent = "STANDARD" | "UPGRADE" | "QUEUED_UPGRADE"; type SubscriptionStatus = "PENDING" | "ACTIVE" | "EXPIRED" | "REPLACED" | "CANCELLED"; type SubscriptionAutoRefundStatus = "PROCESSING" | "SUCCEEDED" | "FAILED"; type SubscriptionErrorCode = "SUBSCRIPTION_UPGRADE_NOT_AVAILABLE" | "SUBSCRIPTION_SAME_LEVEL_NOT_ALLOWED" | "SUBSCRIPTION_DOWNGRADE_NOT_ALLOWED" | "SUBSCRIPTION_PENDING_ORDER_EXISTS" | "SUBSCRIPTION_NO_REMAINING_DAYS" | "SUBSCRIPTION_CURRENCY_MISMATCH" | "SUBSCRIPTION_PERIOD_MISMATCH" | "SUBSCRIPTION_PRICING_MANAGED"; interface SubscriptionBillingSnapshot { version: number; action: SubscriptionAction; isUpgrade: boolean; quoteBusinessDate: string; timezone: string; periodDays: number; subscriptionGroup: string; subscriptionLevel: number; productCode: string; standardAmount: number; policyDiscountAmount: number; policyId: string | null; policyCode: string | null; policyName: string | null; policyRevision: number | null; qualificationCode: string | null; intent?: SubscriptionIntent | null; fromSubscriptionId?: string | null; managedSubscription?: boolean; fromProductCode?: string | null; remainingDays?: number | null; currentFullPlanValueAmount?: number | null; currentRemainingValueAmount?: number | null; targetFullPlanValueAmount?: number | null; targetRemainingValueAmount?: number | null; appliedDiscountAmount?: number | null; finalAmount?: number | null; startsAt?: string | null; cycleStartsAt?: string | null; expiresAt?: string | null; previousSubscriptionExpiresAt?: string | null; queueMode?: "INSERT_AFTER_ACTIVE" | null; queueAdjustments?: SubscriptionQueueAdjustment[]; } interface SubscriptionQueueAdjustment { subscriptionId: string; sourceOrderId: string; startsAt: string; cycleStartsAt: string; expiresAt: string; replacesSubscriptionId: string | null; } interface BillingSnapshot { version: number; standardAmount: number; discountAmount: number; upgradeCreditAmount: number; targetRemainingValueAmount: number | null; fullPlanValueAmount: number | null; discountPolicyCode: string | null; discountPolicyRevision: number | null; qualificationCode: string | null; refundRequired: boolean; autoRefundStatus: SubscriptionAutoRefundStatus | null; subscription: SubscriptionBillingSnapshot | null; customAmount: Record | null; merchantPricing: MerchantPricingSnapshot | null; } interface SubscriptionDetails { id: string; action: SubscriptionAction; status: SubscriptionStatus; productId: string; productCode: string; priceId: string; subscriptionGroup: string; subscriptionLevel: number; startsAt: string; cycleStartsAt: string; expiresAt: string; periodDays: number; timezone: string; fullPlanValueAmount: number; currency: string; replacesSubscriptionId: string | null; activatedAt: string | null; replacedAt: string | null; cancelledAt: string | null; } declare class PaymentApiError extends Error { readonly status: number; readonly code?: string; constructor(message: string, status: number, code?: string); } /** * Order details response (full order information) */ interface OrderDetails { orderId: string; internalId: string; merchantUserId: string; productCode: string | null; status: "PENDING" | "PAID" | "CANCELLED" | "REFUNDED" | "FAILED" | "EXPIRED"; amount: number; currency: string; description?: string; paidAt?: string; createdAt: string; channel?: string; merchantPricing?: MerchantPricingSnapshot; billing: BillingSnapshot; subscription: SubscriptionDetails | null; pricingBreakdown?: PricingBreakdown; upgrade?: { isUpgrade: boolean; fromProductId?: string | null; fromProductCode?: string | null; fromPriceId?: string | null; fromOrderId?: string | null; fromSourceKind?: string | null; fromSortOrder?: number | null; toSortOrder?: number | null; originalAmount?: number | null; creditAmount?: number | null; finalPayableAmount?: number | null; remainingRatio?: number | null; newPeriodStartsAt?: string | null; newPeriodValue?: number | null; newPeriodUnit?: "days" | "months" | "years" | null; } | null; product?: { code: string; type: string; name: string; description?: string; entitlements: ProductEntitlements; metadata?: ProductMetadata | null; }; } /** * Product Entitlements */ interface ProductEntitlements { [key: string]: any; } /** * Product Price */ interface ProductPrice { id: string; currency: string; amount: number; displayAmount: string; locale: string | null; isDefault: boolean; } interface ProductSubscriptionPeriod { value: number; unit: "days" | "months" | "years"; } interface ProductResetRule { resetInterval: "day" | "month"; } interface ProductCustomAmountCurrency { minAmount: number; maxAmount: number; stepAmount?: number; unitsPerCurrencyUnit: number; unitsPerCurrencyUnitBasis?: "MINOR" | "MAJOR"; } interface ProductCustomAmount { enabled: boolean; entitlementKey: string; currencies: Record; } interface ProductInventory { enabled: boolean; totalQuantity: number; reserveTimeoutSeconds?: number; } interface ProductMetadata { subscriptionPeriod?: ProductSubscriptionPeriod; subscriptionGroup?: string; restrictSubscriptionPurchase?: boolean; expiringEntitlements?: string[]; resetEntitlements?: Record; autoAssignOnNewUser?: boolean; trialDurationDays?: number; customAmount?: ProductCustomAmount; inventory?: ProductInventory; } type ProductStockLookupMode = "auto" | "id" | "code"; interface ProductStock { productId: string; productCode: string; limited: boolean; total: number | null; reserved: number; sold: number; available: number | null; updatedAt: string; reserveTimeoutSeconds: number | null; } interface ProductStockQueryOptions { lookupBy?: ProductStockLookupMode; locale?: string; currency?: string; } interface ProductStocksQueryParams { productIds?: string[]; productCodes?: string[]; } interface PricingBreakdown { isUpgrade: boolean; originalAmount: number; creditAmount: number; finalPayableAmount: number; fromProductCode?: string | null; } interface ConsumeEntitlementPoolResult { balance: number; balances: Record; consumed: Record; consumedBuckets?: EntitlementCreditBucketConsumption[]; } interface EntitlementCreditBucket { key: string; grantId: string | null; sourceKind: string; sourceProductId: string | null; sourceOrderId: string | null; amount: number; remaining: number; expiresAt: string | null; grantedAt: string | null; metadata?: Record | null; } interface EntitlementCreditBucketConsumption { key: string; grantId: string | null; amount: number; expiresAt: string | null; sourceProductId: string | null; sourceOrderId: string | null; } interface ActiveSubscriptionInfo { subscriptionId?: string; productId: string; productCode: string; sortOrder: number; subscriptionLevel?: number; subscriptionGroup?: string | null; paidAt?: string | null; cycleStartsAt?: string; expiresAt: string; periodDays?: number; timezone?: string; priceId?: string | null; orderId?: string | null; sourceKind?: string | null; currency?: string | null; } interface DiscountPolicy { code: string; name: string; description: string | null; qualificationCode: string; balancePackThresholdAmount: number | null; productId: string; productCode: string; priceId: string; currency: string; standardAmount: number; discountAmount: number; startsAt: string | null; endsAt: string | null; } interface UserProductDiscountEligibility { userId: string; productId: string; productCode: string; eligible: boolean; coupons: Array<{ coupon: DiscountPolicy; eligible: boolean; grantedAt: string | null; }>; } /** * Product Data */ interface Product { id: string; code: string; type: string; name: string; description?: string; entitlements: ProductEntitlements; prices: ProductPrice[]; subscriptionGroup?: string | null; subscriptionLevel?: number | null; subscriptionPeriodDays?: number | null; subscriptionTimezone?: string | null; metadata?: ProductMetadata | null; discountEligibility?: ProductDiscountEligibility; } interface ProductDiscountEligibility { eligible: boolean; coupons: Array<{ code: string; name: string; currency: string; standardAmount: number; discountAmount: number; discountedAmount: number; grantedAt: string | null; }>; } interface CustomAmountRechargeRule extends ProductCustomAmountCurrency { productId: string; productCode: string; entitlementKey: string; currency: string; configuredMinAmount: number; minimumGrantAmount: number; } type CustomAmountRechargeValidationResult = { valid: true; rule: CustomAmountRechargeRule; } | { valid: false; code: "CUSTOM_AMOUNT_UNAVAILABLE" | "CUSTOM_AMOUNT_INVALID_AMOUNT" | "CUSTOM_AMOUNT_OUT_OF_RANGE" | "CUSTOM_AMOUNT_INVALID_STEP"; error: string; rule?: CustomAmountRechargeRule; }; /** * Resolve the custom amount recharge rule for a product and currency. * * Amounts are in the smallest currency unit. `unitsPerCurrencyUnit` defaults * to the smallest currency unit. When `unitsPerCurrencyUnitBasis` is `MAJOR`, * fractional entitlement amounts are rounded to the nearest whole unit. The * returned `minAmount` is the effective lower bound that both satisfies product * metadata and grants at least one entitlement unit. `configuredMinAmount` * keeps the raw product metadata value for display or diagnostics. */ declare function getCustomAmountRechargeRule(product: Product | null | undefined, currency: string): CustomAmountRechargeRule | null; /** * Validate a custom recharge amount before calling `PaymentUI.openPayment`. * This is an SDK-side guardrail for integrator-owned amount inputs; the worker * still performs authoritative server-side validation when creating the order. */ declare function validateCustomAmountRecharge(product: Product | null | undefined, customAmount: { amount: number; currency: string; }): CustomAmountRechargeValidationResult; /** * WeChat JSAPI Payment Parameters (for wx.requestPayment) */ interface WechatJsapiPayParams { appId: string; timeStamp: string; nonceStr: string; package: string; signType: "RSA"; paySign: string; } /** * Verified hosted login token payload. */ interface VerifiedLoginToken { appId: string; userId: string; legacyCasdoorId?: string | null; channel: string; email?: string | null; emailVerified?: boolean | null; name?: string | null; username?: string | null; avatar?: string | null; phoneCountryCode?: string | null; phoneNumber?: string | null; phoneE164?: string | null; phoneVerifiedAt?: string | null; wechatOpenId?: string | null; wechatUnionId?: string | null; expiresAt: string; } interface SendPhoneVerificationCodeParams { userId: string; phoneCountryCode?: string; countryCode?: string; phoneNumber: string; } interface SendPhoneVerificationCodeResponse { phoneCountryCode?: string | null; phoneNumber?: string | null; phoneE164: string; expiresAt: string; cooldownSeconds?: number; resendAfterSeconds?: number; } interface PhoneBinding { userId: string; phoneCountryCode?: string | null; phoneNumber?: string | null; phoneE164?: string | null; phoneVerifiedAt?: string | null; bound: boolean; } interface GetPhoneBindingParams { userId: string; } interface BindPhoneNumberParams { userId: string; phoneCountryCode?: string; countryCode?: string; phoneNumber: string; code: string; } type UpdatePhoneNumberParams = BindPhoneNumberParams; interface BindPhoneNumberResponse { user: { userId: string; phoneCountryCode?: string | null; phoneNumber?: string | null; phoneE164?: string | null; phoneVerifiedAt?: string | null; }; merged: boolean; mergeSummary?: Record; } type UpdatePhoneNumberResponse = BindPhoneNumberResponse; interface CreateWechatMessageBindingParams { /** Hosted login external user ID returned by Youidian login. */ userId?: string; loginExternalUserId?: string; /** Integrator-owned user ID when hosted login is not used. */ merchantUserId?: string; /** Optional linked template ID or code to infer the WeChat channel. */ templateId?: string; templateCode?: string; /** Optional direct channel ID when no template is selected yet. */ channelId?: string; /** Optional locale for the hosted binding page. */ locale?: string; /** Optional URL to return to after binding succeeds. */ returnUrl?: string; } interface CreateWechatMessageBindingResponse { ticketId: string; status: "PENDING" | "BOUND" | "EXPIRED" | "FAILED"; bindingUrl: string; qrCodeUrl?: string | null; expiresAt: string; } type MessageTemplateDataValue = string | number | boolean | { value: string | number | boolean; color?: string; }; interface SendMessageParams { templateId?: string; templateCode?: string; userId?: string; loginExternalUserId?: string; merchantUserId?: string; /** Direct SMS recipient phone number. When provided for SMS templates, binding is not required before sending. */ phoneNumber?: string; /** Country/region code for phoneNumber. Defaults to +86 on the gateway. */ phoneCountryCode?: string; /** Alias for phoneCountryCode. */ countryCode?: string; /** Direct E.164 SMS recipient. Alternative to phoneNumber. */ phoneE164?: string; data: Record | MessageTemplateDataValue[]; url?: string; redirectUrl?: string; miniProgram?: { appid: string; pagepath?: string; }; idempotencyKey?: string; } interface SendMessageResponse { logId: string; status: "PENDING" | "SENT" | "FAILED" | "SKIPPED"; providerMessageId?: string | null; errorCode?: string | null; errorMessage?: string | null; bindRequired?: boolean; idempotent?: boolean; phoneBinding?: { bound: boolean; userId?: string; phoneE164?: string | null; merged?: boolean; alreadyBound?: boolean; error?: string; } | null; } /** * SDK Client Options */ interface PaymentClientOptions { /** Application ID (Required) */ appId: string; /** Application Secret (Required for server-side operations) */ appSecret: string; /** * @deprecated Use apiUrl and checkoutUrl instead * API Base URL (e.g. https://pay.youidian.com) * If apiUrl or checkoutUrl is not provided, this will be used as fallback * Default: https://pay.imgto.link */ baseUrl?: string; /** * API server URL for backend requests (e.g. https://api.youidian.com) * Default: https://pay-api.imgto.link */ apiUrl?: string; /** * Checkout page URL for client-side payment (e.g. https://pay.youidian.com) * Default: https://pay.imgto.link */ checkoutUrl?: string; } interface MerchantPricingBreakdownItem { type: "coupon" | "promotion" | "membership" | "manual" | "other"; amount: number; label?: string; code?: string; } interface MerchantPricing { amount: number; currency: string; originalAmount?: number; discountAmount?: number; discountReason?: string; discountCode?: string; breakdown?: MerchantPricingBreakdownItem[]; } interface MerchantPricingSnapshot extends MerchantPricing { originalAmount: number; discountAmount: number; priceId: string; productId: string; productCode: string; } /** * Create Order Parameters */ interface CreateOrderParams { productId?: string; priceId?: string; channel?: string; userId: string; returnUrl?: string; /** Public server endpoint used for both payment and refund webhooks. */ callbackUrl?: string; metadata?: Record; merchantOrderId?: string; openid?: string; locale?: string; subscriptionIntent?: SubscriptionIntent; customAmount?: { amount: number; currency: string; }; merchantPricing?: MerchantPricing; } type CreateBankTransferOrderParams = Omit; /** * Create WeChat Mini Program Order Parameters */ type CreateMiniProgramOrderParams = { userId: string; openid: string; merchantOrderId?: string; priceId: string; subscriptionIntent?: SubscriptionIntent; }; /** * Create Order Response */ interface CreateOrderResponse { orderId: string; internalId: string; amount: number; currency: string; payParams: any; pricingBreakdown?: PricingBreakdown; status?: "PENDING" | "PAID" | "CANCELLED" | "REFUNDED" | "FAILED" | "EXPIRED"; paidAt?: string | null; channel?: string; isSandbox?: boolean; merchantPricing?: MerchantPricingSnapshot; billing?: BillingSnapshot; subscription?: SubscriptionDetails | null; } interface CancelOrderResponse { cancelled: boolean; status: "PENDING" | "PAID" | "CANCELLED" | "REFUNDED" | "FAILED" | "EXPIRED"; orderId: string; internalId?: string | null; } interface RefundOrderParams { /** Refund amount in the currency's smallest unit. Omit for the full remainder. */ amount?: number; /** A unique key for this refund attempt. */ idempotencyKey: string; /** Send an ORDER_REFUNDED webhook after the refund is recorded. */ notifyIntegrator?: boolean; /** Revoke entitlements granted by this order after a full refund. */ revokeEntitlements?: boolean; } interface RefundOrderResponse { orderId: string; internalId: string; status: "PAID" | "REFUNDED" | "PROCESSING"; refundAmount: number; refundId: string; notifyIntegrator: boolean; revokeEntitlements: boolean; idempotentReplay: boolean; } interface CompleteFreeOrderResponse { completed: boolean; status: "paid" | "pending" | "cancelled" | "refunded" | "failed" | "unknown"; orderId: string; internalId?: string | null; } /** * Payment Callback Notification */ interface PaymentNotification { iv: string; encryptedData: string; authTag: string; } /** * Decrypted Payment Callback Data */ interface PaymentCallbackData { orderId: string; merchantOrderId?: string; status: "PAID" | "CANCELLED" | "REFUNDED" | "FAILED"; amount: number; currency: string; paidAt: string; channelTransactionId?: string; metadata?: Record; } /** * Platform webhook payload. * * The platform delivers this object as plaintext JSON in the webhook request * body, signed with `X-UniPay-Signature` / `X-UniPay-Timestamp` headers. * Validate with {@link PaymentClient.verifyWebhookSignature} using the raw * body string before parsing. */ interface WebhookPayload { event: "ORDER_PAID" | "ORDER_CANCELLED" | "ORDER_REFUNDED" | "ORDER_FAILED"; orderId: string; merchantOrderId: string; merchantUserId: string; productCode: string; billing: BillingSnapshot; subscription: SubscriptionDetails | null; amount: number; currency: string; paidAt: string | null; channelTransactionId?: string; cancelSubscription?: boolean; revokeEntitlements?: boolean; } /** * Get Orders Parameters */ interface GetOrdersParams { page?: number; pageSize?: number; userId?: string; status?: "PENDING" | "PAID" | "CANCELLED" | "REFUNDED" | "FAILED" | "EXPIRED"; startDate?: string; endDate?: string; } /** * Order List Item */ interface OrderListItem { orderId: string; internalId: string; merchantUserId: string; status: "PENDING" | "PAID" | "CANCELLED" | "REFUNDED" | "FAILED" | "EXPIRED"; amount: number; currency: string; channel?: string; paidAt?: string; createdAt: string; } /** * Get Orders Response */ interface GetOrdersResponse { orders: OrderListItem[]; pagination: { total: number; page: number; pageSize: number; totalPages: number; }; } /** * Entitlement Detail Item */ interface EntitlementDetailItem { type: string; current: number | boolean; limit?: number; expiresAt?: string | null; resetInterval?: string | null; nextResetAt?: string | null; sourceKind?: string | null; } /** * Entitlement Detail - returned by getEntitlementsDetail */ type EntitlementDetail = Record; /** * Ensure User With Trial Response */ interface EnsureUserWithTrialResponse { isNew: boolean; trialAssigned: boolean; trialProductCode?: string; entitlements: EntitlementDetail; } /** * Server-side Payment Client * 服务端支付客户端,用于创建订单、查询状态、解密回调 */ declare class PaymentClient { private readonly appId; private readonly appSecret; private readonly apiUrl; private readonly checkoutUrl; constructor(options: PaymentClientOptions); /** * Generate SHA256 signature for the request * Logic: SHA256(appId + appSecret + timestamp) */ private generateSignature; /** * Internal request helper for Gateway API */ private request; /** * Decrypts the callback notification payload using AES-256-GCM. * * @deprecated This legacy encrypted-envelope protocol is NOT what the platform * actually delivers. The platform sends an HMAC-signed plaintext JSON webhook * with `X-UniPay-Signature` / `X-UniPay-Timestamp` headers; use * {@link PaymentClient.verifyWebhookSignature} to validate those instead. * * @param notification - The encrypted notification from payment webhook * @returns Decrypted payment callback data */ decryptCallback(notification: PaymentNotification): PaymentCallbackData; /** * Verify an inbound platform webhook signature. * * The platform delivers webhooks as plaintext JSON with two headers: * `X-UniPay-Signature` (HMAC-SHA256 of `${timestamp}.${rawBodyString}`) and * `X-UniPay-Timestamp`. The body itself is NOT encrypted; verify the signature * then `JSON.parse` the body to obtain a {@link WebhookPayload}. * * @param rawBody - The raw request body string (exactly as received) * @param signature - The `X-UniPay-Signature` header value (hex) * @param timestamp - The `X-UniPay-Timestamp` header value (ms epoch string) * @param options - Optional `toleranceMs` for timestamp freshness (default 5 min) * @returns `true` if the signature is valid and the timestamp is fresh */ verifyWebhookSignature(rawBody: string, signature: string, timestamp: string, options?: { toleranceMs?: number; }): boolean; /** * Fetch products for the configured app. */ getProducts(options?: { locale?: string; currency?: string; userId?: string; }): Promise; /** Fetch all currently active discount policies for the configured app. */ getDiscountPolicies(): Promise; /** Fetch currently active discount policies for one product. */ getProductDiscountPolicies(productIdOrCode: string): Promise; /** Query one user's discount eligibility for one product. */ getUserProductDiscountEligibility(userId: string, productIdOrCode: string): Promise; /** * Fetch the realtime stock snapshot for a single product. */ getProductStock(productIdOrCode: string, options?: ProductStockQueryOptions): Promise; /** * Fetch realtime stock snapshots for multiple products. */ getProductStocks(params: ProductStocksQueryParams, options?: ProductStockQueryOptions): Promise; getProductStocks(params: ProductStocksQueryParams & ProductStockQueryOptions): Promise; /** * Create a new order * @param params - Order creation parameters * @returns Order details with payment parameters */ createOrder(params: CreateOrderParams): Promise; /** * Create a paid manual bank transfer order. * @param params - Order creation parameters without channel * @returns Paid order details */ createBankTransferOrder(params: CreateBankTransferOrderParams): Promise; /** * Create a WeChat Mini Program order (channel fixed to WECHAT_MINI) * @param params - Mini program order parameters * @returns Order details with payment parameters */ createMiniProgramOrder(params: CreateMiniProgramOrderParams): Promise; /** * Pay for an existing order * @param orderId - The order ID to pay * @param params - Payment parameters including channel */ payOrder(orderId: string, params: { channel: string; returnUrl?: string; openid?: string; [key: string]: any; }): Promise; /** * Cancel a pending order and release its inventory reservation. * Paid/refunded/failed orders are returned unchanged by the gateway. */ cancelOrder(orderId: string, params?: { reason?: string; }): Promise; /** * Refund a paid order owned by this app. * * Orders carrying subscriptions or entitlements require a full refund and * entitlement revocation. Reuse the same idempotency key when retrying. */ refundOrder(orderId: string, params: RefundOrderParams): Promise; /** * Complete a zero-amount FREE order. * This marks the pending order as paid and triggers normal paid-order side effects. */ completeFreeOrder(orderId: string): Promise; /** * Query order status * @param orderId - The order ID to query */ getOrderStatus(orderId: string): Promise; /** * Get order details (full order information) * @param orderId - The order ID to query */ getOrderDetails(orderId: string): Promise; /** * Get orders list with pagination * @param params - Query parameters (pagination, filters) * @returns Orders list and pagination info */ getOrders(params?: GetOrdersParams): Promise; /** * Get user entitlements in the legacy flat shape. * @param userId - User ID */ getEntitlements(userId: string): Promise>; /** * Get user entitlements with full details (type, expiry, reset config, source) * @param userId - User ID */ getEntitlementsDetail(userId: string): Promise; getActiveSubscription(userId: string): Promise; getSubscriptionUpgradeOptions(userId: string, options?: { locale?: string; currency?: string; subscriptionIntent?: Extract; }): Promise; /** * Ensure user exists and auto-assign trial product if new user * This should be called when user first logs in or registers * @param userId - User ID */ ensureUserWithTrial(userId: string): Promise; /** * Get a single entitlement value * @param userId - User ID * @param key - Entitlement key */ getEntitlementValue(userId: string, key: string): Promise; /** * Consume numeric entitlement * @param userId - User ID * @param key - Entitlement key * @param amount - Amount to consume */ consumeEntitlement(userId: string, key: string, amount: number, options?: { idempotencyKey?: string; metadata?: Record; }): Promise<{ balance: number; }>; /** * Consume numeric entitlements from an ordered key pool. * Useful when subscription credits and perpetual credits use separate keys. */ consumeEntitlementPool(userId: string, keys: string[], amount: number, options?: { idempotencyKey?: string; metadata?: Record; }): Promise; /** * Get active numeric entitlement buckets ordered by expiration. */ getEntitlementCreditBuckets(userId: string, keys?: string[]): Promise; /** * Add numeric entitlement (e.g. refund) * @param userId - User ID * @param key - Entitlement key * @param amount - Amount to add */ addEntitlement(userId: string, key: string, amount: number): Promise<{ balance: number; }>; /** * Toggle boolean entitlement * @param userId - User ID * @param key - Entitlement key * @param enabled - Whether to enable */ toggleEntitlement(userId: string, key: string, enabled: boolean): Promise<{ isEnabled: boolean; }>; /** * Generate checkout URL for client-side payment * @param productId - Product ID * @param priceId - Price ID * @returns Checkout page URL */ getCheckoutUrl(productId: string, priceId: string): string; /** * Verify a hosted login token and return the normalized login profile. * This request is signed with your app credentials and routed through the worker API. */ verifyLoginToken(token: string): Promise; /** * Send a phone verification code for binding a phone number to a hosted login user. */ sendPhoneVerificationCode(params: SendPhoneVerificationCodeParams): Promise; /** * Query the verified phone binding for a hosted login user. */ getPhoneBinding(params: GetPhoneBindingParams): Promise; /** * Bind a verified phone number to a hosted login user, merging existing accounts when needed. */ bindPhoneNumber(params: BindPhoneNumberParams): Promise; /** * Update a hosted login user's phone number after verifying the new number by SMS code. */ updatePhoneNumber(params: UpdatePhoneNumberParams): Promise; /** * Create a hosted WeChat official account binding URL for a user. */ createWechatMessageBinding(params: CreateWechatMessageBindingParams): Promise; /** * Send an app-linked message template to a bound recipient. */ sendMessage(params: SendMessageParams): Promise; } export { type ActiveSubscriptionInfo, type BillingSnapshot, type BindPhoneNumberParams, type BindPhoneNumberResponse, type CancelOrderResponse, type CompleteFreeOrderResponse, type ConsumeEntitlementPoolResult, type CreateBankTransferOrderParams, type CreateMiniProgramOrderParams, type CreateOrderParams, type CreateOrderResponse, type CreateWechatMessageBindingParams, type CreateWechatMessageBindingResponse, type CustomAmountRechargeRule, type CustomAmountRechargeValidationResult, type DiscountPolicy, type EnsureUserWithTrialResponse, type EntitlementCreditBucket, type EntitlementCreditBucketConsumption, type EntitlementDetail, type EntitlementDetailItem, type GetOrdersParams, type GetOrdersResponse, type GetPhoneBindingParams, type MerchantPricing, type MerchantPricingBreakdownItem, type MerchantPricingSnapshot, type MessageTemplateDataValue, type OrderDetails, type OrderListItem, type OrderStatus, PaymentApiError, type PaymentCallbackData, PaymentClient, type PaymentClientOptions, type PaymentNotification, type PhoneBinding, type PricingBreakdown, type Product, type ProductCustomAmount, type ProductCustomAmountCurrency, type ProductDiscountEligibility, type ProductEntitlements, type ProductInventory, type ProductMetadata, type ProductPrice, type ProductResetRule, type ProductStock, type ProductStockLookupMode, type ProductStockQueryOptions, type ProductStocksQueryParams, type ProductSubscriptionPeriod, type RefundOrderParams, type RefundOrderResponse, type SendMessageParams, type SendMessageResponse, type SendPhoneVerificationCodeParams, type SendPhoneVerificationCodeResponse, type SubscriptionAction, type SubscriptionAutoRefundStatus, type SubscriptionBillingSnapshot, type SubscriptionDetails, type SubscriptionErrorCode, type SubscriptionIntent, type SubscriptionQueueAdjustment, type SubscriptionStatus, type UpdatePhoneNumberParams, type UpdatePhoneNumberResponse, type UserProductDiscountEligibility, type VerifiedLoginToken, type WebhookPayload, type WechatJsapiPayParams, getCustomAmountRechargeRule, validateCustomAmountRecharge };