APIs & Hooks

This document introduces the HTTP APIs and Hooks provided by the component library for more granular control and custom implementation.

HTTP API / SDK

The library provides an SDK-style ApiClient (recommended) and still exposes standalone helpers (getPricePointInfo, createOrder, createOrderWithToken, getOrderDetail, etc.) with the same parameters as before. ApiClient reuses baseUrl and returns a consistent response shape.

ApiClient

ApiClient is a class that provides a convenient way to make API calls with a pre-configured base URL. It reuses the baseUrl and returns consistent response shapes.

import { ApiClient } from '@clickaroo/checkout-ui';
 
const apiClient = new ApiClient({ baseUrl: 'https://api.clickaroo.io' });

getPricePointInfo

Fetch price point info (single or multiple).

Using ApiClient (recommended)

import { ApiClient } from '@clickaroo/checkout-ui';
 
const apiClient = new ApiClient({ baseUrl: 'https://api.clickaroo.io' });
 
// Get single price point
const singleResult = await apiClient.getPricePointInfo('OPP-XXX');
 
// Get multiple price points
const multipleResult = await apiClient.getPricePointInfo(['OPP-XXX', 'OPP-YYY']);

Using standalone function

import { getPricePointInfo } from '@clickaroo/checkout-ui';
 
// Get single price point
const singleResult2 = await getPricePointInfo('https://api.clickaroo.io', 'OPP-XXX');
 
// Get multiple price points
const multipleResult2 = await getPricePointInfo('https://api.clickaroo.io', ['OPP-XXX', 'OPP-YYY']);

Parameters:

Parameter Type Description
offerPricePoints string|string[] Price point code(s)
can be a single string or an array of strings

Return Value:

{
  success: boolean;
  data?: ClickarooInfo | Record<string, ClickarooInfo>;  // Returns ClickarooInfo for single, object for multiple
  error?: {                                         // Error information
    message: string;
    code?: string;
    details?: unknown;
  };
}
 
interface ClickarooInfo {
  offer_code: string;                                // Price point code
  type: "one_off" | "subscription_schedules";        // Type: one-time purchase or subscription plan
  payment: {                                         // Payment information
    type: "stripe";
    data: {
      publishable_key: string;                       // Stripe publishable key
      account_id: string;                            // Stripe account ID
    };
  };
  one_off?: {                                        // One-time purchase info (exists when type is "one_off")
    price_in_cents: number;                          // Price (in cents)
    currency: string;                                // Currency type
    quantity: number;                                // Quantity
  };
  subscription_schedules?: {                         // Subscription plan info (exists when type is "subscription_schedules")
    phase: number;                                   // Phase
    price_in_cents: number;                          // Price (in cents)
    currency: string;                                // Currency type
    quantity: number;                                // Quantity
    period: string;                                  // Period
  }[];
}

createOrder

Create an order with the provided order data.

Using ApiClient (recommended)

import { ApiClient, useCheckoutContext } from '@clickaroo/checkout-ui';
 
const apiClient = new ApiClient({ baseUrl: 'https://api.clickaroo.io' });
const { stripe } = useCheckoutContext()
const { confirmationToken, error } = await stripe.createConfirmationToken({
  elements,
  params: {
    payment_method_data: {
      billing_details: {
        name: 'John Doe',
        email: '[email protected]',
        phone: '+1234567890',
      },
    },
  },
});
const result = await apiClient.createOrderWithToken({
  customer_info: {
    name: 'John Doe',
    email: '[email protected]',
    phone: '+1234567890',
  },
  shipping_address: {
    country: 'US',
    state: 'CA',
    city: 'San Francisco',
    address1: '123 Main St',
    zip: '94102',
  },
  payment: {
    type: 'stripe',
    data: {
      confirmation_token_id: confirmationToken,
      payment_method_types: ['card'],
    },
  },
  items: [
    { sku: 'SKU001', price_point_code: 'OPP-XXX' },
    { sku: 'SKU002', price_point_code: 'OPP-YYY' },
  ],
  metadata: {},
});

Parameters:

Parameter Type Description
orderData Omit<CreateOrderRequest, 'clickaroo_token'> Order payload
export interface CreateOrderRequest {
  clickaroo_token: string | null;
  price_point_code?: string; // Used for single product
  items?: CreateOrderItem[]; // Used for multiple products
  customer_info: OrderCustomerInfo;
  shipping_address: OrderShippingAddress;
  source_url: string;
  remark: string;
  metadata: OrderMetadata;
  payment: OrderPayment;
}
 
export interface OrderPayment {
  type: 'stripe';
  data: OrderPaymentData;
}
 
