Skip to main content

Checkout API Reference

The Checkout module manages the transition from shopping cart to order, handling customer information, shipping addresses, and order processing.

Overview

The Checkout API allows you to:

  • Create checkout sessions from shopping carts
  • Update customer billing and shipping information
  • Manage order status and payment processing
  • Handle order completion workflow
import SdkService from '../services/SdkService';

// Access checkout methods
const checkout = SdkService.sdk.checkout;

Methods

create()

Creates a new checkout session from an existing cart.

create(params: {
cart_id: string;
}): Promise<CreateCheckoutDto>

Parameters

ParameterTypeRequiredDescription
cart_idstringYesThe ID of the cart to convert to checkout

Example

const checkout = await SdkService.sdk.checkout.create({
cart_id: 'cart_12345'
});

console.log('Checkout created:', checkout.id);
console.log('Total amount:', checkout.total_price);
console.log('Currency:', checkout.currency);

Response

interface CreateCheckoutDto {
id: string;
cart_id: string;
status: 'PENDING' | 'PROCESSING' | 'COMPLETED' | 'CANCELLED';
total_price: number;
subtotal_price: number;
total_tax: number;
currency: string;
line_items: LineItem[];
created_at: string;
updated_at: string;
}


getById()

Retrieves a checkout session by its ID with all current details.

getById(params: {
checkout_id: string;
}): Promise<GetCheckoutDto>

Parameters

ParameterTypeRequiredDescription
checkout_idstringYesThe unique identifier of the checkout

Example

const checkout = await SdkService.sdk.checkout.getById({
checkout_id: 'checkout_67890'
});

console.log('Checkout status:', checkout.status);
console.log('Billing address:', checkout.billing_address);
console.log('Shipping address:', checkout.shipping_address);

Response

interface GetCheckoutDto {
id: string;
cart_id: string;
status: string;
email?: string;
total_price: number;
subtotal_price: number;
total_tax: number;
currency: string;
line_items: LineItem[];
billing_address?: AddressDto;
shipping_address?: AddressDto;
payment_method?: string;
success_url?: string;
cancel_url?: string;
buyer_accepts_terms_conditions: boolean;
buyer_accepts_purchase_conditions: boolean;
created_at: string;
updated_at: string;
}


update()

Updates checkout information including addresses, contact details, and order preferences.

update(params: {
checkout_id: string;
status?: string;
email?: string;
success_url?: string;
cancel_url?: string;
payment_method?: string;
shipping_address?: AddressInput;
billing_address?: AddressInput;
buyer_accepts_terms_conditions: boolean;
buyer_accepts_purchase_conditions: boolean;
}): Promise<UpdateCheckoutDto>

Parameters

ParameterTypeRequiredDescription
checkout_idstringYesThe unique identifier of the checkout
statusstringNoOrder status update
emailstringNoCustomer email address
success_urlstringNoURL to redirect after successful payment
cancel_urlstringNoURL to redirect if payment is cancelled
payment_methodstringNoPreferred payment method
shipping_addressAddressInputNoCustomer shipping address
billing_addressAddressInputNoCustomer billing address
buyer_accepts_terms_conditionsbooleanYesTerms and conditions acceptance
buyer_accepts_purchase_conditionsbooleanYesPurchase conditions acceptance

Example

const updatedCheckout = await SdkService.sdk.checkout.update({
checkout_id: 'checkout_67890',
email: 'customer@example.com',
billing_address: {
first_name: 'John',
last_name: 'Doe',
email: 'customer@example.com',
phone: '+1234567890',
phone_code: '+1',
address1: '123 Main Street',
address2: 'Apt 4B',
city: 'New York',
province: 'New York',
province_code: 'NY',
country: 'United States',
country_code: 'US',
zip: '10001',
company: 'Acme Corp'
},
shipping_address: {
first_name: 'John',
last_name: 'Doe',
email: 'customer@example.com',
phone: '+1234567890',
phone_code: '+1',
address1: '456 Delivery Ave',
city: 'Brooklyn',
province: 'New York',
province_code: 'NY',
country: 'United States',
country_code: 'US',
zip: '11201'
},
buyer_accepts_terms_conditions: true,
buyer_accepts_purchase_conditions: true
});

console.log('Checkout updated successfully');

Address Input Type

interface AddressInput {
first_name?: string;
last_name?: string;
phone_code?: string;
phone?: string;
company?: string;
address1?: string;
address2?: string;
city?: string;
province?: string;
province_code?: string;
country?: string;
country_code?: string;
email?: string;
zip?: string;
}

Response

interface UpdateCheckoutDto {
id: string;
status: string;
email?: string;
billing_address?: AddressDto;
shipping_address?: AddressDto;
buyer_accepts_terms_conditions: boolean;
buyer_accepts_purchase_conditions: boolean;
updated_at: string;
}


delete()

Permanently deletes a checkout session.

delete(params: {
checkout_id: string;
}): Promise<RemoveCheckoutDto>

Parameters

