SazitoSazito SDKv1.4.0
API Reference

Payments

Checkout payment APIs for gateway selection, payment creation, verification steps, and final order action.

Module role in sales flow

payments is the final checkout module before order completion.

  • Depends on invoice credentials (invoices.create must run first).
  • Supports redirect/post gateways and manual step-based flows like card-to-card upload/code verification.
  • When payment reaches show_order, SDK runs checkout finalization automatically.

Usage notes

  • Create an invoice before loading payment methods.
  • Gateway-return verification requires the positive payment ID from the callback URL.
  • Use processStep() for JSON payloads and processStepForm() for form payloads.
  • Action values are case-sensitive; use the exported PaymentAction type.

Methods

Get Methods

Use: payments.getMethods(options?).

Returns available payment methods for current invoice credentials.

const methodsRes = await client.payments.getMethods();

Create

Use: payments.create(paymentTypeId, options?).

ParameterTypeRequiredDescription
paymentTypeIdnumberRequiredPayment method ID (PaymentMethod.id).
optionsRequestOptionsOptionalPer-request controls.

Returns: SazitoResponse<Payment>.

const methodsRes = await client.payments.getMethods();
if (methodsRes.data?.length) {
  await client.payments.create(methodsRes.data[0].id);
}

Initialize

Use: payments.initialize(options?).

Initializes current payment and returns next action.

Returns: SazitoResponse<PaymentAction>.

When payment verification succeeds (action === 'show_order'), the SDK automatically finalizes the checkout and clears the completed cart, invoice, shipping-address, payment, and discount credentials from browser storage.

const actionRes = await client.payments.initialize();

if (actionRes.data?.action === 'REDIRECT') {
  console.log('Redirect to:', actionRes.data.address);
}

Process Step

Use: payments.processStep(input, options?).

Use this for JSON-mode step requests (commonly cardtocardpayment) after create/initialize.

FieldTypeRequiredDescription
input.paymentIdentifierstringOptionalWith input.id, restores callback payment credentials; otherwise overrides the stored identifier.
input.idnumberOptionalWith input.paymentIdentifier, restores callback payment credentials.
input.payloadRecord<string, any>OptionalGateway-specific JSON payload.
input.tatokenstringOptionalGateway/session token.
input.trackingDataRecord<string, any>OptionalTracking payload.
input.isFailedstringOptionalMark payment failed ("true").
input.imageUrlstringOptionalUploaded payment proof URL.
input.codestringOptionalVerification code (e.g., card-to-card).
optionsRequestOptionsOptionalPer-request controls.
const cardToCardStep = await client.payments.processStep({
  imageUrl: 'https://cdn.example.com/payment-proof.png',
  code: '894512',
});

Verify

Use: payments.verify(input?, options?).

Verifies a returning gateway payment. Provide the callback payment ID and identifier to restore payment credentials when browser storage is empty:

const result = await client.payments.verify({
  id: 304,
  paymentIdentifier: '6f8a717eb211f0839e522a5358932968',
});

If id and paymentIdentifier are omitted, verify uses the payment created earlier on the same SDK client and checks its status once.

For server adapters that receive GET and POST callback data separately, use verifyPaymentCallback. Body fields are copied first and query fields second, so query values win when a field appears in both places:

const result = await client.payments.verifyPaymentCallback({
  paymentId: 304,
  paymentIdentifier: '6f8a717eb211f0839e522a5358932968',
  body: requestBody,
  query: searchParams,
});

Use getPaymentStep() to check payment status once.

Process Step (Form Mode)

Use: payments.processStepForm(input, options?).

Use this when the gateway flow requires form data.

This callback branch requires the positive payment ID from the gateway-return URL; the temporary initialization ID 0 is rejected.

FieldTypeRequiredDescription
inputFormData | Record<string, string | number | boolean | null | undefined>RequiredForm fields sent with non-JSON content type.
optionsRequestOptionsOptionalPer-request controls.
const stepRes = await client.payments.processStepForm({
  code: '894512',
  imageUrl: 'https://cdn.example.com/payment-proof.png',
});