export interface OrderPaymentData {
  confirmation_token_id?: string;
  payment_method_types?: string[];
  setup_future_usage?: 'on_session' | 'off_session';
}

Return Value:

{
  success: boolean;
  data?: CreateOrderResponse;
  error?: {
    message: string;
    code?: string;
    details?: unknown;
  };
}
 
interface CreateOrderResponse {
  order_code: string;                    // Order code
  payment_status: OrderPaymentStatus;    // Payment status
  payment_result: Record<string, unknown>; // Payment result details
  order_trade_code: string;              // Trade code
}
 
enum OrderPaymentStatus {
  PENDING = 'pending',           // Pending payment
  PAID = 'paid',                 // Paid
  PARTIALLY_PAID = 'partially_paid', // Partially paid
  FAILED = 'failed',             // Payment failed
}

Note: This method automatically extracts clro_token. Please ensure that your application initially loads with clro_token in the URL.

getOrderDetail

Fetch order detail.

Using ApiClient (recommended)

import { ApiClient } from '@clickaroo/checkout-ui';
 
const apiClient = new ApiClient({ baseUrl: 'https://api.clickaroo.io' });
 
const result = await apiClient.getOrderDetail('ORDER-12345');

Parameters:

Parameter Type Description
orderCode string Order code (required)

Return Value:

{
  success: boolean;
  data?: OrderDetail;
  error?: {
    message: string;
    code?: string;
    details?: unknown;
  };
}
 
interface OrderDetail {
  order_code: string;                    // Order code
  customer: {                            // Customer information
    customer_code: string;
    name: string;
    email: string;
    phone: string;
  };
  shipping_address: {                    // Shipping address
    zip: string;
    city: string;
    state: string;
    country: string;
    address1: string;
    address2?: string;
  };
  billing_address: {                     // Billing address
    zip: string;
    city: string;
    state: string;
    country: string;
    address1: string;
    address2?: string;
  };
  status: OrderStatus;                   // Order status
  payment_status: OrderPaymentStatus;    // Payment status
  refund_status: RefundStatus;           // Refund status
  fulfillment_status: FulfillmentStatus; // Fulfillment status
  remark: string;                        // Remark
  total_amount: string;                  // Total order amount
  currency: string;                      // Currency type
  items: Array<{                         // Order item list
    item_code: string;
    name: string;
    quantity: number;
    price: string;
    total: string;
  }>;
  metadata?: {                           // Order metadata
    sku?: string;
    [key: string]: unknown;
  };
  created_at: string;                    // Creation time
  updated_at: string;                    // Update time
}
 
enum OrderStatus {
  PENDING = 'pending',       // Pending
  CONFIRMED = 'confirmed',   // Confirmed
  PROCESSING = 'processing', // Processing
  SHIPPED = 'shipped',       // Shipped
  DELIVERED = 'delivered',   // Delivered
  CANCELLED = 'cancelled',   // Cancelled
}
 
enum RefundStatus {
  NO_REFUND = 'no_refund',           // No refund
  PARTIAL_REFUND = 'partial_refund', // Partial refund
  FULL_REFUND = 'full_refund',       // Full refund
}
 
enum FulfillmentStatus {
  PENDING = 'pending',       // Pending
  PROCESSING = 'processing', // Processing
  SHIPPED = 'shipped',       // Shipped
  DELIVERED = 'delivered',   // Delivered
}

Hooks

The component library provides the following Hooks for getting state and handling logic in components. These Hooks are built on top of the APIs and can be used directly in React projects.

useCheckoutContext

Get checkout context data and methods. Must be used inside CheckoutProvider.

Usage Example:

import { useCheckoutContext } from '@clickaroo/checkout-ui';
 
function CustomComponent() {
  const {
    customerInfo,           // Customer information
    deliveryAddress,        // Delivery address
    cart,                   // Cart items array
    isPaymentComplete,      // Whether payment info is complete (Stripe form validation passed)
    updateCustomerInfo,     // Update customer information
    updateDeliveryAddress,  // Update delivery address
    isFormValid,            // Validate if form is valid
  } = useCheckoutContext();
 
  return (
    <div>
      <p>Cart items count: {cart.length}</p>
      <p>Form valid: {isFormValid() ? 'Yes' : 'No'}</p>
      <p>Payment status: {isPaymentComplete ? 'Complete' : 'Incomplete'}</p>
    </div>
  );
}

Return Value Types:

CustomerInfo

Customer information structure:

interface CustomerInfo {
  firstName: string;
  lastName: string;
  email: string;
  phone: string;
}
Field Type Description
*firstName string First name (required)
*lastName string Last name (required)
*email string Email (required, must be valid email format)
*phone string Phone number (required, E.164 format)

