import {z} from 'zod' export type CurrencyCode = string; export type Money = {currency_code: CurrencyCode, value: string}; export type PricingTier = {starting_quantity: string, ending_quantity?: string | undefined, amount: Money}; export type PricingTierList = Array; export type DateTime = unknown; export type PricingScheme = {version?: number | undefined, fixed_price?: Money | undefined, pricing_model?: ('VOLUME' | 'TIERED') | undefined, tiers?: PricingTierList | undefined, create_time?: DateTime | undefined, update_time?: DateTime | undefined}; export type Frequency = {interval_unit: 'DAY' | 'WEEK' | 'MONTH' | 'YEAR', interval_count?: number | undefined}; export type BillingCycle = {pricing_scheme?: PricingScheme | undefined, frequency: Frequency, tenure_type: 'REGULAR' | 'TRIAL', sequence: number, total_cycles?: number | undefined}; export type BillingCycleList = Array; export type PaymentPreferences = {auto_bill_outstanding?: boolean | undefined, setup_fee?: Money | undefined, setup_fee_failure_action?: ('CONTINUE' | 'CANCEL') | undefined, payment_failure_threshold?: number | undefined}; export type MerchantPreferences = {return_url?: string | undefined, cancel_url?: string | undefined}; export type Percentage = unknown; export type Taxes = {percentage: Percentage, inclusive?: boolean | undefined}; export type PlanRequestPOST = {product_id: string, name: string, status?: ('CREATED' | 'INACTIVE' | 'ACTIVE') | undefined, description?: string | undefined, billing_cycles: BillingCycleList, payment_preferences: PaymentPreferences, merchant_preferences?: MerchantPreferences | undefined, taxes?: Taxes | undefined, quantity_supported?: boolean | undefined}; export type CreateApiV1BillingPlansArgs = {'Content-Type': string, Prefer?: string | undefined, 'PayPal-Request-Id'?: string | undefined, body: PlanRequestPOST}; export type CreateApiV1BillingPlansOptions = {baseUrl?: string | undefined, Oauth2?: string | undefined, fetch?: typeof fetch | undefined}; export const currencyCode = z.string().min(3).max(3); export const money = z.object({currency_code: currencyCode, value: z.string().max(32)}); export const pricingTier = z.object({starting_quantity: z.string().min(1).max(32), ending_quantity: z.string().min(1).max(32).optional(), amount: money}); export const pricingTierList = z.array(pricingTier); export const dateTime = z.string().min(20).max(64); export const pricingScheme = z.object({version: z.number().int().gte(0).lte(999).optional(), fixed_price: money.optional(), pricing_model: z.union([z.literal("VOLUME").min(1).max(24), z.literal("TIERED").min(1).max(24)]).optional(), tiers: pricingTierList.optional(), create_time: dateTime.optional(), update_time: dateTime.optional()}); export const frequency = z.object({interval_unit: z.union([z.literal("DAY").min(1).max(24), z.literal("WEEK").min(1).max(24), z.literal("MONTH").min(1).max(24), z.literal("YEAR").min(1).max(24)]), interval_count: z.number().int().gte(1).lte(365).optional()}); export const billingCycle = z.object({pricing_scheme: pricingScheme.optional(), frequency: frequency, tenure_type: z.union([z.literal("REGULAR").min(1).max(24), z.literal("TRIAL").min(1).max(24)]), sequence: z.number().int().gte(1).lte(99), total_cycles: z.number().int().gte(0).lte(999).optional()}); export const billingCycleList = z.array(billingCycle); export const paymentPreferences = z.object({auto_bill_outstanding: z.boolean().optional(), setup_fee: money.optional(), setup_fee_failure_action: z.union([z.literal("CONTINUE").min(1).max(24), z.literal("CANCEL").min(1).max(24)]).optional(), payment_failure_threshold: z.number().int().gte(0).lte(999).optional()}); export const merchantPreferences = z.object({return_url: z.string().min(10).max(4000).optional(), cancel_url: z.string().min(10).max(4000).optional()}); export const percentage = z.string(); export const taxes = z.object({percentage: percentage, inclusive: z.boolean().optional()}); export const linkDescription = z.object({href: z.string(), rel: z.string(), method: z.enum(["GET", "POST", "PUT", "DELETE", "HEAD", "CONNECT", "OPTIONS", "PATCH"]).optional()}); export const linkDescriptionList = z.array(linkDescription); export const plan = z.object({id: z.string().min(26).max(26).optional(), product_id: z.string().min(22).max(22).optional(), name: z.string().min(1).max(127).optional(), status: z.union([z.literal("CREATED").min(1).max(24), z.literal("INACTIVE").min(1).max(24), z.literal("ACTIVE").min(1).max(24)]).optional(), description: z.string().min(1).max(127).optional(), billing_cycles: billingCycleList.optional(), payment_preferences: paymentPreferences.optional(), merchant_preferences: merchantPreferences.optional(), taxes: taxes.optional(), quantity_supported: z.boolean().optional(), create_time: dateTime.optional(), update_time: dateTime.optional(), links: linkDescriptionList.optional()}); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Create plan * * POST /v1/billing/plans */ export const createApiV1BillingPlans = async (args: CreateApiV1BillingPlansArgs, options?: CreateApiV1BillingPlansOptions) => { const {baseUrl = "https://api-m.sandbox.paypal.com", fetch: fetchFn = fetch, Oauth2} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args['Content-Type'] != null) headers.set("Content-Type", String(args['Content-Type'])) if (args.Prefer != null) headers.set("Prefer", String(args.Prefer)) if (args['PayPal-Request-Id'] != null) headers.set("PayPal-Request-Id", String(args['PayPal-Request-Id'])) if (Oauth2 !== undefined) headers.set('authorization', `Bearer ${Oauth2}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/billing/plans${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(plan, await res.json()) };