Poll Until Settled

Use: payments.pollUntilSettled(options?, intervalMs?).

Polls payment state via JSON every 15 seconds by default until action !== 'pending'. It supports AbortSignal, maxAttempts, an immediate first request, and a five-minute default polling deadline.

const finalAction = await client.payments.pollUntilSettled({
  intervalMs: 5000,
  pollingTimeoutMs: 120000,
  signal: controller.signal,
});

Clear Payment

Use: payments.clearPayment().

Clears persisted payment credentials.

client.payments.clearPayment();

Response key fields

Payment Method

FieldTypeRequiredDescription
idnumberRequiredPayment method ID.
codePaymentGatewayRequiredGateway code enum.
titlestringRequiredDisplay title (English).
titleFastringRequiredDisplay title (Persian).
descriptionstring | nullRequiredMethod description; often null.
paymentSubTypenumber | nullRequiredPayment sub-type id; null when absent.
ordernumberRequiredDisplay order.
isDefaultbooleanRequiredDefault method flag.

Payment Action

FieldTypeRequiredDescription
action'POST' | 'REDIRECT' | 'UPLOAD' | 'show_otp_modal' | 'show_order' | 'pending' | 'payment_fail_error' | 'show_error' | 'FAIL' | 'StockViolated'RequiredExact, case-sensitive next action type returned by the API.
addressstringOptionalRedirect/post URL.
payloadRecord<string, string | number>OptionalHidden form fields for POST.
orderCheckoutOrderOptionalRequired for pending; optional for show_order. Fields are camelCased by the SDK.
timenumberOptionalUpload or OTP window in minutes.
messagestringOptionalError/action message.
rawJsonObjectOptionalOriginal result for unrecognized actions.

For pending, call pollUntilSettled() (15 seconds by default). Polling stops when the action changes to show_order or a failure/unknown action, when it is cancelled, or when its configured limit is reached.

CheckoutOrder describes the final checkout order, independently of the account Order returned by orders.get() and orders.list(). Its invoice can omit netTotal and finalTotal in verification responses. Items use variantAttributes, singleItemPrice, noOfItems, totalItemsPrice, and nested productVariant data. IDs retain their string or number values. No invoice-item ID or original price is invented when the payment response does not provide one.

variantAttributes uses the shared ProductAttribute shape. Its value may be a string or a ProductAttributeValueObject; for color attributes, fieldType: 'color' identifies the field and value.extra contains the hex value used for a swatch.

Known errors

TypeWhen it happens
validationMissing invoice/payment credentials.

Examples

// app/lib/sazito-client.ts
import { createSazitoClient } from '@sazito/client-sdk';

export const sazito = createSazitoClient({
  domain: process.env.NEXT_PUBLIC_SAZITO_DOMAIN!,
});
// app/[lang]/(home)/page.tsx
'use client';
import { useEffect, useState } from 'react';
import { sazito } from '@/app/lib/sazito-client';

export default function Example() {
  const [data, setData] = useState<any>(null);

  useEffect(() => {
    (async () => {
      await sazito.cart.addItem(12001, 1);
      await sazito.invoices.create();
      const methods = await sazito.payments.getMethods();

      if (!methods.data?.length) {
        setData({ message: 'No payment methods available' });
        return;
      }

      await sazito.payments.create(methods.data[0].id);
      const action = await sazito.payments.initialize();
      setData(action.data ?? null);
    })();
  }, []);

  return <pre>{JSON.stringify(data, null, 2)}</pre>;
}

Type Details

The following tables are generated from SDK TypeScript types and include nested object fields.

PaymentMethod

Source: src/types/payment.ts

FieldTypeRequired
idnumberRequired
codePaymentGatewayRequired
titlestringRequired
titleFastringRequired
descriptionstring | nullRequired
paymentSubTypenumber | nullRequired
ordernumberRequired
isDefaultbooleanRequired