DeliveryAddress

Delivery address structure:

interface DeliveryAddress {
  country: string;
  address: string;
  address2?: string;
  city: string;
  state: string;
  zipCode: string;
}
Field Type Description
*country string Country (required)
*address string Street address (required)
address2 string Address line 2 (optional)
*city string City (required)
*state string State/Province (required)
*zipCode string Postal code (required)

StripeState

Stripe payment state:

interface StripeState {
  stripe: Stripe | null;
  elements: StripeElements | null;
  isComplete: boolean;
  isLoading: boolean;
}
Field Type Description
stripe Stripe | null Stripe instance
elements StripeElements | null Stripe Elements instance
isComplete boolean Whether payment information is complete (Stripe form validation passed), not payment completion
isLoading boolean Whether Stripe is loading

useOrderSubmission

Handle order submission logic, including creating Stripe confirmation tokens and calling the order creation API.

Usage Example:

import { useCheckoutContext, useOrderSubmission } from '@clickaroo/checkout-ui';
 
function CustomSubmitButton() {
  const { isFormValid } = useCheckoutContext();
  const { isSubmitting, submitOrder } = useOrderSubmission();
 
  const handleSubmit = async () => {
    if (!isFormValid()) {
      alert('Please fill in all information');
      return;
    }
 
    const result = await submitOrder();
 
    if (result.success) {
      console.log('Order successful', result.orderCode, result.tradeCode);
      // Navigate to success page
    } else {
      alert(result.message || 'Order submission failed');
    }
  };
 
  return (
    <button 
      onClick={handleSubmit}
      disabled={isSubmitting || !isFormValid()}
    >
      {isSubmitting ? 'Submitting...' : 'Submit Order'}
    </button>
  );
}

Return Value:

interface UseOrderSubmissionReturn {
  isSubmitting: boolean;  // Whether submitting
  submitOrder: () => Promise<OrderSubmissionResult>;
}
 
interface OrderSubmissionResult {
  success: boolean;        // Whether successful
  message: string;         // Message (success or error information)
  orderCode?: string;      // Order code (when successful)
  tradeCode?: string;      // Trade code (when successful)
}

useOrderDetail

Get order details, supports automatic refresh and error handling.

Usage Example:

import { useOrderDetail } from '@clickaroo/checkout-ui';
 
function OrderDetailPage({ orderCode }: { orderCode: string }) {
  const { orderDetail, loading, error, refetch } = useOrderDetail(orderCode);
 
  if (loading) return <div>Loading...</div>;
  if (error) return <div>Error: {error}</div>;
  if (!orderDetail) return <div>Order does not exist</div>;
 
  return (
    <div>
      <h1>Order Details</h1>
      <p>Order Code: {orderDetail.order_code}</p>
      <p>Status: {orderDetail.status}</p>
      <p>Payment Status: {orderDetail.payment_status}</p>
      <p>Total Amount: {orderDetail.total_amount} {orderDetail.currency}</p>
      {orderDetail.metadata && (
        <div>
          <p>Product Title: {orderDetail.metadata.product_title}</p>
          <p>Product Price: {orderDetail.metadata.current_price}</p>
        </div>
      )}
      <button onClick={refetch}>Refresh</button>
    </div>
  );
}

Return Value:

interface UseOrderDetailReturn {
  orderDetail: OrderDetail | null;  // Order details
  loading: boolean;                  // Whether loading
  error: string | null;              // Error information
  refetch: () => void;               // Refetch order details
}

useClickarooParams

Access Clickaroo parameters (such as token, sub4, etc.) managed by ClickarooProvider. This hook must be used inside ClickarooProvider.

Usage Example:

import { useClickarooParams } from '@clickaroo/checkout-ui';
 
function MyComponent() {
  const { getParam, params } = useClickarooParams();
 
  // Get a specific parameter
  const token = getParam('token');
  const sub4 = getParam('sub4');
 
  return (
    <div>
      <p>Token: {token || 'Not set'}</p>
      <p>Sub4: {sub4 || 'Not set'}</p>
      <p>All params: {JSON.stringify(params)}</p>
    </div>
  );
}

Return Value:

interface UseClickarooParamsReturn {
  getParam: (paramName: string) => string | null;           // Get parameter value
  params: Record<string, string>;                          // Current parameters (read-only)
}

Notes: If params is not specified in ClickarooProvider config, all URL parameters will be managed automatically. If keyPrefix is not specified in ClickarooProvider config, parameters will be stored without a prefix.