ParameterTypeRequiredDescription
checkout_idstringYesThe unique identifier of the checkout

Example

const result = await SdkService.sdk.checkout.delete({
checkout_id: 'checkout_67890'
});

console.log('Checkout deleted successfully');

Response

interface RemoveCheckoutDto {
success: boolean;
message: string;
}

Type Definitions

AddressDto

interface AddressDto {
first_name?: string;
last_name?: string;
phone?: string;
phone_code?: string;
company?: string;
address1?: string;
address2?: string;
city?: string;
province?: string;
province_code?: string;
country?: string;
country_code?: string;
email?: string;
zip?: string;
}

LineItem

interface LineItem {
id: string;
product_id: number;
variant_id?: number;
product_title: string;
variant_title?: string;
quantity: number;
price: number;
total_price: number;
sku?: string;
barcode?: string;
image_url?: string;
}

Complete Checkout Flow Example

Here's a comprehensive example showing the complete checkout process:

import React, { useState } from 'react';
import {
View,
Text,
TextInput,
Button,
StyleSheet,
ScrollView,
Alert,
Switch,
} from 'react-native';
import SdkService from '../services/SdkService';

interface CheckoutFormData {
email: string;
firstName: string;
lastName: string;
phone: string;
address1: string;
address2: string;
city: string;
country: string;
countryCode: string;
zip: string;
acceptTerms: boolean;
acceptPurchase: boolean;
}

export const CheckoutFlow: React.FC<{ cartId: string }> = ({ cartId }) => {
const [checkoutId, setCheckoutId] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
const [formData, setFormData] = useState<CheckoutFormData>({
email: '',
firstName: '',
lastName: '',
phone: '',
address1: '',
address2: '',
city: '',
country: 'United States',
countryCode: 'US',
zip: '',
acceptTerms: false,
acceptPurchase: false,
});

const createCheckout = async () => {
try {
setLoading(true);
const checkout = await SdkService.sdk.checkout.create({
cart_id: cartId,
});
setCheckoutId(checkout.id);
Alert.alert('Success', 'Checkout session created!');
} catch (error) {
console.error('Error creating checkout:', error);
Alert.alert('Error', 'Failed to create checkout session');
} finally {
setLoading(false);
}
};

const updateCheckoutInfo = async () => {
if (!checkoutId) return;

if (!formData.acceptTerms || !formData.acceptPurchase) {
Alert.alert('Error', 'Please accept terms and conditions');
return;
}

try {
setLoading(true);
const addressData = {
first_name: formData.firstName,
last_name: formData.lastName,
email: formData.email,
phone: formData.phone,
address1: formData.address1,
address2: formData.address2,
city: formData.city,
country: formData.country,
country_code: formData.countryCode,
zip: formData.zip,
};

await SdkService.sdk.checkout.update({
checkout_id: checkoutId,
email: formData.email,
billing_address: addressData,
shipping_address: addressData, // Same as billing for this example
buyer_accepts_terms_conditions: formData.acceptTerms,
buyer_accepts_purchase_conditions: formData.acceptPurchase,
});

Alert.alert('Success', 'Checkout information updated!');
} catch (error) {
console.error('Error updating checkout:', error);
Alert.alert('Error', 'Failed to update checkout information');
} finally {
setLoading(false);
}
};

const updateFormData = (key: keyof CheckoutFormData, value: string | boolean) => {
setFormData(prev => ({ ...prev, [key]: value }));
};

return (
<ScrollView style={styles.container}>
<Text style={styles.title}>Checkout</Text>

{!checkoutId ? (
<View style={styles.section}>
<Button
title={loading ? "Creating..." : "Create Checkout"}
onPress={createCheckout}
disabled={loading}
/>
</View>
) : (
<>
<Text style={styles.checkoutId}>Checkout ID: {checkoutId}</Text>

<View style={styles.section}>
<Text style={styles.sectionTitle}>Contact Information</Text>
<TextInput
style={styles.input}
placeholder="Email"
value={formData.email}
onChangeText={(value) => updateFormData('email', value)}
keyboardType="email-address"
autoCapitalize="none"
/>
</View>

<View style={styles.section}>
<Text style={styles.sectionTitle}>Personal Information</Text>
<View style={styles.row}>
<TextInput
style={[styles.input, styles.halfInput]}
placeholder="First Name"
value={formData.firstName}
onChangeText={(value) => updateFormData('firstName', value)}
/>
<TextInput
style={[styles.input, styles.halfInput]}
placeholder="Last Name"
value={formData.lastName}
onChangeText={(value) => updateFormData('lastName', value)}
/>
</View>
<TextInput
style={styles.input}
placeholder="Phone"
value={formData.phone}
onChangeText={(value) => updateFormData('phone', value)}
keyboardType="phone-pad"
/>
</View>

<View style={styles.section}>
<Text style={styles.sectionTitle}>Address Information</Text>
<TextInput
style={styles.input}
placeholder="Address Line 1"
value={formData.address1}
onChangeText={(value) => updateFormData('address1', value)}
/>
<TextInput
style={styles.input}
placeholder="Address Line 2 (Optional)"
value={formData.address2}
onChangeText={(value) => updateFormData('address2', value)}
/>
<View style={styles.row}>
<TextInput
style={[styles.input, styles.halfInput]}
placeholder="City"
value={formData.city}
onChangeText={(value) => updateFormData('city', value)}
/>
<TextInput
style={[styles.input, styles.halfInput]}
placeholder="ZIP Code"
value={formData.zip}
onChangeText={(value) => updateFormData('zip', value)}
/>
</View>
</View>

<View style={styles.section}>
<Text style={styles.sectionTitle}>Terms & Conditions</Text>
<View style={styles.switchRow}>
<Text style={styles.switchLabel}>Accept Terms & Conditions</Text>
<Switch
value={formData.acceptTerms}
onValueChange={(value) => updateFormData('acceptTerms', value)}
/>
</View>
<View style={styles.switchRow}>
<Text style={styles.switchLabel}>Accept Purchase Conditions</Text>
<Switch
value={formData.acceptPurchase}
onValueChange={(value) => updateFormData('acceptPurchase', value)}
/>
</View>
</View>

<View style={styles.section}>
<Button
title={loading ? "Updating..." : "Update Checkout Information"}
onPress={updateCheckoutInfo}
disabled={loading}
/>
</View>
</>
)}
</ScrollView>
);
};