Payment

Source: src/types/payment.ts

FieldTypeRequired
idnumberRequired
identifierstringRequired
paymentType{ id?: number; code: PaymentGateway; }Required
paymentType.idnumberOptional
paymentType.codePaymentGatewayRequired
amountnumberRequired

PaymentAction

Source: src/types/payment.ts

Type: PaymentActionBase & ( \| { action: 'POST'; address: string; payload: Record<string, string \| number> } \| { action: 'REDIRECT'; address: string } \| { action: 'UPLOAD'; time?: number } \| { action: 'show_otp_modal'; time?: number } /** Successful payment; some deployments omit order details in the terminal response. */ \| { action: 'show_order'; order?: CheckoutOrder } \| { action: 'pending'; order: CheckoutOrder } \| { action: 'payment_fail_error' \| 'show_error' \| 'FAIL' } \| { action: 'StockViolated' } \| { action: 'unknown'; backendAction: string; raw: JsonObject } )

PaymentStepInput

Source: src/types/payment.ts

FieldTypeRequired
idnumberOptional
paymentIdentifierstringOptional
payloadJsonObjectOptional
tatokenstringOptional
trackingDataJsonObjectOptional
isFailedstringOptional
imageUrlstringOptional
codestringOptional

CheckoutOrder

Source: src/types/checkout-order.ts

FieldTypeRequired
idOrderPublicIdRequired
orderNumberOrderPublicIdRequired
orderIdentifierstringRequired
invoiceCheckoutInvoiceRequired

CheckoutInvoice

Source: src/types/checkout-order.ts

FieldTypeRequired
invoiceItemsCheckoutInvoiceItem[]Required
shippingItemsCheckoutShippingItem[]Required
netTotalnumberOptional
finalTotalnumberOptional
shippingTotalnumberOptional
discountTotalnumberOptional
creditTotalnumberOptional
vatnumberOptional
vatPercentnumberOptional
itemsTotalRawPricenumberOptional
itemsDiscountnumberOptional
customerProfitnumberOptional
customerProfitPercentagenumberOptional
discountUsagesArray<{ discountCode?: { code?: string }; }>Optional
discountUsages.[].discountCode{ code?: string }Optional
discountUsages.[].discountCode.codestringOptional

CheckoutInvoiceItem

Source: src/types/checkout-order.ts

FieldTypeRequired
idOrderPublicIdOptional
productVariantIdOrderPublicIdRequired
namestringRequired
image{ url?: string }Optional
image.urlstringOptional
variantAttributesProductAttribute[]Required
singleItemPricenumberRequired
noOfItemsnumberRequired
totalItemsPricenumberRequired
customerProfitnumberOptional
formAttributesunknownOptional
bookingAttributesunknownOptional
productVariant{ commercialFiles?: Array<{ id: OrderPublicId }>; product: { productType: string; }; }Required
productVariant.commercialFilesArray<{ id: OrderPublicId }>Optional
productVariant.commercialFiles[].idOrderPublicIdRequired
productVariant.product{ productType: string; }Required
productVariant.product.productTypestringRequired

CheckoutShippingItem

Source: src/types/checkout-order.ts

FieldTypeRequired
idOrderPublicIdRequired
invoiceItemIdsOrderPublicId[]Required
rate{ id?: OrderPublicId; name: string; description?: string; price: number; type?: string; icon?: string; color?: string; }Required
rate.idOrderPublicIdOptional
rate.namestringRequired
rate.descriptionstringOptional
rate.pricenumberRequired
rate.typestringOptional
rate.iconstringOptional
rate.colorstringOptional

ProductAttribute

Source: src/types/common.ts

FieldTypeRequired
namestringRequired
valuestring | ProductAttributeValueObjectRequired

ProductAttributeValueObject

Source: src/types/common.ts

FieldTypeRequired
valuestringRequired
extrastringOptional
fieldTypestringOptional

On this page