const styles = StyleSheet.create({
container: {
flex: 1,
padding: 20,
backgroundColor: '#ffffff',
},
title: {
fontSize: 24,
fontWeight: 'bold',
textAlign: 'center',
marginBottom: 20,
},
checkoutId: {
fontSize: 12,
color: '#666',
marginBottom: 20,
fontFamily: 'monospace',
},
section: {
marginBottom: 20,
},
sectionTitle: {
fontSize: 18,
fontWeight: '600',
marginBottom: 10,
color: '#333',
},
input: {
borderWidth: 1,
borderColor: '#ddd',
borderRadius: 8,
padding: 12,
marginBottom: 10,
fontSize: 16,
},
row: {
flexDirection: 'row',
justifyContent: 'space-between',
},
halfInput: {
width: '48%',
},
switchRow: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
marginBottom: 10,
},
switchLabel: {
fontSize: 14,
flex: 1,
color: '#333',
},
});

Address Validation

Implement client-side address validation for better user experience:

const validateAddress = (address: AddressInput): string[] => {
const errors: string[] = [];

if (!address.first_name?.trim()) {
errors.push('First name is required');
}

if (!address.last_name?.trim()) {
errors.push('Last name is required');
}

if (!address.address1?.trim()) {
errors.push('Address is required');
}

if (!address.city?.trim()) {
errors.push('City is required');
}

if (!address.zip?.trim()) {
errors.push('ZIP code is required');
}

if (!address.email?.includes('@')) {
errors.push('Valid email is required');
}

return errors;
};

// Usage in checkout update
const updateCheckoutWithValidation = async () => {
const addressErrors = validateAddress(addressData);

if (addressErrors.length > 0) {
Alert.alert('Validation Error', addressErrors.join('\n'));
return;
}

// Proceed with checkout update
await SdkService.sdk.checkout.update({...});
};

Error Handling

Common checkout errors and how to handle them:

const handleCheckoutError = (error: any) => {
if (error.message?.includes('CART_NOT_FOUND')) {
Alert.alert('Error', 'The shopping cart no longer exists. Please start over.');
} else if (error.message?.includes('INVALID_ADDRESS')) {
Alert.alert('Invalid Address', 'Please check your address information and try again.');
} else if (error.message?.includes('TERMS_NOT_ACCEPTED')) {
Alert.alert('Terms Required', 'Please accept the terms and conditions to continue.');
} else {
Alert.alert('Checkout Error', 'An unexpected error occurred. Please try again.');
}
};

Best Practices

1. Form Validation

  • Validate required fields before submission
  • Provide real-time feedback to users
  • Use appropriate keyboard types for different inputs

2. Data Persistence

// Save checkout progress to AsyncStorage
import AsyncStorage from '@react-native-async-storage/async-storage';

const saveCheckoutProgress = async (checkoutId: string, formData: any) => {
const progressData = { checkoutId, formData, timestamp: Date.now() };
await AsyncStorage.setItem('checkout_progress', JSON.stringify(progressData));
};

const loadCheckoutProgress = async () => {
const saved = await AsyncStorage.getItem('checkout_progress');
return saved ? JSON.parse(saved) : null;
};

3. Address Suggestions

// Integration with address validation services
const validateAddressWithService = async (address: AddressInput) => {
// Use services like Google Places API, SmartyStreets, etc.
// to validate and suggest correct addresses
};

  • Cart API - Manage cart before checkout
  • Payment API - Process checkout payments
  • Channel API - Get terms and conditions (coming soon)