csharp
java
javascript
php
python
ruby
typescript

order

/order

Software Development Kit (SDK)

To make working with our API easier, we package an SDK in the languages listed to the right. Select the language that you are interested in and sample code with additional commentary will be available. All of our APIs are available on GitHub at:

http://www.github.com/UltraCart/

By using an SDK you receive a number of important benefits.

Instantiating the API

There are four steps to instantiating the API.

  1. Include the SDK package
  2. Set the API credentials.
  3. Set the API version header.
  4. Instantiate the API Client.

Expansion

By default, when you read an order, a limited object is returned. If you specify the _expand parameter, additional properties of the order object are returned. We encourage you to limit the amount of information that you query for orders, to the minimal amount possible to have optimal communication. The following expansion operations are available.

Retrieve A/R Retry Configuration

Permissions:
  • order_read

Produces: application/json
get
/order/accountsReceivableRetryConfig

Retrieve A/R Retry Configuration. This is primarily an internal API call. It is doubtful you would ever need to use it.

SDK Function Name: getAccountsReceivableRetryConfig

Responses
Status Code Reason Response Model
200
Successful response AccountsReceivableRetryConfigResponse
400
Bad Request 400
401
Unauthorized 401
410
Authorized Application Disabled 410
429
Too Many Requests 429
500
Server Side 500
// This is primarily an internal API call.  It is doubtful you would ever need to use it.
// We do not provide an example for this call.
// This is primarily an internal API call.  It is doubtful you would ever need to use it.
// We do not provide an example for this call.
// This is primarily an internal API call.  It is doubtful you would ever need to use it.
// We do not provide an example for this call.
// This is primarily an internal API call.  It is doubtful you would ever need to use it.
// We do not provide an example for this call.
# This is primarily an internal API call.  It is doubtful you would ever need to use it.
# We do not provide an example for this call.
# This is primarily an internal API call.  It is doubtful you would ever need to use it.
# We do not provide an example for this call.
// This is primarily an internal API call.  It is doubtful you would ever need to use it.
// We do not provide an example for this call.

Update A/R Retry Configuration

Permissions:
  • order_write

Produces: application/json
post
/order/accountsReceivableRetryConfig

Update A/R Retry Configuration. This is primarily an internal API call. It is doubtful you would ever need to use it.

SDK Function Name: updateAccountsReceivableRetryConfig

Parameters
Parameter Description Location Data Type Required
retry_config AccountsReceivableRetryConfig object body AccountsReceivableRetryConfig required
Responses
Status Code Reason Response Model
200
Successful response BaseResponse
400
Bad Request 400
401
Unauthorized 401
410
Authorized Application Disabled 410
429
Too Many Requests 429
500
Server Side 500
// This is primarily an internal API call.  It is doubtful you would ever need to use it.
// We do not provide an example for this call.
// This is primarily an internal API call.  It is doubtful you would ever need to use it.
// We do not provide an example for this call.
// This is primarily an internal API call.  It is doubtful you would ever need to use it.
// We do not provide an example for this call.
// This is primarily an internal API call.  It is doubtful you would ever need to use it.
// We do not provide an example for this call.
# This is primarily an internal API call.  It is doubtful you would ever need to use it.
# We do not provide an example for this call.
# This is primarily an internal API call.  It is doubtful you would ever need to use it.
# We do not provide an example for this call.
// This is primarily an internal API call.  It is doubtful you would ever need to use it.
// We do not provide an example for this call.

Retrieve A/R Retry Statistics

Permissions:
  • order_read

Produces: application/json
get
/order/accountsReceivableRetryConfig/stats

Retrieve A/R Retry Statistics. This is primarily an internal API call. It is doubtful you would ever need to use it.

SDK Function Name: getAccountsReceivableRetryStats

Parameters
Parameter Description Location Data Type Required
from query string optional
to query string optional
Responses
Status Code Reason Response Model
200
Successful response AccountsReceivableRetryStatsResponse
400
Bad Request 400
401
Unauthorized 401
410
Authorized Application Disabled 410
429
Too Many Requests 429
500
Server Side 500
// This is primarily an internal API call.  It is doubtful you would ever need to use it.
// We do not provide an example for this call.
// This is primarily an internal API call.  It is doubtful you would ever need to use it.
// We do not provide an example for this call.
// This is primarily an internal API call.  It is doubtful you would ever need to use it.
// We do not provide an example for this call.
// This is primarily an internal API call.  It is doubtful you would ever need to use it.
// We do not provide an example for this call.
# This is primarily an internal API call.  It is doubtful you would ever need to use it.
# We do not provide an example for this call.
# This is primarily an internal API call.  It is doubtful you would ever need to use it.
# We do not provide an example for this call.
// This is primarily an internal API call.  It is doubtful you would ever need to use it.
// We do not provide an example for this call.

Retrieve orders

Permissions:
  • order_read

Produces: application/json
get
/order/orders

Retrieves a group of orders from the account. If no parameters are specified, the API call will fail with a bad request error. Always specify some parameters to limit the scope of the orders returned to ones you are truly interested in. You will need to make multiple API calls in order to retrieve the entire result set since this API performs result set pagination.

SDK Function Name: getOrders

Parameters
Parameter Description Location Data Type Required
order_id Order Id query string optional
payment_method Payment Method
Allowed Values
  • Affirm
  • Amazon
  • Amazon SC
  • Cash
  • Check
  • COD
  • Credit Card
  • eCheck
  • LoanHero
  • Money Order
  • PayPal
  • Venmo
  • Apple Pay
  • Google Pay
  • Purchase Order
  • Quote Request
  • Unknown
  • Wire Transfer
query string optional
company Company query string optional
first_name First Name query string optional
last_name Last Name query string optional
city City query string optional
state_region State/Region query string optional
postal_code Postal Code query string optional
country_code Country Code (ISO-3166 two letter) query string optional
phone Phone query string optional
email Email query string optional
cc_email CC Email query string optional
total Total query number optional
screen_branding_theme_code Screen Branding Theme Code query string optional
storefront_host_name StoreFront Host Name query string optional
creation_date_begin Creation Date Begin query string (dateTime) optional
creation_date_end Creation Date End query string (dateTime) optional
payment_date_begin Payment Date Begin query string (dateTime) optional
payment_date_end Payment Date End query string (dateTime) optional
shipment_date_begin Shipment Date Begin query string (dateTime) optional
shipment_date_end Shipment Date End query string (dateTime) optional
rma RMA query string optional
purchase_order_number Purchase Order Number query string optional
item_id Item Id query string optional
current_stage Current Stage
Allowed Values
  • Accounts Receivable
  • Pending Clearance
  • Fraud Review
  • Rejected
  • Shipping Department
  • Completed Order
  • Quote Request
  • Quote Sent
  • Least Cost Routing
query string optional
channel_partner_code Channel Partner Code query string optional
channel_partner_order_id Channel Partner Order ID query string optional
customer_profile_oid query integer (int32) optional
Refund Date Begin query string optional
Refund Date End query string optional
Custom Field 1 query string optional
Custom Field 2 query string optional
Custom Field 3 query string optional
Custom Field 4 query string optional
Custom Field 5 query string optional
Custom Field 6 query string optional
Custom Field 7 query string optional
ship_on_date_begin query string optional
ship_on_date_end query string optional
Custom Field 8 query string optional
Custom Field 9 query string optional
Custom Field 10 query string optional
Query Target query string optional
_limit The maximum number of records to return on this one API call. (Maximum 200)
Default: 100
query integer optional
_offset Pagination of the record set. Offset is a zero based index.
Default: 0
query integer optional
_sort The sort order of the orders. See Sorting documentation for examples of using multiple values and sorting by ascending and descending.
Allowed Values
  • order_id
  • shipping.company
  • shipping.first_name
  • shipping.last_name
  • shipping.city
  • shipping.state_region
  • shipping.postal_code
  • shipping.country_code
  • billing.phone
  • billing.email
  • billing.cc_email
  • billing.company
  • billing.first_name
  • billing.last_name
  • billing.city
  • billing.state
  • billing.postal_code
  • billing.country_code
  • creation_dts
  • payment.payment_dts
  • checkout.screen_branding_theme_code
  • channel_partner.channel_partner_code
  • channel_partner.channel_partner_order_id
query string optional
_expand The object expansion to perform on the result. query string optional
Responses
Status Code Reason Response Model
200
Successful response OrdersResponse
400
Bad Request 400
401
Unauthorized 401
410
Authorized Application Disabled 410
429
Too Many Requests 429
500
Server Side 500
using System;
using System.Collections.Generic;
using System.Linq;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;
using Newtonsoft.Json;

namespace SdkSample.order
{
    public class GetOrders
    {
        /*
         * getOrders was the first order query provided by UltraCart. It still functions well, but it is extremely verbose
         * because the query call takes a variable for every possible filter. You are advised to get getOrdersByQuery().
         * It is easier to use and will result in less code. Still, we provide an example here to be thorough.
         *
         * For this email, we will query all orders for a particular email address. The getOrdersByQuery() example
         * illustrates using a date range to filter and select orders.
         */
        public static void Execute()
        {
            OrderApi orderApi = new OrderApi(Constants.ApiKey);

            List<Order> orders = new List<Order>();

            int iteration = 1;
            int offset = 0;
            int limit = 200;
            bool moreRecordsToFetch = true;

            while (moreRecordsToFetch)
            {
                Console.WriteLine($"executing iteration {iteration}<br>");
                List<Order> chunkOfOrders = GetOrderChunk(orderApi, offset, limit);
                orders.AddRange(chunkOfOrders);
                offset = offset + limit;
                moreRecordsToFetch = chunkOfOrders.Count == limit;
                iteration++;
            }

            // this could get verbose...
            foreach (Order order in orders)
            {
                Console.WriteLine(JsonConvert.SerializeObject(order, new JsonSerializerSettings { Formatting = Formatting.Indented}));                
            }
            
            Console.WriteLine("<html lang=\"en\"><body><pre>");
            Console.WriteLine(orders);
            Console.WriteLine("</pre></body></html>");
        }

        private static List<Order> GetOrderChunk(OrderApi orderApi, int offset, int limit)
        {
            string expansion = "item,summary,billing,shipping,shipping.tracking_number_details";
            // see www.ultracart.com/api/ for all the expansion fields available (this list below may become stale)
            /*
            Possible Order Expansions:
            affiliate           affiliate.ledger                    auto_order
            billing             channel_partner                     checkout
            coupon              customer_profile                    digital_order
            edi                 fraud_score                         gift
            gift_certificate    internal                            item
            linked_shipment     marketing                           payment
            payment.transaction quote                               salesforce
            shipping            shipping.tracking_number_details    summary
            taxes
            */

            string orderId = null;
            string paymentMethod = null;
            string company = null;
            string firstName = null;
            string lastName = null;
            string city = null;
            string stateRegion = null;
            string postalCode = null;
            string countryCode = null;
            string phone = null;
            string email = "support@ultracart.com"; // <-- this is the only filter we're using.
            string ccEmail = null;
            decimal? total = null;
            string screenBrandingThemeCode = null;
            string storefrontHostName = null;
            string creationDateBegin = null;
            string creationDateEnd = null;
            string paymentDateBegin = null;
            string paymentDateEnd = null;
            string shipmentDateBegin = null;
            string shipmentDateEnd = null;
            string rma = null;
            string purchaseOrderNumber = null;
            string itemId = null;
            string currentStage = null;
            string channelPartnerCode = null;
            string channelPartnerOrderId = null;
            string sort = null;

            // see all these parameters? that is why you should use getOrdersByQuery() instead of getOrders()
            OrdersResponse apiResponse = orderApi.GetOrders(orderId, paymentMethod, company, firstName, lastName, city,
                stateRegion, postalCode, countryCode, phone, email, ccEmail, total, screenBrandingThemeCode,
                storefrontHostName, creationDateBegin, creationDateEnd, paymentDateBegin, paymentDateEnd,
                shipmentDateBegin, shipmentDateEnd, rma, purchaseOrderNumber, itemId, currentStage,
                channelPartnerCode, channelPartnerOrderId, limit, offset, sort, expansion);

            if (apiResponse.Orders != null)
            {
                return apiResponse.Orders.ToList();
            }
            return new List<Order>();
        }
    }
}
package order;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.ultracart.admin.v2.OrderApi;
import com.ultracart.admin.v2.models.*;
import com.ultracart.admin.v2.util.ApiException;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class GetOrders {
   /*
    * getOrders was the first order query provided by UltraCart. It still functions well, but it is extremely verbose
    * because the query call takes a variable for every possible filter. You are advised to get getOrdersByQuery().
    * It is easier to use and will result in less code. Still, we provide an example here to be thorough.
    *
    * For this email, we will query all orders for a particular email address. The getOrdersByQuery() example
    * illustrates using a date range to filter and select orders.
    */
   public void execute() throws ApiException {
       OrderApi orderApi = new OrderApi(common.Constants.API_KEY);

       List<Order> orders = new ArrayList<>();

       int iteration = 1;
       int offset = 0;
       int limit = 200;
       boolean moreRecordsToFetch = true;

       while (moreRecordsToFetch) {
           System.out.println("executing iteration " + iteration + "<br>");
           List<Order> chunkOfOrders = getOrderChunk(orderApi, offset, limit);
           orders.addAll(chunkOfOrders);
           offset = offset + limit;
           moreRecordsToFetch = chunkOfOrders.size() == limit;
           iteration++;
       }

       // this could get verbose...
       Gson gson = new GsonBuilder().setPrettyPrinting().create();
       for (Order order : orders) {
           System.out.println(gson.toJson(order));
       }
       
       System.out.println("<html lang=\"en\"><body><pre>");
       System.out.println(orders);
       System.out.println("</pre></body></html>");
   }

   private List<Order> getOrderChunk(OrderApi orderApi, int offset, int limit) throws ApiException {
       String expansion = "item,summary,billing,shipping,shipping.tracking_number_details";
       // see www.ultracart.com/api/ for all the expansion fields available (this list below may become stale)
       /*
       Possible Order Expansions:
       affiliate           affiliate.ledger                    auto_order
       billing             channel_partner                     checkout
       coupon              customer_profile                    digital_order
       edi                 fraud_score                         gift
       gift_certificate    internal                            item
       linked_shipment     marketing                           payment
       payment.transaction quote                               salesforce
       shipping            shipping.tracking_number_details    summary
       taxes
       */

       String orderId = null;
       String paymentMethod = null;
       String company = null;
       String firstName = null;
       String lastName = null;
       String city = null;
       String stateRegion = null;
       String postalCode = null;
       String countryCode = null;
       String phone = null;
       String email = "support@ultracart.com"; // <-- this is the only filter we're using.
       String ccEmail = null;
       BigDecimal total = null;
       String screenBrandingThemeCode = null;
       String storefrontHostName = null;
       String creationDateBegin = null;
       String creationDateEnd = null;
       String paymentDateBegin = null;
       String paymentDateEnd = null;
       String shipmentDateBegin = null;
       String shipmentDateEnd = null;
       String rma = null;
       String purchaseOrderNumber = null;
       String itemId = null;
       String currentStage = null;
       String channelPartnerCode = null;
       String channelPartnerOrderId = null;
       String sort = null;

       // see all these parameters? that is why you should use getOrdersByQuery() instead of getOrders()
       OrdersResponse apiResponse = orderApi.getOrders(orderId, paymentMethod, company, firstName, lastName, city,
           stateRegion, postalCode, countryCode, phone, email, ccEmail, total, screenBrandingThemeCode,
           storefrontHostName, creationDateBegin, creationDateEnd, paymentDateBegin, paymentDateEnd,
           shipmentDateBegin, shipmentDateEnd, rma, purchaseOrderNumber, itemId, currentStage,
           channelPartnerCode, channelPartnerOrderId, limit, offset, sort, expansion);

       if (apiResponse.getOrders() != null) {
           return apiResponse.getOrders();
       }
       return new ArrayList<>();
   }
}
import { orderApi } from '../api.js';

/**
 * getOrders was the first order query provided by UltraCart. It still functions well, but it is extremely verbose
 * because the query call takes a variable for every possible filter. You are advised to get getOrdersByQuery().
 * It is easier to use and will result in less code. Still, we provide an example here to be thorough.
 *
 * For this email, we will query all orders for a particular email address. The getOrdersByQuery() example
 * illustrates using a date range to filter and select orders.
 */
export async function execute() {
    const orders = [];

    let iteration = 1;
    let offset = 0;
    const limit = 200;
    let moreRecordsToFetch = true;

    while (moreRecordsToFetch) {
        console.log(`executing iteration ${iteration}<br>`);
        const chunkOfOrders = await getOrderChunk(offset, limit);
        orders.push(...chunkOfOrders);
        offset = offset + limit;
        moreRecordsToFetch = chunkOfOrders.length === limit;
        iteration++;
    }

    // this could get verbose...
    for (const order of orders) {
        console.log(JSON.stringify(order, null, 2));
    }

    console.log(orders);
}

/**
 * Fetches a chunk of orders based on various filters
 * @param offset - The offset for pagination
 * @param limit - The number of records to fetch
 * @returns A list of orders
 */
async function getOrderChunk(offset, limit) {
    // The expansion variable instructs UltraCart how much information to return.
    // see www.ultracart.com/api/ for all the expansion fields available (this list below may become stale)
    /*
    Possible Order Expansions:
    affiliate           affiliate.ledger                    auto_order
    billing             channel_partner                     checkout
    coupon              customer_profile                    digital_order
    edi                 fraud_score                         gift
    gift_certificate    internal                            item
    linked_shipment     marketing                           payment
    payment.transaction quote                               salesforce
    shipping            shipping.tracking_number_details    summary
    taxes
    */
    const expansion = "item,summary,billing,shipping,shipping.tracking_number_details";

    // Prepare query parameters - only using email as a filter
    const queryParams = {
        orderId: undefined,
        paymentMethod: undefined,
        company: undefined,
        firstName: undefined,
        lastName: undefined,
        city: undefined,
        stateRegion: undefined,
        postalCode: undefined,
        countryCode: undefined,
        phone: undefined,
        email: "support@ultracart.com", // <-- this is the only filter we're using
        ccEmail: undefined,
        total: undefined,
        screenBrandingThemeCode: undefined,
        storefrontHostName: undefined,
        creationDateBegin: undefined,
        creationDateEnd: undefined,
        paymentDateBegin: undefined,
        paymentDateEnd: undefined,
        shipmentDateBegin: undefined,
        shipmentDateEnd: undefined,
        rma: undefined,
        purchaseOrderNumber: undefined,
        itemId: undefined,
        currentStage: undefined,
        channelPartnerCode: undefined,
        channelPartnerOrderId: undefined,
        _limit: limit,
        _offset: offset,
        _sort: undefined,
        _expand: expansion
    };

    try {
        const apiResponse = await new Promise((resolve, reject) => {
            orderApi.getOrders(queryParams, function (error, data, response) {
                if (error) {
                    reject(error);
                } else {
                    resolve(data);
                }
            });
        });

        return apiResponse.orders || [];
    } catch (error) {
        console.error('Error fetching orders:', error);
        return [];
    }
}
<?php

set_time_limit(3000); // pull all orders could take a long time.
ini_set('max_execution_time', 3000);
ini_set('display_errors', 1);

/*
 * getOrders was the first order query provided by UltraCart.  It still functions well, but it is extremely verbose
 * because the query call takes a variable for every possible filter.  You are advised to get getOrdersByQuery().
 * It is easier to use and will result in less code.  Still, we provide an example here to be thorough.
 *
 * For this email, we will query all orders for a particular email address.  The getOrdersByQuery() example
 * illustrates using a date range to filter and select orders.
 */

use ultracart\v2\api\OrderApi;

require_once '../vendor/autoload.php';
require_once '../constants.php';


$order_api = ultracart\v2\api\OrderApi::usingApiKey(Constants::API_KEY);


function getOrderChunk(OrderApi $order_api, int $offset, int $limit): array
{
    $expansion = "item,summary,billing,shipping,shipping.tracking_number_details";
    // see www.ultracart.com/api/ for all the expansion fields available (this list below may become stale)
    /*
    Possible Order Expansions:
    affiliate           affiliate.ledger                    auto_order
    billing             channel_partner                     checkout
    coupon              customer_profile                    digital_order
    edi                 fraud_score                         gift
    gift_certificate    internal                            item
    linked_shipment     marketing                           payment
    payment.transaction quote                               salesforce
    shipping            shipping.tracking_number_details    summary
    taxes
    */

    $order_id = null;
    $payment_method = null;
    $company = null;
    $first_name = null;
    $last_name = null;
    $city = null;
    $state_region = null;
    $postal_code = null;
    $country_code = null;
    $phone = null;
    $email = 'support@ultracart.com'; // <-- this is the only filter we're using.
    $cc_email = null;
    $total = null;
    $screen_branding_theme_code = null;
    $storefront_host_name = null;
    $creation_date_begin = null;
    $creation_date_end = null;
    $payment_date_begin = null;
    $payment_date_end = null;
    $shipment_date_begin = null;
    $shipment_date_end = null;
    $rma = null;
    $purchase_order_number = null;
    $item_id = null;
    $current_stage = null;
    $channel_partner_code = null;
    $channel_partner_order_id = null;
    $_sort = null;


    // see all these parameters?  that is why you should use getOrdersByQuery() instead of getOrders()
    $api_response = $order_api->getOrders($order_id, $payment_method, $company, $first_name, $last_name, $city,
        $state_region, $postal_code, $country_code, $phone, $email, $cc_email, $total, $screen_branding_theme_code,
        $storefront_host_name, $creation_date_begin, $creation_date_end, $payment_date_begin, $payment_date_end,
        $shipment_date_begin, $shipment_date_end, $rma, $purchase_order_number, $item_id, $current_stage,
        $channel_partner_code, $channel_partner_order_id, $limit, $offset, $_sort, $expansion);

    if($api_response->getOrders() != null){
        return $api_response->getOrders();
    }
    return [];
}

$orders = [];

$iteration = 1;
$offset = 0;
$limit = 200;
$more_records_to_fetch = true;

while( $more_records_to_fetch ){

    echo "executing iteration " . $iteration . '<br>';
    $chunk_of_orders = getOrderChunk($order_api, $offset, $limit);
    $orders = array_merge($orders, $chunk_of_orders);
    $offset = $offset + $limit;
    $more_records_to_fetch = count($chunk_of_orders) == $limit;
    $iteration++;

}

// this could get verbose...
echo '<html lang="en"><body><pre>';
var_dump($orders);
echo '</pre></body></html>';

import time
from ultracart import ApiException
from ultracart.apis import OrderApi
from samples import api_client

# Increase time limit, pulling all orders could take a long time.
time_limit = 3000
# Set max execution time
time.sleep(time_limit)
# Set display errors
display_errors = 1

# getOrders was the first order query provided by UltraCart. It still functions well, but it is extremely verbose
# because the query call takes a variable for every possible filter. You are advised to use getOrdersByQuery().
# It is easier to use and will result in less code. Still, we provide an example here to be thorough.
#
# For this email, we will query all orders for a particular email address. The getOrdersByQuery() example
# illustrates using a date range to filter and select orders.

# Using the API key to initialize the order API
order_api = OrderApi(api_client())

def get_order_chunk(order_api, offset, limit):
    expand = "item,summary,billing,shipping,shipping.tracking_number_details"
    # See www.ultracart.com/api/ for all the expansion fields available (this list below may become stale)
    # Possible Order Expansions:
    # affiliate           affiliate.ledger                    auto_order
    # billing             channel_partner                     checkout
    # coupon              customer_profile                    digital_order
    # edi                 fraud_score                         gift
    # gift_certificate    internal                            item
    # linked_shipment     marketing                           payment
    # payment.transaction quote                               salesforce
    # shipping            shipping.tracking_number_details    summary
    # taxes

    order_id = None
    payment_method = None
    company = None
    first_name = None
    last_name = None
    city = None
    state_region = None
    postal_code = None
    country_code = None
    phone = None
    email = 'support@ultracart.com'  # <-- this is the only filter we're using.
    cc_email = None
    total = None
    screen_branding_theme_code = None
    storefront_host_name = None
    creation_date_begin = None
    creation_date_end = None
    payment_date_begin = None
    payment_date_end = None
    shipment_date_begin = None
    shipment_date_end = None
    rma = None
    purchase_order_number = None
    item_id = None
    current_stage = None
    channel_partner_code = None
    channel_partner_order_id = None
    _sort = None

    # See all these parameters? That is why you should use getOrdersByQuery() instead of getOrders()
    try:
        api_response = order_api.get_orders(
            order_id=order_id, payment_method=payment_method, company=company, first_name=first_name,
            last_name=last_name, city=city, state_region=state_region, postal_code=postal_code,
            country_code=country_code, phone=phone, email=email, cc_email=cc_email, total=total,
            screen_branding_theme_code=screen_branding_theme_code, storefront_host_name=storefront_host_name,
            creation_date_begin=creation_date_begin, creation_date_end=creation_date_end,
            payment_date_begin=payment_date_begin, payment_date_end=payment_date_end,
            shipment_date_begin=shipment_date_begin, shipment_date_end=shipment_date_end, rma=rma,
            purchase_order_number=purchase_order_number, item_id=item_id, current_stage=current_stage,
            channel_partner_code=channel_partner_code, channel_partner_order_id=channel_partner_order_id,
            limit=limit, offset=offset, _sort=_sort, expand=expand
        )
    except ApiException as e:
        print(f"Exception when calling OrderApi->get_orders: {e}")
        return []

    if api_response.orders is not None:
        return api_response.orders
    return []

# Initialize empty list to hold orders
orders = []

iteration = 1
offset = 0
limit = 200
more_records_to_fetch = True

while more_records_to_fetch:
    print(f"executing iteration {iteration}")
    chunk_of_orders = get_order_chunk(order_api, offset, limit)
    orders.extend(chunk_of_orders)
    offset += limit
    more_records_to_fetch = len(chunk_of_orders) == limit
    iteration += 1

# This could get verbose...
import pprint
pprint.pprint(orders)

# frozen_string_literal: true

require 'ultracart_api'
require_relative '../constants'

# Increase script execution time limit
Process.setrlimit(Process::RLIMIT_CPU, 3000)

=begin
 getOrders was the first order query provided by UltraCart.  It still functions well, but it is extremely verbose
 because the query call takes a variable for every possible filter.  You are advised to get getOrdersByQuery().
 It is easier to use and will result in less code.  Still, we provide an example here to be thorough.

 For this script, we will query all orders for a particular email address.  The getOrdersByQuery() example
 illustrates using a date range to filter and select orders.
=end

def get_order_chunk(order_api, offset, limit)
  # Possible Order Expansions:
  # affiliate           affiliate.ledger                    auto_order
  # billing             channel_partner                     checkout
  # coupon              customer_profile                    digital_order
  # edi                 fraud_score                         gift
  # gift_certificate    internal                            item
  # linked_shipment     marketing                           payment
  # payment.transaction quote                               salesforce
  # shipping            shipping.tracking_number_details    summary
  # taxes

  expansion = "item,summary,billing,shipping,shipping.tracking_number_details"

  # Prepare opts hash with all parameters
  opts = {
    'order_id' => nil,
    'payment_method' => nil,
    'company' => nil,
    'first_name' => nil,
    'last_name' => nil,
    'city' => nil,
    'state_region' => nil,
    'postal_code' => nil,
    'country_code' => nil,
    'phone' => nil,
    'email' => 'support@ultracart.com', # Only filter we're using
    'cc_email' => nil,
    'total' => nil,
    'screen_branding_theme_code' => nil,
    'storefront_host_name' => nil,
    'creation_date_begin' => nil,
    'creation_date_end' => nil,
    'payment_date_begin' => nil,
    'payment_date_end' => nil,
    'shipment_date_begin' => nil,
    'shipment_date_end' => nil,
    'rma' => nil,
    'purchase_order_number' => nil,
    'item_id' => nil,
    'current_stage' => nil,
    'channel_partner_code' => nil,
    'channel_partner_order_id' => nil,
    '_sort' => nil,
    '_limit' => limit,
    '_offset' => offset,
    '_expand' => expansion
  }

  # Make API call
  api_response = order_api.get_orders(opts)

  # Return orders or empty array
  api_response.orders || []
end

# Initialize variables for order retrieval
orders = []
iteration = 1
offset = 0
limit = 200
more_records_to_fetch = true

# Retrieve orders in chunks
order_api = UltracartClient::OrderApi.new_using_api_key(Constants::API_KEY)

while more_records_to_fetch
  puts "executing iteration #{iteration}"

  chunk_of_orders = get_order_chunk(order_api, offset, limit)
  orders.concat(chunk_of_orders)

  offset += limit
  more_records_to_fetch = chunk_of_orders.length == limit
  iteration += 1
end

# Output orders (without HTML wrapping as per guidelines)
p orders
import { orderApi } from '../api';
import {
    Order,
    OrdersResponse
} from 'ultracart_rest_api_v2_typescript';

/**
 * getOrders was the first order query provided by UltraCart. It still functions well, but it is extremely verbose
 * because the query call takes a variable for every possible filter. You are advised to get getOrdersByQuery().
 * It is easier to use and will result in less code. Still, we provide an example here to be thorough.
 *
 * For this email, we will query all orders for a particular email address. The getOrdersByQuery() example
 * illustrates using a date range to filter and select orders.
 */
export async function execute(): Promise<void> {
    const orders: Order[] = [];

    let iteration = 1;
    let offset = 0;
    const limit = 200;
    let moreRecordsToFetch = true;

    while (moreRecordsToFetch) {
        console.log(`executing iteration ${iteration}<br>`);
        const chunkOfOrders = await getOrderChunk(offset, limit);
        orders.push(...chunkOfOrders);
        offset = offset + limit;
        moreRecordsToFetch = chunkOfOrders.length === limit;
        iteration++;
    }

    // this could get verbose...
    for (const order of orders) {
        console.log(JSON.stringify(order, null, 2));
    }

    console.log(orders);
}

/**
 * Fetches a chunk of orders based on various filters
 * @param offset - The offset for pagination
 * @param limit - The number of records to fetch
 * @returns A list of orders
 */
async function getOrderChunk(offset: number, limit: number): Promise<Order[]> {
    // The expansion variable instructs UltraCart how much information to return.
    // see www.ultracart.com/api/ for all the expansion fields available (this list below may become stale)
    /*
    Possible Order Expansions:
    affiliate           affiliate.ledger                    auto_order
    billing             channel_partner                     checkout
    coupon              customer_profile                    digital_order
    edi                 fraud_score                         gift
    gift_certificate    internal                            item
    linked_shipment     marketing                           payment
    payment.transaction quote                               salesforce
    shipping            shipping.tracking_number_details    summary
    taxes
    */
    const expansion = "item,summary,billing,shipping,shipping.tracking_number_details";

    // Prepare query parameters - only using email as a filter
    const queryParams = {
        orderId: undefined,
        paymentMethod: undefined,
        company: undefined,
        firstName: undefined,
        lastName: undefined,
        city: undefined,
        stateRegion: undefined,
        postalCode: undefined,
        countryCode: undefined,
        phone: undefined,
        email: "support@ultracart.com", // <-- this is the only filter we're using
        ccEmail: undefined,
        total: undefined,
        screenBrandingThemeCode: undefined,
        storefrontHostName: undefined,
        creationDateBegin: undefined,
        creationDateEnd: undefined,
        paymentDateBegin: undefined,
        paymentDateEnd: undefined,
        shipmentDateBegin: undefined,
        shipmentDateEnd: undefined,
        rma: undefined,
        purchaseOrderNumber: undefined,
        itemId: undefined,
        currentStage: undefined,
        channelPartnerCode: undefined,
        channelPartnerOrderId: undefined,
        limit,
        offset,
        sort: undefined,
        expand: expansion
    };

    try {
        const apiResponse: OrdersResponse = await orderApi.getOrders(queryParams);
        return apiResponse.orders || [];
    } catch (error) {
        console.error('Error fetching orders:', error);
        return [];
    }
}

Insert an order

Permissions:
  • order_write

Consumes: application/json
Produces: application/json
post
/order/orders

Inserts a new order on the UltraCart account. This is probably NOT the method you want. This is for channel orders. For regular orders the customer is entering, use the CheckoutApi. It has many, many more features, checks, and validations.

SDK Function Name: insertOrder

Parameters
Parameter Description Location Data Type Required
order Order to insert body Order required
_expand The object expansion to perform on the result. See documentation for examples query string optional
Responses
Status Code Reason Response Model
200
Successful response OrderResponse
400
Bad Request 400
401
Unauthorized 401
410
Authorized Application Disabled 410
429
Too Many Requests 429
500
Server Side 500
/*
 * Please do not use OrderApi.insertOrder()
 * This method was provided in the first release of our REST API.
 * It was replaced with our ChannelPartnerApi.importChannelPartnerOrder()
 *
 * Here are your options:
 * If you need to add regular orders that still require payment processing, use the CheckoutApi.
 *    The CheckoutApi has fantastic support for payment processing.
 *
 * If you need to add channel partner orders (eBay, Amazon, your call center, etc), use the ChannelPartnerApi.
 *    The ChannelPartnerApi has appropriate support for processing such orders.
 *
 * We support our entire API forever, so this method remains active.  But, we do not provide any samples for it.
 * You may use it, but we believe it will require extra time and effort and possibly much frustration.
 *
 * Reminder: The ONLY way to provide credit card numbers and cvv numbers to the UltraCart system is through
 * hosted fields.
 * See: https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1377775/UltraCart+Hosted+Credit+Card+Fields
 * See: https://github.com/UltraCart/sdk_samples/blob/master/hosted_fields/hosted_fields.html
 */
/*
 * Please do not use OrderApi.insertOrder()
 * This method was provided in the first release of our REST API.
 * It was replaced with our ChannelPartnerApi.importChannelPartnerOrder()
 *
 * Here are your options:
 * If you need to add regular orders that still require payment processing, use the CheckoutApi.
 *    The CheckoutApi has fantastic support for payment processing.
 *
 * If you need to add channel partner orders (eBay, Amazon, your call center, etc), use the ChannelPartnerApi.
 *    The ChannelPartnerApi has appropriate support for processing such orders.
 *
 * We support our entire API forever, so this method remains active.  But, we do not provide any samples for it.
 * You may use it, but we believe it will require extra time and effort and possibly much frustration.
 *
 * Reminder: The ONLY way to provide credit card numbers and cvv numbers to the UltraCart system is through
 * hosted fields.
 * See: https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1377775/UltraCart+Hosted+Credit+Card+Fields
 * See: https://github.com/UltraCart/sdk_samples/blob/master/hosted_fields/hosted_fields.html
 */
/*
 * Please do not use OrderApi.insertOrder()
 * This method was provided in the first release of our REST API.
 * It was replaced with our ChannelPartnerApi.importChannelPartnerOrder()
 *
 * Here are your options:
 * If you need to add regular orders that still require payment processing, use the CheckoutApi.
 *    The CheckoutApi has fantastic support for payment processing.
 *
 * If you need to add channel partner orders (eBay, Amazon, your call center, etc), use the ChannelPartnerApi.
 *    The ChannelPartnerApi has appropriate support for processing such orders.
 *
 * We support our entire API forever, so this method remains active.  But, we do not provide any samples for it.
 * You may use it, but we believe it will require extra time and effort and possibly much frustration.
 *
 * Reminder: The ONLY way to provide credit card numbers and cvv numbers to the UltraCart system is through
 * hosted fields.
 * See: https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1377775/UltraCart+Hosted+Credit+Card+Fields
 * See: https://github.com/UltraCart/sdk_samples/blob/master/hosted_fields/hosted_fields.html
 */
<?php

/*
 * Please do not use OrderApi.insertOrder()
 * This method was provided in the first release of our REST API.
 * It was replaced with our ChannelPartnerApi.importChannelPartnerOrder()
 *
 * Here are your options:
 * If you need to add regular orders that still require payment processing, use the CheckoutApi.
 *    The CheckoutApi has fantastic support for payment processing.
 *
 * If you need to add channel partner orders (eBay, Amazon, your call center, etc), use the ChannelPartnerApi.
 *    The ChannelPartnerApi has appropriate support for processing such orders.
 *
 * We support our entire API forever, so this method remains active.  But, we do not provide any samples for it.
 * You may use it, but we believe it will require extra time and effort and possibly much frustration.
 *
 * Reminder: The ONLY way to provide credit card numbers and cvv numbers to the UltraCart system is through
 * hosted fields.
 * See: https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1377775/UltraCart+Hosted+Credit+Card+Fields
 * See: https://github.com/UltraCart/sdk_samples/blob/master/hosted_fields/hosted_fields.html
 */

echo '<html><body>Please see script comments.</body></html>';

"""
 * Please do not use OrderApi.insertOrder()
 * This method was provided in the first release of our REST API.
 * It was replaced with our ChannelPartnerApi.importChannelPartnerOrder()
 *
 * Here are your options:
 * If you need to add regular orders that still require payment processing, use the CheckoutApi.
 *    The CheckoutApi has fantastic support for payment processing.
 *
 * If you need to add channel partner orders (eBay, Amazon, your call center, etc), use the ChannelPartnerApi.
 *    The ChannelPartnerApi has appropriate support for processing such orders.
 *
 * We support our entire API forever, so this method remains active.  But, we do not provide any samples for it.
 * You may use it, but we believe it will require extra time and effort and possibly much frustration.
 *
 * Reminder: The ONLY way to provide credit card numbers and cvv numbers to the UltraCart system is through
 * hosted fields.
 * See: https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1377775/UltraCart+Hosted+Credit+Card+Fields
 * See: https://github.com/UltraCart/sdk_samples/blob/master/hosted_fields/hosted_fields.html
"""

# This is important:
# You cannot use the Order API to insert an order.
# Orders can only be created using the Checkout API. It contains a huge amount of validations and routines
# to ensure order integrity.  So the example below uses the Checkout API.
#
# This is equally important:
# You cannot just add credit card numbers.  The UltraCart system is designed from the "Security First".
# As such, the system is designed so that merchants never touch credit card numbers.  With that said, the API
# must be able to interact with credit card numbers in a limited sense.  To do so, you will need to use Hosted
# Fields.  Hosted fields are a set of javascript scripts designed for a web page that encapsulate credit card fields
# inside iframes to prevent script attacks.  If you need to provide credit cards (as the merchant) using the API,
# you'll have to create a web page that has hosted fields, enter the credit card information, and then use
# the subsequently provided token within your API objects to associate the credit card with the api object.
#
# Common objections to this insane amount of trouble to work with credit cards:
# Objection 1: You can trust me.
# Response 1: You? Maybe.  The other guy?  No.  Experience has shown us that if we allow it, developers will misuse it.
#
# Objection 2: I need to automate something.
# Response 2:  There is nothing you need to automate with credit cards.  Also, touching credit cards in any way moves
# your code and your machines within PCI scope and could require you to provide expensive auditing of that code and
# equipment should a payment company target you for an audit.
#
# Objection 3: My customers need to manage their information.
# Response 3: We have tremendous tools and web pages already built and free to you, the merchant, that allow customers
# to manage their own credit cards.  We have email communication routines and powerful engines to keep track of customer
# information and alert them to self-service any of their information should the need arise.
#

# frozen_string_literal: true

require 'json'
require 'ultracart_api'
require_relative '../constants'

checkout_api = UltracartClient::CheckoutApi.new_using_api_key(Constants::API_KEY, Constants::VERIFY_SSL, Constants::DEBUG_MODE)
customer_api = UltracartClient::CustomerApi.new_using_api_key(Constants::API_KEY, Constants::VERIFY_SSL, Constants::DEBUG_MODE)

# ----------------------------------------------------------------------------------
# expansion should contain all the objects that will be needed throughout the checkout.
# see https://www.ultracart.com/api/#Topic3 for the complete list.
# This expansion list should be supplied for each get/put throughout or data may be lost on the return objects.
expansion = 'billing,checkout,coupons,items,payment,settings.shipping.estimates,shipping,summary,taxes,coupons'
# The expansion above doesn't include much of the item objects because they're not needed.  For example, we don't
# need the item multimedia because we're not showing this cart to an end customer like a javascript implementation would
# if you needed to show images and such to a customer, then add 'items' to the csv above.  Better, yet, if you need to do
# all that, use javascript instead.
# ----------------------------------------------------------------------------------

# look at an existing customer profile, grab the first shipping address, if any, and create a CartShipping object
def get_shipping_from_profile(customer_profile)
  shipping = nil

  if customer_profile.shipping&.length&.positive?
    shipping = UltracartClient::CartShipping.new
    shipping.company = customer_profile.shipping.company
    shipping.first_name = customer_profile.shipping.first_name
    shipping.last_name = customer_profile.shipping.last_name
    shipping.address1 = customer_profile.shipping.address1
    shipping.address2 = customer_profile.shipping.address2
    shipping.city = customer_profile.shipping.city
    shipping.postal_code = customer_profile.shipping.postal_code
    shipping.state_region = customer_profile.shipping.state_region
    shipping.country_code = customer_profile.shipping.country_code
    shipping.day_phone = customer_profile.shipping.day_phone
    shipping.evening_phone = customer_profile.shipping.evening_phone
  end

  shipping
end

# look at an existing customer profile, grab the first billing address, if any, and create a CartBilling object
def get_billing_from_profile(customer_profile)
  billing = nil

  if customer_profile.billing&.length&.positive?
    billing = UltracartClient::CartBilling.new
    billing.company = customer_profile.billing.company
    billing.first_name = customer_profile.billing.first_name
    billing.last_name = customer_profile.billing.last_name
    billing.address1 = customer_profile.billing.address1
    billing.address2 = customer_profile.billing.address2
    billing.city = customer_profile.billing.city
    billing.postal_code = customer_profile.billing.postal_code
    billing.state_region = customer_profile.billing.state_region
    billing.country_code = customer_profile.billing.country_code
    billing.day_phone = customer_profile.billing.day_phone
    billing.evening_phone = customer_profile.billing.evening_phone
  end

  billing
end

begin

  email = 'test@test.com'
  cc_mask = 'XXXXXXXXXXXX1234'
  cvv_mask = 'XXX'
  cc_token = 'F893C8CBAE34830177F9EA9D97205400'
  cvv_token = '3FA7577E42F7580177F9EAA2FF1F5900'

  get_response = checkout_api.get_cart(_expand: expansion)
  if get_response.errors&.length&.positive?
    # handle errors here.
    abort('System error.  Could not retrieve shopping cart.')
  else
    cart = get_response.cart
  end

  items = []
  item = UltracartClient::CartItem.new
  item.item_id = 'BONE'
  item.quantity = 1

  # This 'Bone' item within the DEMO account has a single item option.
  # To get the name and possible values of, use the Item API and query the item.
  item_option = UltracartClient::CartItemOption.new
  item_option.name = 'Addon Treat'
  item_option.selected_value = 'No thanks'
  item.options = [item_option]

  items.push(item)
  cart.items = items

  # If the customer already has a customer profile, then load that profile and pull the shipping/billing from there.
  # otherwise populate it manually.
  customer_response = customer_api.get_customer_by_email(email, { _expand: 'shipping,billing,cards' })
  if customer_response&.customer

    cp = customer_response.customer # cp is short for 'customer profile'
    cart.shipping = get_shipping_from_profile(cp)
    cart.billing = get_billing_from_profile(cp)

  end

  # if we didn't load the shipping from a customer profile, add it here (assume this data is collected from somewhere)
  unless cart.shipping
    shipping = UltracartClient::CartShipping.new
    shipping.company = 'UltraCart'
    shipping.first_name = 'Perry'
    shipping.last_name = 'Smith'
    shipping.address1 = '55 Main Street'
    shipping.address2 = 'Suite 101'
    shipping.city = 'Duluth'
    shipping.postal_code = '30097'
    shipping.state_region = 'GA'
    shipping.country_code = 'US'
    shipping.day_phone = '404-656-1776'
    shipping.evening_phone = '404-656-1776'
    cart.shipping = shipping
  end

  unless cart.billing
    billing = UltracartClient::CartBilling.new
    billing.company = 'UltraCart'
    billing.first_name = 'Perry'
    billing.last_name = 'Smith'
    billing.address1 = '55 Main Street'
    billing.address2 = 'Suite 101'
    billing.city = 'Duluth'
    billing.postal_code = '30097'
    billing.state_region = 'GA'
    billing.country_code = 'US'
    billing.day_phone = '404-656-1776'
    billing.evening_phone = '404-656-1776'
    billing.email = email
    cart.billing = billing
  end
  
  # --- Payment Block ---
  payment = UltracartClient::CartPayment.new
  credit_card = UltracartClient::CartPaymentCreditCard.new

  credit_card.card_number = cc_mask
  credit_card.card_expiration_month = 3
  credit_card.card_expiration_year = 2031
  credit_card.card_type = 'Visa'
  credit_card.card_number_token = cc_token
  credit_card.card_verification_number = cvv_mask
  credit_card.card_verification_number_token = cvv_token

  payment.payment_method = 'Credit Card'
  payment.credit_card = credit_card
  cart.payment = payment
  # --- End Payment Block ---

  # add a coupon.
  coupon = UltracartClient::CartCoupon.new
  coupon.coupon_code = '10OFF' # you'll need to create a coupon first, you know?
  cart.coupons = [coupon]

  # for best results, set the shipping address and update the server before
  # setting the shipping method.  the cart that is returned below will have
  # the optimal shipping method estimates and ensure that you don't error
  # by selecting a shipping method that is somehow excluded from the possible
  # list for whatever reason (restrictions, locations, item-level constraints, etc)
  update_response = checkout_api.update_cart(cart, _expand: expansion)
  cart = update_response.cart

  # for shipping, check the estimates and select one.  for a completely non-interactive checkout such as this,
  # the shipping method will either be known beforehand (hard-coded) or use the least expensive method.  The
  # least expensive method is always the first one, so for this example, I'll select the first shipping method.
  if cart.settings&.shipping
    shipping_settings = cart.settings.shipping
    estimates = shipping_settings.estimates
    if estimates != nil && estimates.length.positive?
      cart.shipping.shipping_method = estimates[0].name
    end
  end

  update_response = checkout_api.update_cart(cart, _expand: expansion)
  cart = update_response.cart

  # validate the cart to ensure everything is in order.
  validation_request = UltracartClient::CartValidationRequest.new
  validation_request.cart = cart # I don't set the checks variable.  standard checks are usually sufficient.
  validation_response = checkout_api.validate_cart(validation_request)

  errors = []
  order = nil

  if validation_response.errors == nil || validation_response.errors.length.zero?
    finalize_request = UltracartClient::CartFinalizeOrderRequest.new
    finalize_request.cart = cart
    finalize_response = checkout_api.finalize_order(finalize_request)

    if finalize_response
      if finalize_response.successful
        order = finalize_response.order
      else
        errors = finalize_response.errors
      end
    end

  else
    errors = validation_response.errors
  end

rescue UltracartClient::ApiError => ex
  puts ex.to_json
  abort(ex.message)
end

puts 'Errors follow:'
puts errors.to_json

puts 'Order follows:'
puts order.to_json
/*
 * Please do not use OrderApi.insertOrder()
 * This method was provided in the first release of our REST API.
 * It was replaced with our ChannelPartnerApi.importChannelPartnerOrder()
 *
 * Here are your options:
 * If you need to add regular orders that still require payment processing, use the CheckoutApi.
 *    The CheckoutApi has fantastic support for payment processing.
 *
 * If you need to add channel partner orders (eBay, Amazon, your call center, etc), use the ChannelPartnerApi.
 *    The ChannelPartnerApi has appropriate support for processing such orders.
 *
 * We support our entire API forever, so this method remains active.  But, we do not provide any samples for it.
 * You may use it, but we believe it will require extra time and effort and possibly much frustration.
 *
 * Reminder: The ONLY way to provide credit card numbers and cvv numbers to the UltraCart system is through
 * hosted fields.
 * See: https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1377775/UltraCart+Hosted+Credit+Card+Fields
 * See: https://github.com/UltraCart/sdk_samples/blob/master/hosted_fields/hosted_fields.html
 */

Retrieve order batch

Permissions:
  • order_read

Produces: application/json
post
/order/orders/batch

Retrieves a group of orders from the account based on an array of order ids. If more than 500 order ids are specified, the API call will fail with a bad request error.

SDK Function Name: getOrdersBatch

Parameters
Parameter Description Location Data Type Required
order_batch Order batch body OrderQueryBatch required
_expand The object expansion to perform on the result. query string optional
Responses
Status Code Reason Response Model
200
Successful response OrdersResponse
400
Bad Request 400
401
Unauthorized 401
410
Authorized Application Disabled 410
429
Too Many Requests 429
500
Server Side 500
using System;
using System.Collections.Generic;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;
using Newtonsoft.Json;

namespace SdkSample.order
{
    public class GetOrdersBatch
    {
        /*
         * This method is useful when you need to query a defined set of orders and would like to avoid querying them
         * one at a time.
         */
        public static void Execute()
        {
            OrderApi orderApi = new OrderApi(Constants.ApiKey);

            string expansion = "item,summary,billing,shipping,shipping.tracking_number_details";
            // see www.ultracart.com/api/ for all the expansion fields available (this list below may become stale)
            /*
            Possible Order Expansions:
            affiliate           affiliate.ledger                    auto_order
            billing             channel_partner                     checkout
            coupon              customer_profile                    digital_order
            edi                 fraud_score                         gift
            gift_certificate    internal                            item
            linked_shipment     marketing                           payment
            payment.transaction quote                               salesforce
            shipping            shipping.tracking_number_details    summary
            taxes
            */

            OrderQueryBatch orderBatch = new OrderQueryBatch();
            List<string> orderIds = new List<string> { "DEMO-0009104390", "DEMO-0009104391", "DEMO-0009104392" };
            orderBatch.OrderIds = orderIds;

            OrdersResponse apiResponse = orderApi.GetOrdersBatch(orderBatch, expansion);

            if (apiResponse.Error != null)
            {
                Console.Error.WriteLine(apiResponse.Error.DeveloperMessage);
                Console.Error.WriteLine(apiResponse.Error.UserMessage);
                Environment.Exit(1);
            }

            List<Order> orders = apiResponse.Orders;
            if (orders.Count == 0)
            {
                Console.Error.WriteLine("There were no orders returned by this query.");
            }

            // do something with the orders. for this example, we're just accessing many properties as illustration.
            foreach (Order order in orders)
            {
                OrderSummary summary = order.Summary;
                decimal actualShippingCost = summary.ActualShipping?.Localized ?? 0m;

                Order.CurrentStageEnum? currentStage = order.CurrentStage;
                OrderShipping sAddr = order.Shipping;
                List<string> trackingNumbers = sAddr.TrackingNumbers;
                foreach (string trackingNumber in trackingNumbers)
                {
                    // do something with tracking number here.
                }

                // Here's how to access the shipping information.  Do something with the variables.
                string sfname = order.Shipping.FirstName;
                string slname = order.Shipping.LastName;
                string saddress1 = order.Shipping.Address1;
                string saddress2 = order.Shipping.Address2;
                string scity = order.Shipping.City;
                string sregion = order.Shipping.StateRegion;
                string sccode = order.Shipping.CountryCode;
                string spcode = order.Shipping.PostalCode;
                string sdayphone = order.Shipping.DayPhone;
                string shippingMethod = order.Shipping.ShippingMethod;

                // Here's how to access the billing information.  Do something with the variables.
                string billingAddress1 = order.Billing.Address1;
                string billingAddress2 = order.Billing.Address2;
                string billingCity = order.Billing.City;
                string billingStateRegion = order.Billing.StateRegion;
                string billingCountryCode = order.Billing.CountryCode;
                string billingPostalCode = order.Billing.PostalCode;
                string email = order.Billing.Email; // email is located on the billing object.

                // here is how to access the items
                List<OrderItem> items = order.Items;
                foreach (OrderItem item in items)
                {
                    decimal qty = item.Quantity;
                    string itemId = item.MerchantItemId;
                    string description = item.Description;
                    decimal cost = item.Cost.Localized;
                    string costFormatted = item.Cost.LocalizedFormatted; // cost with symbols.
                }
            }

            // this could get verbose depending on the size of your batch ...
            foreach (Order order in orders)
            {
                Console.WriteLine(JsonConvert.SerializeObject(order, new JsonSerializerSettings { Formatting = Formatting.Indented}));                
            }
            
        }
    }
}
package order;

import com.ultracart.admin.v2.OrderApi;
import com.ultracart.admin.v2.models.*;
import com.ultracart.admin.v2.util.ApiException;
import common.Constants;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

public class GetOrdersBatch {
    /*
     * This method is useful when you need to query a defined set of orders and would like to avoid querying them
     * one at a time.
     */
    public static void execute() throws ApiException {
        OrderApi orderApi = new OrderApi(Constants.API_KEY);

        String expansion = "item,summary,billing,shipping,shipping.tracking_number_details";
        // see www.ultracart.com/api/ for all the expansion fields available (this list below may become stale)
        /*
        Possible Order Expansions:
        affiliate           affiliate.ledger                    auto_order
        billing             channel_partner                     checkout
        coupon              customer_profile                    digital_order
        edi                 fraud_score                         gift
        gift_certificate    internal                            item
        linked_shipment     marketing                           payment
        payment.transaction quote                               salesforce
        shipping            shipping.tracking_number_details    summary
        taxes
        */

        OrderQueryBatch orderBatch = new OrderQueryBatch();
        List<String> orderIds = Arrays.asList("DEMO-0009104390", "DEMO-0009104391", "DEMO-0009104392");
        orderBatch.setOrderIds(orderIds);

        OrdersResponse apiResponse = orderApi.getOrdersBatch(orderBatch, expansion);

        if (apiResponse.getError() != null) {
            System.err.println(apiResponse.getError().getDeveloperMessage());
            System.err.println(apiResponse.getError().getUserMessage());
            System.exit(1);
        }

        List<Order> orders = apiResponse.getOrders();
        if (orders.isEmpty()) {
            System.err.println("There were no orders returned by this query.");
        }

        // do something with the orders. for this example, we're just accessing many properties as illustration.
        for (Order order : orders) {
            OrderSummary summary = order.getSummary();
            BigDecimal actualShippingCost = summary.getActualShipping() != null ? summary.getActualShipping().getLocalized() : BigDecimal.ZERO;

            Order.CurrentStageEnum currentStage = order.getCurrentStage();
            OrderShipping sAddr = order.getShipping();
            List<String> trackingNumbers = sAddr.getTrackingNumbers();
            for (String trackingNumber : trackingNumbers) {
                // do something with tracking number here.
            }

            // Here's how to access the shipping information. Do something with the variables.
            String sfname = order.getShipping().getFirstName();
            String slname = order.getShipping().getLastName();
            String saddress1 = order.getShipping().getAddress1();
            String saddress2 = order.getShipping().getAddress2();
            String scity = order.getShipping().getCity();
            String sregion = order.getShipping().getStateRegion();
            String sccode = order.getShipping().getCountryCode();
            String spcode = order.getShipping().getPostalCode();
            String sdayphone = order.getShipping().getDayPhone();
            String shippingMethod = order.getShipping().getShippingMethod();

            // Here's how to access the billing information. Do something with the variables.
            String billingAddress1 = order.getBilling().getAddress1();
            String billingAddress2 = order.getBilling().getAddress2();
            String billingCity = order.getBilling().getCity();
            String billingStateRegion = order.getBilling().getStateRegion();
            String billingCountryCode = order.getBilling().getCountryCode();
            String billingPostalCode = order.getBilling().getPostalCode();
            String email = order.getBilling().getEmail(); // email is located on the billing object.

            // here is how to access the items
            List<OrderItem> items = order.getItems();
            for (OrderItem item : items) {
                BigDecimal qty = item.getQuantity();
                String itemId = item.getMerchantItemId();
                String description = item.getDescription();
                BigDecimal cost = item.getCost().getLocalized();
                String costFormatted = item.getCost().getLocalizedFormatted(); // cost with symbols.
            }
        }

        // this could get verbose depending on the size of your batch ...
        for (Order order : orders) {
            System.out.println(order.toString());
        }
    }
}
import {orderApi} from '../api.js';

/**
 * This method is useful when you need to query a defined set of orders and would like to avoid querying them
 * one at a time.
 */
export async function execute() {
    // The expansion variable instructs UltraCart how much information to return.
    // see www.ultracart.com/api/ for all the expansion fields available (this list below may become stale)
    /*
    Possible Order Expansions:
    affiliate           affiliate.ledger                    auto_order
    billing             channel_partner                     checkout
    coupon              customer_profile                    digital_order
    edi                 fraud_score                         gift
    gift_certificate    internal                            item
    linked_shipment     marketing                           payment
    payment.transaction quote                               salesforce
    shipping            shipping.tracking_number_details    summary
    taxes
    */
    const expansion = "item,summary,billing,shipping,shipping.tracking_number_details";

    const orderBatch = {
        order_ids: ["DEMO-0009104390", "DEMO-0009104391", "DEMO-0009104392"]
    };

    try {
        const apiResponse = await new Promise((resolve, reject) => {
            orderApi.getOrdersBatch(
                orderBatch,
                {_expand: expansion}, function (error, data, response) {
                    if (error) {
                        reject(error);
                    } else {
                        resolve(data);
                    }
                });
        });

        if (apiResponse.error) {
            console.error(apiResponse.error.developer_message);
            console.error(apiResponse.error.user_message);
            process.exit(1);
        }

        const orders = apiResponse.orders || [];

        if (orders.length === 0) {
            console.error("There were no orders returned by this query.");
        }

        // do something with the orders. for this example, we're just accessing many properties as illustration.
        for (const order of orders) {
            const summary = order.summary;
            const actualShippingCost = summary?.actual_shipping?.localized ?? 0;

            const currentStage = order.current_stage;
            const sAddr = order.shipping;
            const trackingNumbers = sAddr?.tracking_numbers || [];

            for (const trackingNumber of trackingNumbers) {
                // do something with tracking number here.
            }

            // Here's how to access the shipping information. Do something with the variables.
            const sfname = order.shipping?.first_name;
            const slname = order.shipping?.last_name;
            const saddress1 = order.shipping?.address1;
            const saddress2 = order.shipping?.address2;
            const scity = order.shipping?.city;
            const sregion = order.shipping?.state_region;
            const sccode = order.shipping?.country_code;
            const spcode = order.shipping?.postal_code;
            const sdayphone = order.shipping?.day_phone;
            const shippingMethod = order.shipping?.shipping_method;

            // Here's how to access the billing information. Do something with the variables.
            const billingAddress1 = order.billing?.address1;
            const billingAddress2 = order.billing?.address2;
            const billingCity = order.billing?.city;
            const billingStateRegion = order.billing?.state_region;
            const billingCountryCode = order.billing?.country_code;
            const billingPostalCode = order.billing?.postal_code;
            const email = order.billing?.email; // email is located on the billing object.

            // here is how to access the items
            const items = order.items || [];
            for (const item of items) {
                const qty = item.quantity;
                const itemId = item.merchant_item_id;
                const description = item.description;
                const cost = item.cost?.localized;
                const costFormatted = item.cost?.localized_formatted; // cost with symbols.
            }
        }

        // this could get verbose depending on the size of your batch ...
        for (const order of orders) {
            console.log(JSON.stringify(order, null, 2));
        }
    } catch (error) {
        console.error('Error fetching orders batch:', error);
    }
}
<?php

ini_set('display_errors', 1);

/*
 * This method is useful when you need to query a defined set of orders and would like to avoid querying them
 * one at a time.
 */

use ultracart\v2\api\OrderApi;
use ultracart\v2\models\OrderQueryBatch;

require_once '../vendor/autoload.php';
require_once '../constants.php';


$order_api = OrderApi::usingApiKey(Constants::API_KEY);


$expansion = "item,summary,billing,shipping,shipping.tracking_number_details";
// see www.ultracart.com/api/ for all the expansion fields available (this list below may become stale)
/*
Possible Order Expansions:
affiliate           affiliate.ledger                    auto_order
billing             channel_partner                     checkout
coupon              customer_profile                    digital_order
edi                 fraud_score                         gift
gift_certificate    internal                            item
linked_shipment     marketing                           payment
payment.transaction quote                               salesforce
shipping            shipping.tracking_number_details    summary
taxes
*/

$order_batch = new OrderQueryBatch();
$order_ids = array('DEMO-0009104390', 'DEMO-0009104391', 'DEMO-0009104392');
$order_batch->setOrderIds($order_ids);

$api_response = $order_api->getOrdersBatch($order_batch, $expansion);

if ($api_response->getError() != null) {
    error_log($api_response->getError()->getDeveloperMessage());
    error_log($api_response->getError()->getUserMessage());
    exit();
}

$orders = $api_response->getOrders();
if(sizeof($orders) == 0){
    error_log("There were no orders returned by this query.");
}

// do something with the orders.  for this example, we're just accessing many properties as illustration.
foreach ($orders as $order) {
    $summary = $order->getSummary();
    $actual_shipping_cost = is_null($summary->getActualShipping()) ? 0 : $summary->getActualShipping()->getLocalized();

    $currentStage = $order->getCurrentStage();
    $s_addr = $order->getShipping();
    $trackingNumbers = $s_addr->getTrackingNumbers();
    foreach ($trackingNumbers as $tnum) {
        // do something with tracking number here.
    }
    $sfname = $s_addr -> getFirstName();
    $slname = $s_addr -> getLastName();
    $saddress1 = $s_addr->getAddress1();
    $saddress2 = $s_addr->getAddress2();
    $scity = $s_addr->getCity();
    $sregion = $s_addr->getStateRegion();
    $sccode = $s_addr->getCountryCode();
    $spcode = $s_addr->getPostalCode();
    $sdayphone = $s_addr->getDayPhone();
    $shipping_method = $s_addr->getShippingMethod();

    $b_addr = $order->getBilling();
    $b_addr->getAddress1();
    $b_addr->getAddress2();
    $b_addr->getCity();
    $b_addr->getStateRegion();
    $b_addr->getCountryCode();
    $b_addr->getPostalCode();
    $bemail = $b_addr->getEmail(); // email is located on the billing object.

    // here is how to access the items
    $items = $order->getItems();
    foreach ($items as $item) {
        $qty = $item->getQuantity();
        $itemId = $item->getMerchantItemId();
        $description = $item->getDescription();
        $cost = $item->getCost();
        $cost->getLocalized(); // cost as float.
        $real_cost = $cost->getLocalizedFormatted(); // cost with symbols.
    }
}

// this could get verbose depending on the size of your batch ...
echo '<html lang="en"><body><pre>';
var_dump($orders);
echo '</pre></body></html>';

from ultracart.apis import OrderApi
from ultracart.model.order_query_batch import OrderQueryBatch
from pprint import pprint
from samples import api_client

api_instance = OrderApi(api_client())

## This example shows how to request up to 500 orders by passing in their order ids.

# expansion = "item,summary,billing,shipping,shipping.tracking_number_details"
expansion = 'auto_order,billing,channel_partner,checkout,coupon,edi,gift,gift_certificate,internal,item,payment,payment.transaction,point_of_sale,properties,quote,shipping,shipping.tracking_number_details,summary,taxes,utms'
## see www.ultracart.com/api/ for all the expansion fields available (this list below may become stale)
##
## Possible Order Expansions:
## affiliate           affiliate.ledger                    auto_order
## billing             channel_partner                     checkout
## coupon              customer_profile                    digital_order
## edi                 fraud_score                         gift
## gift_certificate    internal                            item
## linked_shipment     marketing                           payment
## payment.transaction quote                               salesforce
## shipping            shipping.tracking_number_details    summary
## taxes
##

order_batch = OrderQueryBatch()
order_batch.limit = 500
order_batch.limit = 500
order_batch.query_target = "cache"
order_batch.order_ids = [
    'DEMO-0009103110',
    'DEMO-0009103116',
    'DEMO-0009103121',
    'DEMO-0009103416',
    'DEMO-0009103422',
    'DEMO-0009103423',
    'DEMO-0009103424',
    'DEMO-0009103426',
    'DEMO-0009103427'
]

api_response = api_instance.get_orders_batch(order_batch=order_batch, expand=expansion)
orders = api_response.orders

# pprint(orders)
for order in orders:
    pprint(order)
print(f"{len(orders)} were returned.")
# frozen_string_literal: true

require 'ultracart_api'
require_relative '../constants'

=begin
 This method is useful when you need to query a defined set of orders and would like to avoid querying them
 one at a time.
=end

# Possible Order Expansions:
# affiliate           affiliate.ledger                    auto_order
# billing             channel_partner                     checkout
# coupon              customer_profile                    digital_order
# edi                 fraud_score                         gift
# gift_certificate    internal                            item
# linked_shipment     marketing                           payment
# payment.transaction quote                               salesforce
# shipping            shipping.tracking_number_details    summary
# taxes

# Initialize API
order_api = UltracartClient::OrderApi.new_using_api_key(Constants::API_KEY)

# Define expansion
expansion = "item,summary,billing,shipping,shipping.tracking_number_details"

# Prepare order batch
order_batch = UltracartClient::OrderQueryBatch.new(
  order_ids: ['DEMO-0009104390', 'DEMO-0009104391', 'DEMO-0009104392']
)

# Retrieve orders
begin
  api_response = order_api.get_orders_batch(
    order_query_batch: order_batch,
    opts: { '_expand' => expansion }
  )

  # Check for errors
  if api_response.error
    warn "Developer Message: #{api_response.error.developer_message}"
    warn "User Message: #{api_response.error.user_message}"
    exit 1
  end

  # Get orders
  orders = api_response.orders

  if orders.empty?
    warn "There were no orders returned by this query."
    exit
  end

  # Process each order
  orders.each do |order|
    # Access summary
    summary = order.summary
    actual_shipping_cost = summary.actual_shipping&.localized || 0

    # Access shipping information
    s_addr = order.shipping
    tracking_numbers = s_addr.tracking_numbers || []
    tracking_numbers.each do |tnum|
      # Do something with tracking number here
    end

    # Extract shipping address details
    sfname = s_addr.first_name
    slname = s_addr.last_name
    saddress1 = s_addr.address1
    saddress2 = s_addr.address2
    scity = s_addr.city
    sregion = s_addr.state_region
    sccode = s_addr.country_code
    spcode = s_addr.postal_code
    sdayphone = s_addr.day_phone
    shipping_method = s_addr.shipping_method

    # Access billing information
    b_addr = order.billing
    b_addr.address1
    b_addr.address2
    b_addr.city
    b_addr.state_region
    b_addr.country_code
    b_addr.postal_code
    bemail = b_addr.email # email is located on the billing object

    # Process order items
    items = order.items || []
    items.each do |item|
      qty = item.quantity
      item_id = item.merchant_item_id
      description = item.description
      cost = item.cost
      cost.localized # cost as float
      real_cost = cost.localized_formatted # cost with symbols
    end
  end

  # Output orders
  p orders

rescue StandardError => e
  warn "An error occurred: #{e.message}"
  warn e.backtrace.join("\n")
end
import {orderApi} from '../api';
import {
    Order,
    OrdersResponse,
    OrderQueryBatch,
    OrderItem,
    OrderShipping,
    OrderSummary
} from 'ultracart_rest_api_v2_typescript';

/**
 * This method is useful when you need to query a defined set of orders and would like to avoid querying them
 * one at a time.
 */
export async function execute(): Promise<void> {
    // The expansion variable instructs UltraCart how much information to return.
    // see www.ultracart.com/api/ for all the expansion fields available (this list below may become stale)
    /*
    Possible Order Expansions:
    affiliate           affiliate.ledger                    auto_order
    billing             channel_partner                     checkout
    coupon              customer_profile                    digital_order
    edi                 fraud_score                         gift
    gift_certificate    internal                            item
    linked_shipment     marketing                           payment
    payment.transaction quote                               salesforce
    shipping            shipping.tracking_number_details    summary
    taxes
    */
    const expansion = "item,summary,billing,shipping,shipping.tracking_number_details";

    const orderBatch: OrderQueryBatch = {
        order_ids: ["DEMO-0009104390", "DEMO-0009104391", "DEMO-0009104392"]
    };

    try {
        const apiResponse: OrdersResponse = await orderApi.getOrdersBatch({
            orderBatch: orderBatch,
            expand: expansion
        });

        if (apiResponse.error) {
            console.error(apiResponse.error.developer_message);
            console.error(apiResponse.error.user_message);
            process.exit(1);
        }

        const orders: Order[] = apiResponse.orders || [];

        if (orders.length === 0) {
            console.error("There were no orders returned by this query.");
        }

        // do something with the orders. for this example, we're just accessing many properties as illustration.
        for (const order of orders) {
            const summary: OrderSummary | undefined = order.summary;
            const actualShippingCost = summary?.actual_shipping?.localized ?? 0;

            const currentStage = order.current_stage;
            const sAddr: OrderShipping | undefined = order.shipping;
            const trackingNumbers = sAddr?.tracking_numbers || [];

            for (const trackingNumber of trackingNumbers) {
                // do something with tracking number here.
            }

            // Here's how to access the shipping information. Do something with the variables.
            const sfname = order.shipping?.first_name;
            const slname = order.shipping?.last_name;
            const saddress1 = order.shipping?.address1;
            const saddress2 = order.shipping?.address2;
            const scity = order.shipping?.city;
            const sregion = order.shipping?.state_region;
            const sccode = order.shipping?.country_code;
            const spcode = order.shipping?.postal_code;
            const sdayphone = order.shipping?.day_phone;
            const shippingMethod = order.shipping?.shipping_method;

            // Here's how to access the billing information. Do something with the variables.
            const billingAddress1 = order.billing?.address1;
            const billingAddress2 = order.billing?.address2;
            const billingCity = order.billing?.city;
            const billingStateRegion = order.billing?.state_region;
            const billingCountryCode = order.billing?.country_code;
            const billingPostalCode = order.billing?.postal_code;
            const email = order.billing?.email; // email is located on the billing object.

            // here is how to access the items
            const items: OrderItem[] = order.items || [];
            for (const item of items) {
                const qty = item.quantity;
                const itemId = item.merchant_item_id;
                const description = item.description;
                const cost = item.cost?.localized;
                const costFormatted = item.cost?.localized_formatted; // cost with symbols.
            }
        }

        // this could get verbose depending on the size of your batch ...
        for (const order of orders) {
            console.log(JSON.stringify(order, null, 2));
        }
    } catch (error) {
        console.error('Error fetching orders batch:', error);
    }
}

Retrieve orders by query

Permissions:
  • order_read

Produces: application/json
post
/order/orders/query

Retrieves a group of orders from the account based on a query object. If no parameters are specified, the API call will fail with a bad request error. Always specify some parameters to limit the scope of the orders returned to ones you are truly interested in. You will need to make multiple API calls in order to retrieve the entire result set since this API performs result set pagination.

SDK Function Name: getOrdersByQuery

Parameters
Parameter Description Location Data Type Required
order_query Order query body OrderQuery required
_limit The maximum number of records to return on this one API call. (Maximum 200)
Default: 100
query integer optional
_offset Pagination of the record set. Offset is a zero based index.
Default: 0
query integer optional
_sort The sort order of the orders. See Sorting documentation for examples of using multiple values and sorting by ascending and descending.
Allowed Values
  • order_id
  • shipping.company
  • shipping.first_name
  • shipping.last_name
  • shipping.city
  • shipping.state_region
  • shipping.postal_code
  • shipping.country_code
  • billing.phone
  • billing.email
  • billing.cc_email
  • billing.company
  • billing.first_name
  • billing.last_name
  • billing.city
  • billing.state
  • billing.postal_code
  • billing.country_code
  • creation_dts
  • payment.payment_dts
  • checkout.screen_branding_theme_code
  • channel_partner.channel_partner_code
  • channel_partner.channel_partner_order_id
query string optional
_expand The object expansion to perform on the result. query string optional
Responses
Status Code Reason Response Model
200
Successful response OrdersResponse
400
Bad Request 400
401
Unauthorized 401
410
Authorized Application Disabled 410
429
Too Many Requests 429
500
Server Side 500
using System;
using System.Collections.Generic;
using System.Linq;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;
using Newtonsoft.Json;

namespace SdkSample.order
{
    public class GetOrdersByQuery
    {
        /*
         * This example illustrates how to query the OrderQuery object to select a range of records. It uses a subroutine
         * to aggregate the records that span multiple API calls. This example illustrates a work-around to selecting
         * all rejected orders. Because the UltraCart SDK does not have a way to query orders based on whether they
         * were rejected, we can instead query based on the rejected_dts, which is null if the order is not rejected.
         * So we will simply use a large time frame to ensure we query all rejections.
         */
        public static void Execute()
        {
            OrderApi orderApi = new OrderApi(Constants.ApiKey);

            List<Order> orders = new List<Order>();

            int iteration = 1;
            int offset = 0;
            int limit = 200;
            bool moreRecordsToFetch = true;

            while (moreRecordsToFetch)
            {
                Console.WriteLine($"executing iteration {iteration}<br>");
                List<Order> chunkOfOrders = GetOrderChunk(orderApi, offset, limit);
                orders.AddRange(chunkOfOrders);
                offset = offset + limit;
                moreRecordsToFetch = chunkOfOrders.Count == limit;
                iteration++;
            }

            foreach (Order order in orders)
            {
                Console.WriteLine(JsonConvert.SerializeObject(order, new JsonSerializerSettings { Formatting = Formatting.Indented}));                
            }            
        }

        private static List<Order> GetOrderChunk(OrderApi orderApi, int offset, int limit)
        {
            string expansion = "item,summary,billing,shipping,shipping.tracking_number_details";
            // see www.ultracart.com/api/ for all the expansion fields available (this list below may become stale)
            /*
            Possible Order Expansions:
            affiliate           affiliate.ledger                    auto_order
            billing             channel_partner                     checkout
            coupon              customer_profile                    digital_order
            edi                 fraud_score                         gift
            gift_certificate    internal                            item
            linked_shipment     marketing                           payment
            payment.transaction quote                               salesforce
            shipping            shipping.tracking_number_details    summary
            taxes
            */

            OrderQuery query = new OrderQuery();
            // Uncomment the next two lines to retrieve a single order. But there are simpler methods to do that.
            // string orderId = "DEMO-0009104390";
            // orderQuery.OrderId = orderId;

            string beginDts = DateTime.Now.AddDays(-2000).ToString("yyyy-MM-dd") + "T00:00:00+00:00"; // yes, that 2,000 days.
            string endDts = DateTime.Now.ToString("yyyy-MM-dd") + "T00:00:00+00:00";
            Console.Error.WriteLine(beginDts);
            Console.Error.WriteLine(endDts);

            query.RefundDateBegin = beginDts;
            query.RefundDateEnd = endDts;

            OrdersResponse apiResponse = orderApi.GetOrdersByQuery(query, limit, offset, null, expansion);
            if (apiResponse.Orders != null)
            {
                return apiResponse.Orders.ToList();
            }
            return new List<Order>();
        }
    }
}
package order;

import com.ultracart.admin.v2.OrderApi;
import com.ultracart.admin.v2.models.Order;
import com.ultracart.admin.v2.models.OrderQuery;
import com.ultracart.admin.v2.models.OrdersResponse;
import com.ultracart.admin.v2.util.ApiException;
import common.Constants;

import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;

public class GetOrdersByQuery {
    /*
     * This example illustrates how to query the OrderQuery object to select a range of records. It uses a subroutine
     * to aggregate the records that span multiple API calls. This example illustrates a work-around to selecting
     * all rejected orders. Because the UltraCart SDK does not have a way to query orders based on whether they
     * were rejected, we can instead query based on the rejected_dts, which is null if the order is not rejected.
     * So we will simply use a large time frame to ensure we query all rejections.
     */
    public static void execute() throws ApiException {
        OrderApi orderApi = new OrderApi(Constants.API_KEY);

        List<Order> orders = new ArrayList<>();

        int iteration = 1;
        int offset = 0;
        int limit = 200;
        boolean moreRecordsToFetch = true;

        while (moreRecordsToFetch) {
            System.out.println("executing iteration " + iteration + "<br>");
            List<Order> chunkOfOrders = getOrderChunk(orderApi, offset, limit);
            orders.addAll(chunkOfOrders);
            offset = offset + limit;
            moreRecordsToFetch = chunkOfOrders.size() == limit;
            iteration++;
        }

        for (Order order : orders) {
            System.out.println(order.toString());
        }
    }

    private static List<Order> getOrderChunk(OrderApi orderApi, int offset, int limit) throws ApiException {
        String expansion = "item,summary,billing,shipping,shipping.tracking_number_details";
        // see www.ultracart.com/api/ for all the expansion fields available (this list below may become stale)
        /*
        Possible Order Expansions:
        affiliate           affiliate.ledger                    auto_order
        billing             channel_partner                     checkout
        coupon              customer_profile                    digital_order
        edi                 fraud_score                         gift
        gift_certificate    internal                            item
        linked_shipment     marketing                           payment
        payment.transaction quote                               salesforce
        shipping            shipping.tracking_number_details    summary
        taxes
        */

        OrderQuery query = new OrderQuery();
        // Uncomment the next two lines to retrieve a single order. But there are simpler methods to do that.
        // String orderId = "DEMO-0009104390";
        // orderQuery.setOrderId(orderId);

        String beginDts = Instant.now().toString();
        String endDts = Instant.now().minus(2000, ChronoUnit.DAYS).toString();
        System.err.println(beginDts);
        System.err.println(endDts);

        query.setRefundDateBegin(beginDts);
        query.setRefundDateEnd(endDts);

        OrdersResponse apiResponse = orderApi.getOrdersByQuery(query, limit, offset, null, expansion);
        if (apiResponse.getOrders() != null) {
            return apiResponse.getOrders();
        }
        return new ArrayList<>();
    }
}
import {DateTime} from 'luxon';
import {orderApi} from '../api.js';

/**
 * This example illustrates how to query the OrderQuery object to select a range of records. It uses a subroutine
 * to aggregate the records that span multiple API calls. This example illustrates a work-around to selecting
 * all rejected orders. Because the UltraCart SDK does not have a way to query orders based on whether they
 * were rejected, we can instead query based on the rejected_dts, which is null if the order is not rejected.
 * So we will simply use a large time frame to ensure we query all rejections.
 */
export class GetOrdersByQuery {
    /**
     * Execute the order query and retrieve orders
     */
    static async execute() {
        const orders = [];

        let iteration = 1;
        let offset = 0;
        const limit = 200;
        let moreRecordsToFetch = true;

        while (moreRecordsToFetch) {
            console.log(`executing iteration ${iteration}<br>`);
            const chunkOfOrders = await this.getOrderChunk(offset, limit);
            orders.push(...chunkOfOrders);
            offset = offset + limit;
            moreRecordsToFetch = chunkOfOrders.length === limit;
            iteration++;
        }

        orders.forEach(order => {
            console.log(JSON.stringify(order, null, 2));
        });
    }

    /**
     * Retrieve a chunk of orders based on query parameters
     * @param offset - The offset for pagination
     * @param limit - The number of records to retrieve
     * @returns A promise resolving to a list of orders
     */
    static async getOrderChunk(offset, limit) {
        const expansion = "item,summary,billing,shipping,shipping.tracking_number_details";
        // see www.ultracart.com/api/ for all the expansion fields available (this list below may become stale)
        /*
        Possible Order Expansions:
        affiliate           affiliate.ledger                    auto_order
        billing             channel_partner                     checkout
        coupon              customer_profile                    digital_order
        edi                 fraud_score                         gift
        gift_certificate    internal                            item
        linked_shipment     marketing                           payment
        payment.transaction quote                               salesforce
        shipping            shipping.tracking_number_details    summary
        taxes
        */

        const query = {};
        // Uncomment the next two lines to retrieve a single order. But there are simpler methods to do that.
        // const orderId = "DEMO-0009104390";
        // query.orderId = orderId;

        const beginDts = DateTime.now().minus({days: 2000}).toFormat("yyyy-MM-dd") + "T00:00:00+00:00"; // yes, that 2,000 days.
        const endDts = DateTime.now().toFormat("yyyy-MM-dd") + "T00:00:00+00:00";
        console.error(beginDts);
        console.error(endDts);

        query.refund_date_begin = beginDts;
        query.refund_date_end = endDts;

        const apiResponse = await new Promise((resolve, reject) => {
            orderApi.getOrdersByQuery(
                query,
                {
                    _limit: limit,
                    _offset: offset,
                    _expand: expansion
                }
                , function (error, data, response) {
                    if (error) {
                        reject(error);
                    } else {
                        resolve(data);
                    }
                });
        });

        return apiResponse.orders ?? [];
    }
}

// Example usage
// GetOrdersByQuery.execute().catch(console.error);
<?php

set_time_limit(3000); // pull all orders could take a long time.
ini_set('max_execution_time', 3000);
ini_set('display_errors', 1);

/*
 * This example illustrates how to query the OrderQuery object to select a range of records.  It uses a subroutine
 * to aggregate the records that span multiple API calls.  This example illustrates a work-around to selecting
 * all rejected orders.  Because the UltraCart SDK does not have a way to query orders based on whether they
 * were rejected, we can instead query based on the rejected_dts, which is null if the order is not rejected.
 * So we will simply use a large time frame to ensure we query all rejections.
 */

use ultracart\v2\api\OrderApi;
use ultracart\v2\models\OrderQuery;

require_once '../vendor/autoload.php';
require_once '../constants.php';


$order_api = ultracart\v2\api\OrderApi::usingApiKey(Constants::API_KEY);


function getOrderChunk(OrderApi $order_api, int $offset, int $limit): array
{
    $expansion = "item,summary,billing,shipping,shipping.tracking_number_details";
    // see www.ultracart.com/api/ for all the expansion fields available (this list below may become stale)
    /*
    Possible Order Expansions:
    affiliate           affiliate.ledger                    auto_order
    billing             channel_partner                     checkout
    coupon              customer_profile                    digital_order
    edi                 fraud_score                         gift
    gift_certificate    internal                            item
    linked_shipment     marketing                           payment
    payment.transaction quote                               salesforce
    shipping            shipping.tracking_number_details    summary
    taxes
    */

    $query = new OrderQuery();
    // Uncomment the next two lines to retrieve a single order.  But there are simpler methods to do that.
    // $order_id = "DEMO-0009104390";
    // $order_query->setOrderId($order_id);

    $begin_dts = date('Y-m-d', strtotime('-2000 days')) . "T00:00:00+00:00"; // yes, that 2,000 days.
    $end_dts = date('Y-m-d', time()) . "T00:00:00+00:00";
    error_log($begin_dts);
    error_log($end_dts);

    $query->setRefundDateBegin($begin_dts);
    $query->setRefundDateEnd($end_dts);

    $api_response = $order_api->getOrdersByQuery($query, $limit, $offset, null, $expansion);
    if($api_response->getOrders() != null){
        return $api_response->getOrders();
    }
    return [];
}

$orders = [];

$iteration = 1;
$offset = 0;
$limit = 200;
$more_records_to_fetch = true;

while( $more_records_to_fetch ){

    echo "executing iteration " . $iteration . '<br>';
    $chunk_of_orders = getOrderChunk($order_api, $offset, $limit);
    $orders = array_merge($orders, $chunk_of_orders);
    $offset = $offset + $limit;
    $more_records_to_fetch = count($chunk_of_orders) == $limit;
    $iteration++;

}

// this could get verbose...
echo '<html lang="en"><body><pre>';
var_dump($orders);
echo '</pre></body></html>';

from ultracart.apis import OrderApi
from ultracart.model.order_query import OrderQuery
from ultracart.model.order import Order
from ultracart.rest import ApiException
from pprint import pprint
from samples import api_client
from datetime import datetime, timedelta
import time

start_time = time.time()
api_instance = OrderApi(api_client())

## This example illustrates how to query the OrderQuery object to select a range of records.  It uses a subroutine
## to aggregate the records that span multiple API calls.  This specific example illustrates a work-around to selecting
## all rejected orders.  Because the UltraCart SDK does not have a way to query orders based on whether they
## were rejected, we can instead query based on the rejected_dts, which is null if the order is not rejected.
## So we will simply use a large time frame to ensure we query all rejections.

iteration = 1
offset = 0
limit = 1000
more_records_to_fetch = True
orders = []
date_field = 'payment'

def get_order_chunk():
    # expansion = "item,summary,billing,shipping,shipping.tracking_number_details"
    expansion = 'auto_order,billing,channel_partner,checkout,coupon,edi,gift,gift_certificate,internal,item,payment,payment.transaction,point_of_sale,properties,quote,shipping,shipping.tracking_number_details,summary,taxes,utms'
    ## see www.ultracart.com/api/ for all the expansion fields available (this list below may become stale)
    ##
    ## Possible Order Expansions:
    ## affiliate           affiliate.ledger                    auto_order
    ## billing             channel_partner                     checkout
    ## coupon              customer_profile                    digital_order
    ## edi                 fraud_score                         gift
    ## gift_certificate    internal                            item
    ## linked_shipment     marketing                           payment
    ## payment.transaction quote                               salesforce
    ## shipping            shipping.tracking_number_details    summary
    ## taxes
    ##

    query = OrderQuery()
    ## Uncomment the next line to retrieve a single order.  But there are simpler methods to retrieve a single order than getOrdersByQuery
    ## order_query.order_id = "DEMO-0009104390"

    now = datetime.now()
    six_hours_ago = now - timedelta(hours=6)
    # begin_dts = datetime.strptime('2000-01-01', '%Y-%m-%d').astimezone().isoformat('T', 'milliseconds')
    begin_dts = six_hours_ago.astimezone().isoformat('T', 'milliseconds')

    end_dts = datetime.now().astimezone().isoformat('T', 'milliseconds')
    print(f"Date range: {begin_dts} to {end_dts}")

    if date_field == 'reject':
        query.refund_date_begin = begin_dts
        query.refund_date_end = end_dts
    elif date_field == 'shipment':
        query.shipment_date_begin = begin_dts
        query.shipment_date_end = end_dts
    else:
        query.payment_date_begin = begin_dts
        query.payment_date_end = end_dts

    query.query_target = 'cache'  # cache is much faster, but may be missing the last few minutes of orders.

    api_response = api_instance.get_orders_by_query(order_query=query, limit=limit, offset=offset, expand=expansion, sort='+shipping.state_region,-shipping.city')
    if api_response.orders is not None:
        return api_response.orders
    return []


while more_records_to_fetch:
    print(f"executing iteration {iteration} ")
    chunk_of_orders = get_order_chunk()
    orders.extend(chunk_of_orders)
    offset = offset + limit
    more_records_to_fetch = len(chunk_of_orders) == limit
    iteration = iteration + 1

# pprint(orders)
for order in orders:
    shipping = getattr(order, 'shipping')
    # pprint(shipping)
    print(f"{getattr(shipping, 'state_region', 'NULL')} {getattr(shipping, 'city', 'NULL')} {order.order_id}")
    # pprint(order)
print(f"{len(orders)} were returned.")

# pprint(orders[0])

end_time = time.time()
elapsed_time = end_time - start_time
print(f"The {date_field} date range query took {elapsed_time} seconds to execute.")
# frozen_string_literal: true

require 'ultracart_api'
require_relative '../constants'
require 'date'

# Increase script execution time limit
Process.setrlimit(Process::RLIMIT_CPU, 3000)

=begin
 This example illustrates how to query the OrderQuery object to select a range of records.  It uses a subroutine
 to aggregate the records that span multiple API calls.  This example illustrates a work-around to selecting
 all rejected orders.  Because the UltraCart SDK does not have a way to query orders based on whether they
 were rejected, we can instead query based on the rejected_dts, which is null if the order is not rejected.
 So we will simply use a large time frame to ensure we query all rejections.
=end

def get_order_chunk(order_api, offset, limit)
  # Possible Order Expansions:
  # affiliate           affiliate.ledger                    auto_order
  # billing             channel_partner                     checkout
  # coupon              customer_profile                    digital_order
  # edi                 fraud_score                         gift
  # gift_certificate    internal                            item
  # linked_shipment     marketing                           payment
  # payment.transaction quote                               salesforce
  # shipping            shipping.tracking_number_details    summary
  # taxes

  expansion = "item,summary,billing,shipping,shipping.tracking_number_details"

  # Uncomment the next two lines to retrieve a single order.  But there are simpler methods to do that.
  # order_id = "DEMO-0009104390"
  # order_query.order_id = order_id

  # Create query with a very large date range
  begin_dts = (Date.today - 2000).strftime('%Y-%m-%d') + "T00:00:00+00:00"
  end_dts = Date.today.strftime('%Y-%m-%d') + "T00:00:00+00:00"

  # Log date range (Ruby equivalent of PHP's error_log)
  warn begin_dts
  warn end_dts

  # Prepare query
  query = UltracartClient::OrderQuery.new(
    refund_date_begin: begin_dts,
    refund_date_end: end_dts
  )

  # Make API call
  api_response = order_api.get_orders_by_query(
    order_query: query,
    opts: {
      '_limit' => limit,
      '_offset' => offset,
      '_expand' => expansion
    }
  )

  # Return orders or empty array
  api_response.orders || []
end

# Initialize API
order_api = UltracartClient::OrderApi.new_using_api_key(Constants::API_KEY)

# Initialize variables for order retrieval
orders = []
iteration = 1
offset = 0
limit = 200
more_records_to_fetch = true

# Retrieve orders in chunks
while more_records_to_fetch
  puts "executing iteration #{iteration}"

  chunk_of_orders = get_order_chunk(order_api, offset, limit)
  orders.concat(chunk_of_orders)

  offset += limit
  more_records_to_fetch = chunk_of_orders.length == limit
  iteration += 1
end

# Output orders
p orders
import {DateTime} from 'luxon';
import {orderApi} from '../api';
import {
    OrderQuery,
    OrdersResponse,
    Order
} from 'ultracart_rest_api_v2_typescript';

/**
 * This example illustrates how to query the OrderQuery object to select a range of records. It uses a subroutine
 * to aggregate the records that span multiple API calls. This example illustrates a work-around to selecting
 * all rejected orders. Because the UltraCart SDK does not have a way to query orders based on whether they
 * were rejected, we can instead query based on the rejected_dts, which is null if the order is not rejected.
 * So we will simply use a large time frame to ensure we query all rejections.
 */
export class GetOrdersByQuery {
    /**
     * Execute the order query and retrieve orders
     */
    public static async execute(): Promise<void> {
        const orders: Order[] = [];

        let iteration = 1;
        let offset = 0;
        const limit = 200;
        let moreRecordsToFetch = true;

        while (moreRecordsToFetch) {
            console.log(`executing iteration ${iteration}<br>`);
            const chunkOfOrders = await this.getOrderChunk(offset, limit);
            orders.push(...chunkOfOrders);
            offset = offset + limit;
            moreRecordsToFetch = chunkOfOrders.length === limit;
            iteration++;
        }

        orders.forEach(order => {
            console.log(JSON.stringify(order, null, 2));
        });
    }

    /**
     * Retrieve a chunk of orders based on query parameters
     * @param offset - The offset for pagination
     * @param limit - The number of records to retrieve
     * @returns A promise resolving to a list of orders
     */
    private static async getOrderChunk(offset: number, limit: number): Promise<Order[]> {
        const expansion = "item,summary,billing,shipping,shipping.tracking_number_details";
        // see www.ultracart.com/api/ for all the expansion fields available (this list below may become stale)
        /*
        Possible Order Expansions:
        affiliate           affiliate.ledger                    auto_order
        billing             channel_partner                     checkout
        coupon              customer_profile                    digital_order
        edi                 fraud_score                         gift
        gift_certificate    internal                            item
        linked_shipment     marketing                           payment
        payment.transaction quote                               salesforce
        shipping            shipping.tracking_number_details    summary
        taxes
        */

        const query: OrderQuery = {};
        // Uncomment the next two lines to retrieve a single order. But there are simpler methods to do that.
        // const orderId = "DEMO-0009104390";
        // query.orderId = orderId;

        const beginDts = DateTime.now().minus({days: 2000}).toFormat("yyyy-MM-dd") + "T00:00:00+00:00"; // yes, that 2,000 days.
        const endDts = DateTime.now().toFormat("yyyy-MM-dd") + "T00:00:00+00:00";
        console.error(beginDts);
        console.error(endDts);

        query.refund_date_begin = beginDts;
        query.refund_date_end = endDts;

        const apiResponse: OrdersResponse = await orderApi.getOrdersByQuery({
            orderQuery: query,
            limit: limit,
            offset: offset,
            expand: expansion
        });

        return apiResponse.orders ?? [];
    }
}

// Example usage
GetOrdersByQuery.execute().catch(console.error);

Retrieve an order using a token

Permissions:
  • order_read

Produces: application/json
post
/order/orders/token

Retrieves a single order using the specified order token.

SDK Function Name: getOrderByToken

Parameters
Parameter Description Location Data Type Required
order_by_token_query Order by token query body OrderByTokenQuery required
_expand The object expansion to perform on the result. See documentation for examples query string optional
Responses
Status Code Reason Response Model
200
Successful response OrderResponse
400
Bad Request 400
401
Unauthorized 401
410
Authorized Application Disabled 410
429
Too Many Requests 429
500
Server Side 500
using System;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;
using Newtonsoft.Json;

namespace SdkSample.order
{
    public class GetOrderByToken
    {
        /*
         * OrderApi.getOrderByToken() was created for use within a custom thank-you page.  The built-in StoreFront
         * thank you page displays the customer receipt and allows for unlimited customization.  However, many
         * merchants wish to process the receipt page on their own servers to do custom processing.
         *
         * See: https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1377199/Custom+Thank+You+Page+URL
         *
         * When setting up a custom thank-you url in the StoreFronts, you will provide a query parameter that will hold
         * this order token.  You many extract that from the Request.QueryString object, then turn around and call getOrderByToken
         * to get the order object.
         */
        public static void Execute()
        {
            OrderApi orderApi = new OrderApi(Constants.ApiKey);

            // The expansion variable instructs UltraCart how much information to return.  The order object is large and
            // while it's easily manageable for a single order, when querying thousands of orders, is useful to reduce
            // payload size.
            // see www.ultracart.com/api/ for all the expansion fields available (this list below may become stale)
            /*
            Possible Order Expansions:
            affiliate           affiliate.ledger                    auto_order
            billing             channel_partner                     checkout
            coupon              customer_profile                    digital_order
            edi                 fraud_score                         gift
            gift_certificate    internal                            item
            linked_shipment     marketing                           payment
            payment.transaction quote                               salesforce
            shipping            shipping.tracking_number_details    summary
            taxes
            */

            string expansion = "billing,checkout,coupon,customer_profile,item,payment,shipping,summary,taxes";

            // the token will be in a Request.QueryString parameter defined by you within your storefront.
            // StoreFront -> Privacy and Tracking -> Advanced -> CustomThankYouUrl
            // Example would be: www.mysite.com/receipt.aspx?OrderToken=[OrderToken]

            // Assuming this is an ASP.NET application and we're using Request.QueryString
            // string orderToken = Request.QueryString["OrderToken"];
            string orderToken = "DEMO:UZBOGywSKKwD2a5wx5JwmkwyIPNsGrDHNPiHfxsi0iAEcxgo9H74J/l6SR3X8g=="; // this won't work for you...
            // to generate an order token manually for testing, set generateOrderToken.cs
            // TODO (for you, the merchant): handle missing order token (perhaps this page somehow called by a search engine, etc).

            OrderByTokenQuery orderTokenQuery = new OrderByTokenQuery();
            orderTokenQuery.OrderToken = orderToken;
            OrderResponse apiResponse = orderApi.GetOrderByToken(orderTokenQuery, expansion);
            Order order = apiResponse.Order;

            Console.WriteLine(JsonConvert.SerializeObject(order, new JsonSerializerSettings { Formatting = Formatting.Indented}));
            
        }
    }
}
package order;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.ultracart.admin.v2.OrderApi;
import com.ultracart.admin.v2.models.*;
import com.ultracart.admin.v2.util.ApiException;

public class GetOrderByToken {
   /*
    * OrderApi.getOrderByToken() was created for use within a custom thank-you page.  The built-in StoreFront
    * thank you page displays the customer receipt and allows for unlimited customization.  However, many
    * merchants wish to process the receipt page on their own servers to do custom processing.
    *
    * See: https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1377199/Custom+Thank+You+Page+URL
    *
    * When setting up a custom thank-you url in the StoreFronts, you will provide a query parameter that will hold
    * this order token.  You many extract that from the Request.QueryString object, then turn around and call getOrderByToken
    * to get the order object.
    */
   public void execute() throws ApiException {
       OrderApi orderApi = new OrderApi(common.Constants.API_KEY);

       // The expansion variable instructs UltraCart how much information to return.  The order object is large and
       // while it's easily manageable for a single order, when querying thousands of orders, is useful to reduce
       // payload size.
       // see www.ultracart.com/api/ for all the expansion fields available (this list below may become stale)
       /*
       Possible Order Expansions:
       affiliate           affiliate.ledger                    auto_order
       billing             channel_partner                     checkout
       coupon              customer_profile                    digital_order
       edi                 fraud_score                         gift
       gift_certificate    internal                            item
       linked_shipment     marketing                           payment
       payment.transaction quote                               salesforce
       shipping            shipping.tracking_number_details    summary
       taxes
       */

       String expansion = "billing,checkout,coupon,customer_profile,item,payment,shipping,summary,taxes";

       // the token will be in a Request.QueryString parameter defined by you within your storefront.
       // StoreFront -> Privacy and Tracking -> Advanced -> CustomThankYouUrl
       // Example would be: www.mysite.com/receipt.jsp?OrderToken=[OrderToken]

       // Assuming this is a Java Servlet application and we're using request.getParameter
       // String orderToken = request.getParameter("OrderToken");
       String orderToken = "DEMO:UZBOGywSKKwD2a5wx5JwmkwyIPNsGrDHNPiHfxsi0iAEcxgo9H74J/l6SR3X8g=="; // this won't work for you...
       // to generate an order token manually for testing, set generateOrderToken.java
       // TODO (for you, the merchant): handle missing order token (perhaps this page somehow called by a search engine, etc).

       OrderByTokenQuery orderTokenQuery = new OrderByTokenQuery();
       orderTokenQuery.setOrderToken(orderToken);
       OrderResponse apiResponse = orderApi.getOrderByToken(orderTokenQuery, expansion);
       Order order = apiResponse.getOrder();

       Gson gson = new GsonBuilder().setPrettyPrinting().create();
       System.out.println(gson.toJson(order));
   }
}
import {orderApi} from '../api.js';

/**
 * OrderApi.getOrderByToken() was created for use within a custom thank-you page.  The built-in StoreFront
 * thank you page displays the customer receipt and allows for unlimited customization.  However, many
 * merchants wish to process the receipt page on their own servers to do custom processing.
 *
 * See: https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1377199/Custom+Thank+You+Page+URL
 *
 * When setting up a custom thank-you url in the StoreFronts, you will provide a query parameter that will hold
 * this order token.  You many extract that from the Request.QueryString object, then turn around and call getOrderByToken
 * to get the order object.
 */
export async function execute() {
    // The expansion variable instructs UltraCart how much information to return.  The order object is large and
    // while it's easily manageable for a single order, when querying thousands of orders, is useful to reduce
    // payload size.
    // see www.ultracart.com/api/ for all the expansion fields available (this list below may become stale)
    /*
    Possible Order Expansions:
    affiliate           affiliate.ledger                    auto_order
    billing             channel_partner                     checkout
    coupon              customer_profile                    digital_order
    edi                 fraud_score                         gift
    gift_certificate    internal                            item
    linked_shipment     marketing                           payment
    payment.transaction quote                               salesforce
    shipping            shipping.tracking_number_details    summary
    taxes
    */
    const expansion = "billing,checkout,coupon,customer_profile,item,payment,shipping,summary,taxes";

    // the token will be in a Request.QueryString parameter defined by you within your storefront.
    // StoreFront -> Privacy and Tracking -> Advanced -> CustomThankYouUrl
    // Example would be: www.mysite.com/receipt.aspx?OrderToken=[OrderToken]

    // Assuming this is collected from query parameters
    // TODO: Replace with actual method of obtaining order token
    const orderToken = "DEMO:UZBOGywSKKwD2a5wx5JwmkwyIPNsGrDHNPiHfxsi0iAEcxgo9H74J/l6SR3X8g=="; // this won't work for you...
    // to generate an order token manually for testing, set generateOrderToken.ts
    // TODO (for you, the merchant): handle missing order token (perhaps this page somehow called by a search engine, etc).

    const orderTokenQuery = {
        order_token: orderToken
    };

    try {
        const apiResponse = await new Promise((resolve, reject) => {
            orderApi.getOrderByToken(
                orderTokenQuery,
                {_expand: expansion}, function (error, data, response) {
                    if (error) {
                        reject(error);
                    } else {
                        resolve(data);
                    }
                });
        });

        const order = apiResponse.order;

        if (order) {
            console.log(JSON.stringify(order, null, 2));
        } else {
            console.log('No order found');
        }
    } catch (error) {
        console.error('Error fetching order:', error);
    }
}
<?php

/*
 * OrderApi.getOrderByToken() was created for use within a custom thank-you page.  The built-in StoreFront
 * thank you page displays the customer receipt and allows for unlimited customization.  However, many
 * merchants wish to process the receipt page on their own servers to do custom processing.
 *
 * See: https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1377199/Custom+Thank+You+Page+URL
 *
 * When setting up a custom thank-you url in the StoreFronts, you will provide a query parameter that will hold
 * this order token.  You many extract that from the $_GET object, then turn around and call getOrderByToken
 * to get the order object.
 */

require_once '../vendor/autoload.php';
require_once '../constants.php';

use ultracart\v2\api\OrderApi;
use \ultracart\v2\models\OrderByTokenQuery;

$order_api = OrderApi::usingApiKey(Constants::API_KEY);

// The expansion variable instructs UltraCart how much information to return.  The order object is large and
// while it's easily manageable for a single order, when querying thousands of orders, is useful to reduce
// payload size.
// see www.ultracart.com/api/ for all the expansion fields available (this list below may become stale)
/*
Possible Order Expansions:
affiliate           affiliate.ledger                    auto_order
billing             channel_partner                     checkout
coupon              customer_profile                    digital_order
edi                 fraud_score                         gift
gift_certificate    internal                            item
linked_shipment     marketing                           payment
payment.transaction quote                               salesforce
shipping            shipping.tracking_number_details    summary
taxes
*/

$expansion = "billing,checkout,coupon,customer_profile,item,payment,shipping,summary,taxes";

// the token will be in a $_GET parameter defined by you within your storefront.
// StoreFront -> Privacy and Tracking -> Advanced -> CustomThankYouUrl
// Example would be: www.mysite.com/receipt.php?orderToken=[OrderToken]

$order_token = $_GET['OrderToken'];
// $order_token = 'DEMO:UZBOGywSKKwD2a5wx5JwmkwyIPNsGrDHNPiHfxsi0iAEcxgo9H74J/l6SR3X8g=='; // this won't work for you...
// to generate an order token manually for testing, set generateOrderToken.php
// TODO (for you, the merchant): handle missing order token (perhaps this page somehow called by a search engine, etc).


$order_token_query = new OrderByTokenQuery();
$order_token_query->setOrderToken($order_token);
$api_response = $order_api->getOrderByToken($order_token_query, $expansion);
$order = $api_response->getOrder();

echo '<html lang="en"><body><pre>';
var_dump($order);
echo '</pre></body></html>';
from ultracart.apis import OrderApi
from ultracart.model.order_by_token_query import OrderByTokenQuery
from samples import api_client

# OrderApi.get_order_by_token() was created for use within a custom thank-you page.
# The built-in StoreFront thank-you page displays the customer receipt and allows for unlimited customization.
# However, many merchants wish to process the receipt page on their own servers to do custom processing.
#
# See: https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1377199/Custom+Thank+You+Page+URL
#
# When setting up a custom thank-you URL in the StoreFronts, you will provide a query parameter that will hold
# this order token. You may extract that from the request parameters and then call get_order_by_token()
# to get the order object.

# Create Order API instance
order_api = OrderApi(api_client())

# The expand variable instructs UltraCart how much information to return. The order object is large and
# while it's easily manageable for a single order, when querying thousands of orders, it is useful to reduce
# payload size.
# See www.ultracart.com/api/ for all the expansion fields available (this list below may become stale).
#
# Possible Order Expansions:
# affiliate           affiliate.ledger                    auto_order
# billing             channel_partner                     checkout
# coupon              customer_profile                    digital_order
# edi                 fraud_score                         gift
# gift_certificate    internal                            item
# linked_shipment     marketing                           payment
# payment.transaction quote                               salesforce
# shipping            shipping.tracking_number_details    summary
# taxes

expand = "billing,checkout,coupon,customer_profile,item,payment,shipping,summary,taxes"

# The token will be in a request parameter defined by you within your storefront.
# StoreFront -> Privacy and Tracking -> Advanced -> CustomThankYouUrl
# Example would be: www.mysite.com/receipt?orderToken=[OrderToken]

# TODO: Handle retrieving the order token from request parameters
order_token = "DEMO:UZBOGywSKKwD2a5wx5JwmkwyIPNsGrDHNPiHfxsi0iAEcxgo9H74J/l6SR3X8g=="  # Replace with actual order token

# To generate an order token manually for testing, refer to generate_order_token.py
# TODO: Handle missing order token (e.g., if this page is called incorrectly by a search engine, etc.)

order_token_query = OrderByTokenQuery(order_token=order_token)

# Retrieve order
api_response = order_api.get_order_by_token(order_token_query, expand=expand)

# Extract order details
order = api_response.order

# Print order details
print(order)

require 'ultracart_api'
require_relative '../constants'

# OrderApi.getOrderByToken() was created for use within a custom thank-you page.  The built-in StoreFront
# thank you page displays the customer receipt and allows for unlimited customization.  However, many
# merchants wish to process the receipt page on their own servers to do custom processing.
#
# See: https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1377199/Custom+Thank+You+Page+URL
#
# When setting up a custom thank-you url in the StoreFronts, you will provide a query parameter that will hold
# this order token.  You many extract that from the $_GET object, then turn around and call getOrderByToken
# to get the order object.
order_api = UltracartClient::OrderApi.new_using_api_key(Constants::API_KEY)

# The expansion variable instructs UltraCart how much information to return.  The order object is large and
# while it's easily manageable for a single order, when querying thousands of orders, is useful to reduce
# payload size.
# see www.ultracart.com/api/ for all the expansion fields available (this list below may become stale)
=begin
Possible Order Expansions:
affiliate           affiliate.ledger                    auto_order
billing             channel_partner                     checkout
coupon              customer_profile                    digital_order
edi                 fraud_score                         gift
gift_certificate    internal                            item
linked_shipment     marketing                           payment
payment.transaction quote                               salesforce
shipping            shipping.tracking_number_details    summary
taxes
=end

expansion = "billing,checkout,coupon,customer_profile,item,payment,shipping,summary,taxes"

# the token will be in a $_GET parameter defined by you within your storefront.
# StoreFront -> Privacy and Tracking -> Advanced -> CustomThankYouUrl
# Example would be: www.mysite.com/receipt.php?orderToken=[OrderToken]

# TODO: Replace with actual method of retrieving order token in Ruby
# For example, if using Rack or Rails, you might use params[:order_token]
order_token = 'DEMO:UZBOGywSKKwD2a5wx5JwmkwyIPNsGrDHNPiHfxsi0iAEcxgo9H74J/l6SR3X8g=='

# TODO (for you, the merchant): handle missing order token (perhaps this page somehow called by a search engine, etc).

begin
  opts = {
    '_expand' => expansion
  }

  api_response = order_api.get_order_by_token(order_token, opts)
  order = api_response.order

  # Using inspect instead of var_dump for Ruby-style object representation
  puts order.inspect
rescue StandardError => e
  puts "An error occurred: #{e.message}"
end
import {orderApi} from '../api';
import {
    OrderByTokenQuery,
    OrderResponse,
    Order
} from 'ultracart_rest_api_v2_typescript';

/**
 * OrderApi.getOrderByToken() was created for use within a custom thank-you page.  The built-in StoreFront
 * thank you page displays the customer receipt and allows for unlimited customization.  However, many
 * merchants wish to process the receipt page on their own servers to do custom processing.
 *
 * See: https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1377199/Custom+Thank+You+Page+URL
 *
 * When setting up a custom thank-you url in the StoreFronts, you will provide a query parameter that will hold
 * this order token.  You many extract that from the Request.QueryString object, then turn around and call getOrderByToken
 * to get the order object.
 */
export async function execute(): Promise<void> {
    // The expansion variable instructs UltraCart how much information to return.  The order object is large and
    // while it's easily manageable for a single order, when querying thousands of orders, is useful to reduce
    // payload size.
    // see www.ultracart.com/api/ for all the expansion fields available (this list below may become stale)
    /*
    Possible Order Expansions:
    affiliate           affiliate.ledger                    auto_order
    billing             channel_partner                     checkout
    coupon              customer_profile                    digital_order
    edi                 fraud_score                         gift
    gift_certificate    internal                            item
    linked_shipment     marketing                           payment
    payment.transaction quote                               salesforce
    shipping            shipping.tracking_number_details    summary
    taxes
    */
    const expansion = "billing,checkout,coupon,customer_profile,item,payment,shipping,summary,taxes";

    // the token will be in a Request.QueryString parameter defined by you within your storefront.
    // StoreFront -> Privacy and Tracking -> Advanced -> CustomThankYouUrl
    // Example would be: www.mysite.com/receipt.aspx?OrderToken=[OrderToken]

    // Assuming this is collected from query parameters
    // TODO: Replace with actual method of obtaining order token
    const orderToken = "DEMO:UZBOGywSKKwD2a5wx5JwmkwyIPNsGrDHNPiHfxsi0iAEcxgo9H74J/l6SR3X8g=="; // this won't work for you...
    // to generate an order token manually for testing, set generateOrderToken.ts
    // TODO (for you, the merchant): handle missing order token (perhaps this page somehow called by a search engine, etc).

    const orderTokenQuery: OrderByTokenQuery = {
        order_token: orderToken
    };

    try {
        const apiResponse: OrderResponse = await orderApi.getOrderByToken({
            orderByTokenQuery: orderTokenQuery,
            expand: expansion
        });

        const order: Order | undefined = apiResponse.order;

        if (order) {
            console.log(JSON.stringify(order, null, 2));
        } else {
            console.log('No order found');
        }
    } catch (error) {
        console.error('Error fetching order:', error);
    }
}

Generate an order token for a given order id

Permissions:
  • order_write

Produces: application/json
get
/order/orders/token/{order_id}

Retrieves a single order token for a given order id. The token can be used with the getOrderByToken API.

SDK Function Name: generateOrderToken

Parameters
Parameter Description Location Data Type Required
order_id The order id to generate a token for. path string required
Responses
Status Code Reason Response Model
200
Successful response OrderTokenResponse
400
Bad Request 400
401
Unauthorized 401
410
Authorized Application Disabled 410
429
Too Many Requests 429
500
Server Side 500
using System;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;

namespace SdkSample.order
{
    public class GenerateOrderToken
    {
        public static void Execute()
        {
            /*
             * This method generates a unique encrypted key for an Order.  This is useful if you wish to provide links for
             * customer orders without allowing someone to easily cycle through orders.  By requiring order tokens, you
             * control which orders are viewable with a public hyperlink.
             *
             * This method works in tandem with OrderApi.getOrderByToken()
             */

            OrderApi orderApi = new OrderApi(Constants.ApiKey);

            string orderId = "DEMO-0009104436";
            OrderTokenResponse orderTokenResponse = orderApi.GenerateOrderToken(orderId);
            string orderToken = orderTokenResponse.OrderToken;

            Console.WriteLine($"Order Token is: {orderToken}");

            /*
             * The token format will look something like this:
             * DEMO:UJZOGiIRLqgE3a10yp5wmEozLPNsGrDHNPiHfxsi0iAEcxgo9H74J/l6SR3X8g==
             */
        }
    }
}
package order;

import com.ultracart.admin.v2.OrderApi;
import com.ultracart.admin.v2.models.*;
import com.ultracart.admin.v2.util.ApiException;

public class GenerateOrderToken {
   public void execute() throws ApiException {
       /*
        * This method generates a unique encrypted key for an Order.  This is useful if you wish to provide links for
        * customer orders without allowing someone to easily cycle through orders.  By requiring order tokens, you
        * control which orders are viewable with a public hyperlink.
        *
        * This method works in tandem with OrderApi.getOrderByToken()
        */

       OrderApi orderApi = new OrderApi(common.Constants.API_KEY);

       String orderId = "DEMO-0009104436";
       OrderTokenResponse orderTokenResponse = orderApi.generateOrderToken(orderId);
       String orderToken = orderTokenResponse.getOrderToken();

       System.out.println("Order Token is: " + orderToken);

       /*
        * The token format will look something like this:
        * DEMO:UJZOGiIRLqgE3a10yp5wmEozLPNsGrDHNPiHfxsi0iAEcxgo9H74J/l6SR3X8g==
        */
   }
}
import {orderApi} from '../api.js';

export class GenerateOrderToken {
    /**
     * This method generates a unique encrypted key for an Order.  This is useful if you wish to provide links for
     * customer orders without allowing someone to easily cycle through orders.  By requiring order tokens, you
     * control which orders are viewable with a public hyperlink.
     *
     * This method works in tandem with OrderApi.getOrderByToken()
     */
    static async execute() {
        const orderId = 'DEMO-0009104436';

        try {
            // Generate order token
            const orderTokenResponse = await new Promise((resolve, reject) => {
                orderApi.generateOrderToken(
                    orderId
                    , function (error, data, response) {
                        if (error) {
                            reject(error);
                        } else {
                            resolve(data);
                        }
                    });
            });
            const orderToken = orderTokenResponse.order_token;

            console.log(`Order Token is: ${orderToken}`);

            /*
             * The token format will look something like this:
             * DEMO:UJZOGiIRLqgE3a10yp5wmEozLPNsGrDHNPiHfxsi0iAEcxgo9H74J/l6SR3X8g==
             */
            return orderToken;
        } catch (error) {
            console.error('Error generating order token:', error);
            throw error;
        }
    }
}

// Optional: If you want to call the method
// GenerateOrderToken.execute().then(token => {
//     // Do something with the token
// }).catch(error => {
//     // Handle any errors
// });
<?php

/*
 * This method generates a unique encrypted key for an Order.  This is useful if you wish to provide links for
 * customer orders without allowing someone to easily cycle through orders.  By requiring order tokens, you
 * control which orders are viewable with a public hyperlink.
 *
 * This method works in tandem with OrderApi.getOrderByToken()
 */

require_once '../vendor/autoload.php';
require_once '../constants.php';

use ultracart\v2\api\OrderApi;

$order_api = OrderApi::usingApiKey(Constants::API_KEY);

$order_id = 'DEMO-0009104436';
$order_token_response = $order_api->generateOrderToken($order_id);
$order_token = $order_token_response->getOrderToken();

echo '<html lang="en"><body><pre>Order Token is: ' . $order_token . '</pre></body></html>';

/*
 * The token format will look something like this:
 * DEMO:UJZOGiIRLqgE3a10yp5wmEozLPNsGrDHNPiHfxsi0iAEcxgo9H74J/l6SR3X8g==
 */



from ultracart.apis import OrderApi
from samples import api_client

# Create Order API instance
order_api = OrderApi(api_client())

# Define order ID
order_id = 'DEMO-0009104436'

# Generate order token
order_token_response = order_api.generate_order_token(order_id)
order_token = order_token_response.order_token

# Print the order token
print(f"Order Token is: {order_token}")

# Example token format:
# DEMO:UJZOGiIRLqgE3a10yp5wmEozLPNsGrDHNPiHfxsi0iAEcxgo9H74J/l6SR3X8g==

require 'ultracart_api'
require_relative '../constants'

# This method generates a unique encrypted key for an Order.  This is useful if you wish to provide links for
# customer orders without allowing someone to easily cycle through orders.  By requiring order tokens, you
# control which orders are viewable with a public hyperlink.
#
# This method works in tandem with OrderApi.getOrderByToken()
order_api = UltracartClient::OrderApi.new_using_api_key(Constants::API_KEY)

order_id = 'DEMO-0009104436'
order_token_response = order_api.generate_order_token(order_id)
order_token = order_token_response.order_token

puts "Order Token is: #{order_token}"

# The token format will look something like this:
# DEMO:UJZOGiIRLqgE3a10yp5wmEozLPNsGrDHNPiHfxsi0iAEcxgo9H74J/l6SR3X8g==
import {orderApi} from '../api';
import {OrderTokenResponse} from 'ultracart_rest_api_v2_typescript';

export class GenerateOrderToken {
    /**
     * This method generates a unique encrypted key for an Order.  This is useful if you wish to provide links for
     * customer orders without allowing someone to easily cycle through orders.  By requiring order tokens, you
     * control which orders are viewable with a public hyperlink.
     *
     * This method works in tandem with OrderApi.getOrderByToken()
     */
    public static async execute(): Promise<string | undefined> {
        const orderId = 'DEMO-0009104436';

        try {
            // Generate order token
            const orderTokenResponse: OrderTokenResponse = await orderApi.generateOrderToken({orderId});
            const orderToken = orderTokenResponse.order_token;

            console.log(`Order Token is: ${orderToken}`);

            /*
             * The token format will look something like this:
             * DEMO:UJZOGiIRLqgE3a10yp5wmEozLPNsGrDHNPiHfxsi0iAEcxgo9H74J/l6SR3X8g==
             */
            return orderToken;
        } catch (error) {
            console.error('Error generating order token:', error);
            throw error;
        }
    }
}

// Optional: If you want to call the method
// GenerateOrderToken.execute().then(token => {
//     // Do something with the token
// }).catch(error => {
//     // Handle any errors
// });

Delete an order

Permissions:
  • order_write

Produces: application/json
delete
/order/orders/{order_id}

Delete an order on the UltraCart account.

SDK Function Name: deleteOrder

Parameters
Parameter Description Location Data Type Required
order_id The order id to delete. path string required
Responses
Status Code Reason Response Model
204
No Content
400
Bad Request 400
401
Unauthorized 401
410
Authorized Application Disabled 410
429
Too Many Requests 429
500
Server Side 500
using System;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;

namespace SdkSample.order
{
    public class DeleteOrder
    {
        /**
         * OrderApi.DeleteOrder() will do just that.  It will delete an order.
         * You might find it more useful to reject an order rather than delete it in order to leave an audit trail.
         * However, deleting test orders will be useful to keep your order history tidy.  Still, any order
         * may be deleted.
         */
        public static void Execute()
        {
            OrderApi orderApi = new OrderApi(Constants.ApiKey);

            string orderId = "DEMO-0008104390";
            orderApi.DeleteOrder(orderId);
            Console.WriteLine("Order was deleted successfully.");
        }
    }
}
package order;

import com.ultracart.admin.v2.OrderApi;
import com.ultracart.admin.v2.util.ApiException;
import common.Constants;

public class DeleteOrder {
   /**
    * OrderApi.deleteOrder() will do just that.  It will delete an order.
    * You might find it more useful to reject an order rather than delete it in order to leave an audit trail.
    * However, deleting test orders will be useful to keep your order history tidy.  Still, any order
    * may be deleted.
    */
   public static void execute() throws ApiException {
       OrderApi orderApi = new OrderApi(Constants.API_KEY);

       String orderId = "DEMO-0008104390";
       orderApi.deleteOrder(orderId);
       System.out.println("Order was deleted successfully.");
   }
}
import { orderApi } from '../api.js';

/**
 * OrderApi.DeleteOrder() will do just that.  It will delete an order.
 * You might find it more useful to reject an order rather than delete it in order to leave an audit trail.
 * However, deleting test orders will be useful to keep your order history tidy.  Still, any order
 * may be deleted.
 */
export async function execute() {
    const orderId = "DEMO-0008104390";

    try {
        await new Promise((resolve, reject) => {
            orderApi.deleteOrder(orderId, function (error, data, response) {
                if (error) {
                    reject(error);
                } else {
                    resolve(data, response);
                }
            });
        });
        console.log("Order was deleted successfully.");
    } catch (error) {
        console.error("An error occurred while deleting the order:", error);
    }
}
<?php

/*
 * OrderApi.deleteOrder() will do just that.  It will delete an order.
 * You might find it more useful to reject an order rather than delete it in order to leave an audit trail.
 * However, deleting test orders will be useful to keep your order history tidy.  Still, any order
 * may be deleted.
 */

require_once '../vendor/autoload.php';
require_once '../samples.php';

$order_api = Samples::getOrderApi();

$order_id = 'DEMO-0008104390';
$order_api->deleteOrder($order_id);
echo 'Order was deleted successfully.';


"""
OrderApi.deleteOrder() deletes an order. While rejecting orders is often preferred for audit trails,
deleting test orders can help maintain a tidy order history.
"""

from samples import api_client
from ultracart.apis import OrderApi
from ultracart import ApiException
import logging

# Configure logging
logging.basicConfig(level=logging.ERROR)
logger = logging.getLogger(__name__)

try:
    # Initialize Order API
    order_api = OrderApi(api_client())

    # Set order to delete
    order_id = 'DEMO-0008104390'

    # Delete order
    order_api.delete_order(order_id)
    print('Order was deleted successfully.')

except ApiException as e:
    logger.error(f"API Exception: {e}")
    print('Order could not be deleted.')
# OrderApi.delete_order() will do just that.  It will delete an order.
# You might find it more useful to reject an order rather than delete it in order to leave an audit trail.
# However, deleting test orders will be useful to keep your order history tidy.  Still, any order
# may be deleted.

require_relative '../constants'
require 'ultracart_api'

order_api = UltracartClient::OrderApi.new_using_api_key(Constants::API_KEY)

order_id = 'DEMO-0008104390'
order_api.delete_order(order_id)
puts 'Order was deleted successfully.'
import { orderApi } from '../api';

/**
 * OrderApi.DeleteOrder() will do just that.  It will delete an order.
 * You might find it more useful to reject an order rather than delete it in order to leave an audit trail.
 * However, deleting test orders will be useful to keep your order history tidy.  Still, any order
 * may be deleted.
 */
export async function execute(): Promise<void> {
    const orderId = "DEMO-0008104390";

    try {
        await orderApi.deleteOrder({
            orderId: orderId
        });
        console.log("Order was deleted successfully.");
    } catch (error) {
        console.error("An error occurred while deleting the order:", error);
    }
}

Retrieve an order

Permissions:
  • order_read

Produces: application/json
get
/order/orders/{order_id}

Retrieves a single order using the specified order id.

SDK Function Name: getOrder

Parameters
Parameter Description Location Data Type Required
order_id The order id to retrieve. path string required
_expand The object expansion to perform on the result. See documentation for examples query string optional
Responses
Status Code Reason Response Model
200
Successful response OrderResponse
400
Bad Request 400
401
Unauthorized 401
410
Authorized Application Disabled 410
429
Too Many Requests 429
500
Server Side 500
using System;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;
using Newtonsoft.Json;

namespace SdkSample.order
{
    public class GetOrder
    {
        /*
         * OrderApi.getOrder() retrieves a single order for a given order_id.
         */
        public static void Execute()
        {
            OrderApi orderApi = new OrderApi(Constants.ApiKey);

            // The expansion variable instructs UltraCart how much information to return.  The order object is large and
            // while it's easily manageable for a single order, when querying thousands of orders, is useful to reduce
            // payload size.
            // see www.ultracart.com/api/ for all the expansion fields available (this list below may become stale)
            /*
            Possible Order Expansions:
            affiliate           affiliate.ledger                    auto_order
            billing             channel_partner                     checkout
            coupon              customer_profile                    digital_order
            edi                 fraud_score                         gift
            gift_certificate    internal                            item
            linked_shipment     marketing                           payment
            payment.transaction quote                               salesforce
            shipping            shipping.tracking_number_details    summary
            taxes
            */
            string expansion = "item,summary,billing,shipping,shipping.tracking_number_details";

            string orderId = "DEMO-0009104390";
            OrderResponse apiResponse = orderApi.GetOrder(orderId, expansion);

            if (apiResponse.Error != null)
            {
                Console.Error.WriteLine(apiResponse.Error.DeveloperMessage);
                Console.Error.WriteLine(apiResponse.Error.UserMessage);
                Environment.Exit(1);
            }

            Order order = apiResponse.Order;
            Console.WriteLine(JsonConvert.SerializeObject(order, new JsonSerializerSettings { Formatting = Formatting.Indented}));
            
        }

    }
}
package order;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.ultracart.admin.v2.OrderApi;
import com.ultracart.admin.v2.models.*;
import com.ultracart.admin.v2.util.ApiException;

public class GetOrder {
   /*
    * OrderApi.getOrder() retrieves a single order for a given order_id.
    */
   public void execute() throws ApiException {
       OrderApi orderApi = new OrderApi(common.Constants.API_KEY);

       // The expansion variable instructs UltraCart how much information to return.  The order object is large and
       // while it's easily manageable for a single order, when querying thousands of orders, is useful to reduce
       // payload size.
       // see www.ultracart.com/api/ for all the expansion fields available (this list below may become stale)
       /*
       Possible Order Expansions:
       affiliate           affiliate.ledger                    auto_order
       billing             channel_partner                     checkout
       coupon              customer_profile                    digital_order
       edi                 fraud_score                         gift
       gift_certificate    internal                            item
       linked_shipment     marketing                           payment
       payment.transaction quote                               salesforce
       shipping            shipping.tracking_number_details    summary
       taxes
       */
       String expansion = "item,summary,billing,shipping,shipping.tracking_number_details";

       String orderId = "DEMO-0009104390";
       OrderResponse apiResponse = orderApi.getOrder(orderId, expansion);

       if (apiResponse.getError() != null) {
           System.err.println(apiResponse.getError().getDeveloperMessage());
           System.err.println(apiResponse.getError().getUserMessage());
           System.exit(1);
       }

       Order order = apiResponse.getOrder();
       Gson gson = new GsonBuilder().setPrettyPrinting().create();
       System.out.println(gson.toJson(order));
   }
}
import { orderApi } from '../api.js';

export class GetOrder {
    /**
     * OrderApi.getOrder() retrieves a single order for a given order_id.
     */
    static async execute() {
        // The expansion variable instructs UltraCart how much information to return.  The order object is large and
        // while it's easily manageable for a single order, when querying thousands of orders, is useful to reduce
        // payload size.
        // see www.ultracart.com/api/ for all the expansion fields available (this list below may become stale)
        /*
        Possible Order Expansions:
        affiliate           affiliate.ledger                    auto_order
        billing             channel_partner                     checkout
        coupon              customer_profile                    digital_order
        edi                 fraud_score                         gift
        gift_certificate    internal                            item
        linked_shipment     marketing                           payment
        payment.transaction quote                               salesforce
        shipping            shipping.tracking_number_details    summary
        taxes
        */
        const expansion = 'item,summary,billing,shipping,shipping.tracking_number_details';

        const orderId = 'DEMO-0009104390';

        try {
            // Retrieve the order
            const apiResponse = await new Promise((resolve, reject) => {
                orderApi.getOrder(orderId, {_expand: expansion }, function (error, data, response) {
                    if (error) {
                        reject(error);
                    } else {
                        resolve(data);
                    }
                });
            });

            // Check for errors
            if (apiResponse.error) {
                console.error('Developer Message:', apiResponse.error.developer_message);
                console.error('User Message:', apiResponse.error.user_message);
                throw new Error('Failed to retrieve order');
            }

            // Ensure order exists
            if (!apiResponse.order) {
                console.error('No order found');
                return undefined;
            }

            // Pretty print the order
            console.log(JSON.stringify(apiResponse.order, null, 2));

            return apiResponse.order;
        } catch (error) {
            console.error('Error retrieving order:', error);
            process.exit(1);
        }
    }
}

// Optional: If you want to call the method
// GetOrder.execute().then(order => {
//     if (order) {
//         // Do something with the order
//     }
// });
<?php

ini_set('display_errors', 1);

/*
 * OrderApi.getOrder() retrieves a single order for a given order_id.
 */

use ultracart\v2\api\OrderApi;

require_once '../vendor/autoload.php';
require_once '../constants.php';


$order_api = OrderApi::usingApiKey(Constants::API_KEY);

// The expansion variable instructs UltraCart how much information to return.  The order object is large and
// while it's easily manageable for a single order, when querying thousands of orders, is useful to reduce
// payload size.
// see www.ultracart.com/api/ for all the expansion fields available (this list below may become stale)
/*
Possible Order Expansions:
affiliate           affiliate.ledger                    auto_order
billing             channel_partner                     checkout
coupon              customer_profile                    digital_order
edi                 fraud_score                         gift
gift_certificate    internal                            item
linked_shipment     marketing                           payment
payment.transaction quote                               salesforce
shipping            shipping.tracking_number_details    summary
taxes
*/
$expansion = "item,summary,billing,shipping,shipping.tracking_number_details";

$order_id = 'DEMO-0009104390';
$api_response = $order_api->getOrder($order_id, $expansion);

if ($api_response->getError() != null) {
    error_log($api_response->getError()->getDeveloperMessage());
    error_log($api_response->getError()->getUserMessage());
    exit();
}

$order = $api_response->getOrder();

echo '<html lang="en"><body><pre>';
var_dump($order);
echo '</pre></body></html>';

from ultracart.apis import OrderApi
from samples import api_client

# Create Order API instance
order_api = OrderApi(api_client())

# The expand variable instructs UltraCart how much information to return. The order object is large and
# while it's easily manageable for a single order, when querying thousands of orders, it is useful to reduce
# payload size.
# See www.ultracart.com/api/ for all the expansion fields available (this list below may become stale).
#
# Possible Order Expansions:
# affiliate           affiliate.ledger                    auto_order
# billing             channel_partner                     checkout
# coupon              customer_profile                    digital_order
# edi                 fraud_score                         gift
# gift_certificate    internal                            item
# linked_shipment     marketing                           payment
# payment.transaction quote                               salesforce
# shipping            shipping.tracking_number_details    summary
# taxes

expand = "item,summary,billing,shipping,shipping.tracking_number_details"

# Define order ID
order_id = 'DEMO-0009104390'

# Retrieve order
api_response = order_api.get_order(order_id, expand=expand)

# Check for errors
if api_response.error:
    print(f"Developer Message: {api_response.error.developer_message}")
    print(f"User Message: {api_response.error.user_message}")
    exit()

# Extract order details
order = api_response.order

# Print order details
print(order)

require 'ultracart_api'
require_relative '../constants'

# OrderApi.getOrder() retrieves a single order for a given order_id.
order_api = UltracartClient::OrderApi.new_using_api_key(Constants::API_KEY)

# The expansion variable instructs UltraCart how much information to return.  The order object is large and
# while it's easily manageable for a single order, when querying thousands of orders, is useful to reduce
# payload size.
# see www.ultracart.com/api/ for all the expansion fields available (this list below may become stale)
=begin
Possible Order Expansions:
affiliate           affiliate.ledger                    auto_order
billing             channel_partner                     checkout
coupon              customer_profile                    digital_order
edi                 fraud_score                         gift
gift_certificate    internal                            item
linked_shipment     marketing                           payment
payment.transaction quote                               salesforce
shipping            shipping.tracking_number_details    summary
taxes
=end
expansion = "item,summary,billing,shipping,shipping.tracking_number_details"

order_id = 'DEMO-0009104390'
opts = {
  '_expand' => expansion
}

begin
  api_response = order_api.get_order(order_id, opts)

  # Check for errors
  if api_response.error
    puts "Developer Message: #{api_response.error.developer_message}"
    puts "User Message: #{api_response.error.user_message}"
    exit
  end

  order = api_response.order

  # Using inspect instead of var_dump for Ruby-style object representation
  puts order.inspect
rescue StandardError => e
  puts "An error occurred: #{e.message}"
end
import {orderApi} from '../api';
import {OrderResponse, Order} from 'ultracart_rest_api_v2_typescript';

export class GetOrder {
    /**
     * OrderApi.getOrder() retrieves a single order for a given order_id.
     */
    public static async execute(): Promise<Order | undefined> {
        // The expansion variable instructs UltraCart how much information to return.  The order object is large and
        // while it's easily manageable for a single order, when querying thousands of orders, is useful to reduce
        // payload size.
        // see www.ultracart.com/api/ for all the expansion fields available (this list below may become stale)
        /*
        Possible Order Expansions:
        affiliate           affiliate.ledger                    auto_order
        billing             channel_partner                     checkout
        coupon              customer_profile                    digital_order
        edi                 fraud_score                         gift
        gift_certificate    internal                            item
        linked_shipment     marketing                           payment
        payment.transaction quote                               salesforce
        shipping            shipping.tracking_number_details    summary
        taxes
        */
        const expansion = 'item,summary,billing,shipping,shipping.tracking_number_details';

        const orderId = 'DEMO-0009104390';

        try {
            // Retrieve the order
            const apiResponse: OrderResponse = await orderApi.getOrder({orderId, expand: expansion});

            // Check for errors
            if (apiResponse.error) {
                console.error('Developer Message:', apiResponse.error.developer_message);
                console.error('User Message:', apiResponse.error.user_message);
                throw new Error('Failed to retrieve order');
            }

            // Ensure order exists
            if (!apiResponse.order) {
                console.error('No order found');
                return undefined;
            }

            // Pretty print the order
            console.log(JSON.stringify(apiResponse.order, null, 2));

            return apiResponse.order;
        } catch (error) {
            console.error('Error retrieving order:', error);
            process.exit(1);
        }
    }
}

// Optional: If you want to call the method
// GetOrder.execute().then(order => {
//     if (order) {
//         // Do something with the order
//     }
// });

Update an order

Permissions:
  • order_write

Consumes: application/json
Produces: application/json
put
/order/orders/{order_id}

Update a new order on the UltraCart account. This is probably NOT the method you want. It is rare to update a completed order. This will not trigger charges, emails, or any other automation.

SDK Function Name: updateOrder

Parameters
Parameter Description Location Data Type Required
order Order to update body Order required
order_id The order id to update. path string required
_expand The object expansion to perform on the result. See documentation for examples query string optional
Responses
Status Code Reason Response Model
200
Successful response OrderResponse
400
Bad Request 400
401
Unauthorized 401
410
Authorized Application Disabled 410
429
Too Many Requests 429
500
Server Side 500
using System;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;
using Newtonsoft.Json;

namespace SdkSample.order
{
    public class UpdateOrder
    {
        public static void Execute()
        {
            OrderApi orderApi = new OrderApi(Constants.ApiKey);

            string expansion = "checkout"; // see the getOrder sample for expansion discussion

            string orderId = "DEMO-0009104976";
            Order order = orderApi.GetOrder(orderId, expansion).Order;

            Console.WriteLine("Original Order follows:");
            Console.WriteLine(JsonConvert.SerializeObject(order, new JsonSerializerSettings { Formatting = Formatting.Indented}));
            

            // TODO: do some updates to the order.
            // For example:
            // order.BillingAddress.FirstName = "John";
            // order.BillingAddress.LastName = "Smith";

            OrderResponse apiResponse = orderApi.UpdateOrder(orderId, order,expansion);

            if (apiResponse.Error != null)
            {
                Console.Error.WriteLine(apiResponse.Error.DeveloperMessage);
                Console.Error.WriteLine(apiResponse.Error.UserMessage);
                return;
            }

            Order updatedOrder = apiResponse.Order;

            Console.WriteLine("Updated Order follows:");
            Console.WriteLine(JsonConvert.SerializeObject(updatedOrder, new JsonSerializerSettings { Formatting = Formatting.Indented}));
            
        }
        
    }
}
package order;

import com.ultracart.admin.v2.OrderApi;
import com.ultracart.admin.v2.models.*;
import com.ultracart.admin.v2.util.ApiException;

public class UpdateOrder {
   public static void execute() throws ApiException {
       OrderApi orderApi = new OrderApi(common.Constants.API_KEY);

       String expansion = "checkout"; // see the getOrder sample for expansion discussion

       String orderId = "DEMO-0009104976";
       Order order = orderApi.getOrder(orderId, expansion).getOrder();

       System.out.println("Original Order follows:");
       System.out.println(order.toString());

       // TODO: do some updates to the order.
       // For example:
       // order.getBillingAddress().setFirstName("John");
       // order.getBillingAddress().setLastName("Smith");

       OrderResponse apiResponse = orderApi.updateOrder(orderId, order, expansion);

       if (apiResponse.getError() != null) {
           System.err.println(apiResponse.getError().getDeveloperMessage());
           System.err.println(apiResponse.getError().getUserMessage());
           return;
       }

       Order updatedOrder = apiResponse.getOrder();

       System.out.println("Updated Order follows:");
       System.out.println(updatedOrder.toString());
   }
}
import {orderApi} from '../api.js';

export class UpdateOrder {
    static async execute() {
        const expansion = "checkout"; // see the getOrder sample for expansion discussion

        const orderId = "DEMO-0009104976";
        const orderOrUndefined = await new Promise((resolve, reject) => {
            orderApi.getOrder(
                orderId,
                {_expand: expansion}, function (error, data, response) {
                    if (error) {
                        reject(error);
                    } else {
                        resolve(data);
                    }
                });
        });

        if (orderOrUndefined.order !== undefined) {
            const order = orderOrUndefined.order;

            console.log("Original Order follows:");
            console.log(JSON.stringify(order, null, 2));

            // TODO: do some updates to the order.
            // For example:
            // order.billingAddress.firstName = "John";
            // order.billingAddress.lastName = "Smith";

            const apiResponse = await new Promise((resolve, reject) => {
                orderApi.updateOrder(
                    orderId,
                    order,
                    {_expand: expansion}, function (error, data, response) {
                        if (error) {
                            reject(error);
                        } else {
                            resolve(data);
                        }
                    });
            });

            if (apiResponse.error !== undefined) {
                console.error(apiResponse.error.developer_message);
                console.error(apiResponse.error.user_message);
                return;
            }

            const updatedOrder = apiResponse.order;

            console.log("Updated Order follows:");
            console.log(JSON.stringify(updatedOrder, null, 2));
        }
    }
}
<?php

ini_set('display_errors', 1);

use ultracart\v2\api\OrderApi;

require_once '../vendor/autoload.php';
require_once '../constants.php';


$order_api = OrderApi::usingApiKey(Constants::API_KEY, false, false);

$expansion = "checkout"; // see the getOrder sample for expansion discussion

$order_id = 'DEMO-0009104976';
$order = $order_api->getOrder($order_id, $expansion)->getOrder();

echo '<html lang="en"><body><pre>';
var_dump($order);

// TODO: do some updates to the order.

$api_response = $order_api->updateOrder($order_id, $order, $expansion);

if ($api_response->getError() != null) {
    error_log($api_response->getError()->getDeveloperMessage());
    error_log($api_response->getError()->getUserMessage());
    exit();
}

$updated_order = $api_response->getOrder();

echo '<br>After Update<br><br>';
var_dump($updated_order);
echo '</pre></body></html>';

from ultracart import ApiException
from ultracart.apis import OrderApi
from samples import api_client

# Initialize the Order API with the API key
order_api = OrderApi(api_client())

# Define the expansion to be used in the API call (related to checkout)
expansion = "checkout"  # see the getOrder sample for expansion discussion

# The order ID to retrieve and update
order_id = 'DEMO-0009104976'

# Step 1: Retrieve the order
try:
    api_response = order_api.get_order(order_id, expansion)
    order = api_response.order
except ApiException as e:
    print(f"Exception when calling OrderApi->get_order: {e}")
    exit()

# Output the current order details
print("<html lang='en'><body><pre>")
print(order)

# TODO: Do some updates to the order here.

# Step 2: Update the order
try:
    api_response = order_api.update_order(order_id, order, expansion)
except ApiException as e:
    print(f"Exception when calling OrderApi->update_order: {e}")
    exit()

# Check for errors in the API response
if api_response.error is not None:
    print(f"Developer Message: {api_response.error.developer_message}")
    print(f"User Message: {api_response.error.user_message}")
    exit()

# Output the updated order details
updated_order = api_response.order
print(updated_order)

require 'ultracart_api'
require_relative '../constants'

order_api = UltracartClient::OrderApi.new_using_api_key(Constants::API_KEY)

expansion = "checkout" # see the get_order sample for expansion discussion

order_id = 'DEMO-0009104976'
order = order_api.get_order(order_id, opts = { _expand: expansion }).order

p order

# TODO: do some updates to the order.

api_response = order_api.update_order(order_id, order, opts = { _expand: expansion })

if api_response.error
  puts api_response.error.developer_message
  puts api_response.error.user_message
  exit
end

updated_order = api_response.order

puts 'After Update'
p updated_order
import {orderApi} from '../api';
import {Order, OrderResponse} from 'ultracart_rest_api_v2_typescript';

export class UpdateOrder {
    public static async execute(): Promise<void> {
        const expansion: string = "checkout"; // see the getOrder sample for expansion discussion

        const orderId: string = "DEMO-0009104976";
        const orderOrUndefined: Order | undefined = (await orderApi.getOrder({orderId, expand: expansion})).order;

        if (orderOrUndefined !== undefined) {
            const order = orderOrUndefined as Order;

            console.log("Original Order follows:");
            console.log(JSON.stringify(order, null, 2));

            // TODO: do some updates to the order.
            // For example:
            // order.billingAddress.firstName = "John";
            // order.billingAddress.lastName = "Smith";

            const apiResponse: OrderResponse = await orderApi.updateOrder({
                orderId: orderId,
                order: order,
                expand: expansion
            });

            if (apiResponse.error !== undefined) {
                console.error(apiResponse.error.developer_message);
                console.error(apiResponse.error.user_message);
                return;
            }

            const updatedOrder: Order | undefined = apiResponse.order;

            console.log("Updated Order follows:");
            console.log(JSON.stringify(updatedOrder, null, 2));
        }
    }
}

Adjusts an order total

Permissions:
  • order_write

Produces: application/json
post
/order/orders/{order_id}/adjust_order_total/{desired_total}

Adjusts an order total. Adjusts individual items appropriately and considers taxes. Desired total should be provided in the same currency as the order and must be less than the current total and greater than zero. This call will change the order total. It returns true if the desired total is achieved. If the goal seeking algorithm falls short (usually by pennies), this method returns back false. View the merchant notes for the order for further details.

SDK Function Name: adjustOrderTotal

Parameters
Parameter Description Location Data Type Required
order_id The order id to cancel. path string required
desired_total The desired total with no formatting. example 123.45 path string required
Responses
Status Code Reason Response Model
200
Successful response BaseResponse
400
Bad Request 400
401
Unauthorized 401
410
Authorized Application Disabled 410
429
Too Many Requests 429
500
Server Side 500
using System;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;

namespace SdkSample.order
{
    public class AdjustOrderTotal
    {
        /**
         * OrderApi.adjustOrderTotal() takes a desired order total and performs goal-seeking to adjust all items and taxes
         * appropriately.  This method was created for merchants dealing with Medicare and Medicaid.  When selling their
         * medical devices, they would often run into limits approved by Medicare.  As such, they needed to adjust the
         * order total to match the approved amount.  This is a convenience method to adjust individual items and their
         * taxes to match the desired total.
         */
        public static void Execute()
        {
            OrderApi orderApi = new OrderApi(Constants.ApiKey);

            string orderId = "DEMO-0009104390";
            string desiredTotal = "21.99";
            BaseResponse apiResponse = orderApi.AdjustOrderTotal(orderId, desiredTotal);

            if (apiResponse.Error != null)
            {
                Console.Error.WriteLine(apiResponse.Error.DeveloperMessage);
                Console.Error.WriteLine(apiResponse.Error.UserMessage);
                Console.WriteLine("Order could not be adjusted. See error log.");
                return;
            }

            if (apiResponse.Success)
            {
                Console.WriteLine("Order was adjusted successfully. Use GetOrder() to retrieve the order if needed.");
            }
        }
    }
}
package order;

import com.ultracart.admin.v2.OrderApi;
import com.ultracart.admin.v2.models.*;
import com.ultracart.admin.v2.util.ApiException;
import common.Constants;

public class AdjustOrderTotal {
   /**
    * OrderApi.adjustOrderTotal() takes a desired order total and performs goal-seeking to adjust all items and taxes
    * appropriately.  This method was created for merchants dealing with Medicare and Medicaid.  When selling their
    * medical devices, they would often run into limits approved by Medicare.  As such, they needed to adjust the
    * order total to match the approved amount.  This is a convenience method to adjust individual items and their
    * taxes to match the desired total.
    */
   public static void execute() throws ApiException {
       OrderApi orderApi = new OrderApi(Constants.API_KEY);

       String orderId = "DEMO-0009104390";
       String desiredTotal = "21.99";
       BaseResponse apiResponse = orderApi.adjustOrderTotal(orderId, desiredTotal);

       if (apiResponse.getError() != null) {
           System.err.println(apiResponse.getError().getDeveloperMessage());
           System.err.println(apiResponse.getError().getUserMessage());
           System.out.println("Order could not be adjusted. See error log.");
           return;
       }

       if (apiResponse.getSuccess()) {
           System.out.println("Order was adjusted successfully. Use getOrder() to retrieve the order if needed.");
       }
   }
}
import { orderApi } from '../api.js';

/**
 * OrderApi.adjustOrderTotal() takes a desired order total and performs goal-seeking to adjust all items and taxes
 * appropriately.  This method was created for merchants dealing with Medicare and Medicaid.  When selling their
 * medical devices, they would often run into limits approved by Medicare.  As such, they needed to adjust the
 * order total to match the approved amount.  This is a convenience method to adjust individual items and their
 * taxes to match the desired total.
 */
export async function execute() {
    const orderId = "DEMO-0009104390";
    const desiredTotal = "21.99";

    try {
        const apiResponse = await new Promise((resolve, reject) => {
            orderApi.adjustOrderTotal(
                orderId,
                desiredTotal
            , function(error, data, response) {
                if (error) {
                    reject(error);
                } else {
                    resolve(data);
                }
            });
        });

        if (apiResponse.error) {
            console.error(apiResponse.error.developer_message);
            console.error(apiResponse.error.user_message);
            console.log("Order could not be adjusted. See error log.");
            return;
        }

        if (apiResponse.success) {
            console.log("Order was adjusted successfully. Use GetOrder() to retrieve the order if needed.");
        }
    } catch (error) {
        console.error("An error occurred while adjusting the order:", error);
    }
}
<?php

/*
 * OrderApi.adjustOrderTotal() takes a desired order total and performs goal-seeking to adjust all items and taxes
 * appropriately.  This method was created for merchants dealing with Medicare and Medicaid.  When selling their
 * medical devices, they would often run into limits approved by Medicare.  As such, they needed to adjust the
 * order total to match the approved amount.  This is a convenience method to adjust individual items and their
 * taxes to match the desired total.
 */

require_once '../vendor/autoload.php';
require_once '../samples.php';

$order_api = Samples::getOrderApi();

$order_id = 'DEMO-0009104390';
$desired_total = '21.99';
$api_response = $order_api->adjustOrderTotal($order_id, $desired_total);

if ($api_response->getError() != null) {
    error_log($api_response->getError()->getDeveloperMessage());
    error_log($api_response->getError()->getUserMessage());
    echo 'Order could not be adjusted.  See php error log.';
    exit();
}

if($api_response->getSuccess()){
    echo 'Order was adjusted successfully.  Use getOrder() to retrieve the order if needed.';
}

"""
OrderApi.adjustOrderTotal() takes a desired order total and performs goal-seeking to adjust all items and taxes
appropriately.  This method was created for merchants dealing with Medicare and Medicaid.  When selling their
medical devices, they would often run into limits approved by Medicare.  As such, they needed to adjust the
order total to match the approved amount.  This is a convenience method to adjust individual items and their
taxes to match the desired total.
"""

from samples import api_client
from ultracart.apis import OrderApi
from ultracart import ApiException
import logging

# Configure logging
logging.basicConfig(level=logging.ERROR)
logger = logging.getLogger(__name__)

try:
    # Initialize Order API
    order_api = OrderApi(api_client())

    # Set order details
    order_id = 'DEMO-0009104390'
    desired_total = '21.99'

    # Adjust order total
    api_response = order_api.adjust_order_total(order_id, desired_total)

    # Check for errors
    if api_response.error:
        logger.error(api_response.error.developer_message)
        logger.error(api_response.error.user_message)
        print('Order could not be adjusted. See Python error log.')
        exit()

    # Check success
    if api_response.success:
        print('Order was adjusted successfully. Use get_order() to retrieve the order if needed.')

except ApiException as e:
    logger.error(f"API Exception: {e}")
    print('Order could not be adjusted due to an API error.')
# OrderApi.adjust_order_total() takes a desired order total and performs goal-seeking to adjust all items and taxes
# appropriately.  This method was created for merchants dealing with Medicare and Medicaid.  When selling their
# medical devices, they would often run into limits approved by Medicare.  As such, they needed to adjust the
# order total to match the approved amount.  This is a convenience method to adjust individual items and their
# taxes to match the desired total.

require_relative '../constants'
require 'ultracart_api'

order_api = UltracartClient::OrderApi.new_using_api_key(Constants::API_KEY)

order_id = 'DEMO-0009104390'
desired_total = '21.99'
api_response = order_api.adjust_order_total(order_id, desired_total)

if api_response.get_error != nil
  # Log the error messages
  puts "Developer Message: #{api_response.get_error.get_developer_message}"
  puts "User Message: #{api_response.get_error.get_user_message}"
  puts 'Order could not be adjusted. See ruby error log.'
  exit
end

if api_response.get_success
  puts 'Order was adjusted successfully. Use get_order() to retrieve the order if needed.'
end
import { orderApi } from '../api';
import { BaseResponse } from 'ultracart_rest_api_v2_typescript';

/**
 * OrderApi.adjustOrderTotal() takes a desired order total and performs goal-seeking to adjust all items and taxes
 * appropriately.  This method was created for merchants dealing with Medicare and Medicaid.  When selling their
 * medical devices, they would often run into limits approved by Medicare.  As such, they needed to adjust the
 * order total to match the approved amount.  This is a convenience method to adjust individual items and their
 * taxes to match the desired total.
 */
export async function execute(): Promise<void> {
    const orderId = "DEMO-0009104390";
    const desiredTotal = "21.99";

    try {
        const apiResponse: BaseResponse = await orderApi.adjustOrderTotal({
            orderId: orderId,
            desiredTotal: desiredTotal
        });

        if (apiResponse.error) {
            console.error(apiResponse.error.developer_message);
            console.error(apiResponse.error.user_message);
            console.log("Order could not be adjusted. See error log.");
            return;
        }

        if (apiResponse.success) {
            console.log("Order was adjusted successfully. Use GetOrder() to retrieve the order if needed.");
        }
    } catch (error) {
        console.error("An error occurred while adjusting the order:", error);
    }
}

Cancel an order

Permissions:
  • order_write

Produces: application/json
post
/order/orders/{order_id}/cancel

Cancel an order on the UltraCart account. If the success flag is false, then consult the error message for why it failed.

SDK Function Name: cancelOrder

Parameters
Parameter Description Location Data Type Required
order_id The order id to cancel. path string required
lock_self_ship_orders Flag to prevent a order shipping during a refund process query boolean optional
skip_refund_and_hold Skip refund and move order to Held Orders department query boolean optional
Responses
Status Code Reason Response Model
200
Successful response BaseResponse
400
Bad Request 400
401
Unauthorized 401
410
Authorized Application Disabled 410
429
Too Many Requests 429
500
Server Side 500
using System;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;

namespace SdkSample.order
{
    public class CancelOrder
    {
        /**
         * OrderApi.CancelOrder() will do just that.  It will cancel an order by rejecting it.
         * However, the following restrictions apply:
         * 1) If the order is already completed, this call will fail.
         * 2) If the order has already been rejected, this call will fail.
         * 3) If the order has already been transmitted to a fulfillment center, this call will fail.
         * 4) If the order is queued for transmission to a distribution center, this call will fail.
         */
        public static void Execute()
        {
            OrderApi orderApi = new OrderApi(Constants.ApiKey);

            string orderId = "DEMO-0009104390";
            BaseResponse apiResponse = orderApi.CancelOrder(orderId);

            if (apiResponse.Error != null)
            {
                Console.Error.WriteLine(apiResponse.Error.DeveloperMessage);
                Console.Error.WriteLine(apiResponse.Error.UserMessage);
                Console.WriteLine("Order could not be canceled. See error log.");
                return;
            }

            if (apiResponse.Success)
            {
                Console.WriteLine("Order was canceled successfully.");
            }
        }
    }
}
package order;

import com.ultracart.admin.v2.OrderApi;
import com.ultracart.admin.v2.models.*;
import com.ultracart.admin.v2.util.ApiException;
import common.Constants;

public class CancelOrder {
   /**
    * OrderApi.cancelOrder() will do just that.  It will cancel an order by rejecting it.
    * However, the following restrictions apply:
    * 1) If the order is already completed, this call will fail.
    * 2) If the order has already been rejected, this call will fail.
    * 3) If the order has already been transmitted to a fulfillment center, this call will fail.
    * 4) If the order is queued for transmission to a distribution center, this call will fail.
    */
   public static void execute() throws ApiException {
       OrderApi orderApi = new OrderApi(Constants.API_KEY);

       String orderId = "DEMO-0009104390";
       BaseResponse apiResponse = orderApi.cancelOrder(orderId, false, false);

       if (apiResponse.getError() != null) {
           System.err.println(apiResponse.getError().getDeveloperMessage());
           System.err.println(apiResponse.getError().getUserMessage());
           System.out.println("Order could not be canceled. See error log.");
           return;
       }

       if (apiResponse.getSuccess()) {
           System.out.println("Order was canceled successfully.");
       }
   }
}
import { orderApi } from '../api.js';

/**
 * OrderApi.CancelOrder() will do just that.  It will cancel an order by rejecting it.
 * However, the following restrictions apply:
 * 1) If the order is already completed, this call will fail.
 * 2) If the order has already been rejected, this call will fail.
 * 3) If the order has already been transmitted to a fulfillment center, this call will fail.
 * 4) If the order is queued for transmission to a distribution center, this call will fail.
 */
export class CancelOrder {
    /**
     * Attempts to cancel a specific order
     * @param apiKey The API key for authentication
     * @returns Promise resolving to whether the order was successfully canceled
     */
    static async execute(apiKey) {
        const orderId = "DEMO-0009104390";

        try {
            const apiResponse = await new Promise((resolve, reject) => {
                orderApi.cancelOrder(orderId, function(error, data, response) {
                    if (error) {
                        reject(error);
                    } else {
                        resolve(data);
                    }
                });
            });

            if (apiResponse.error) {
                console.error(apiResponse.error.developer_message);
                console.error(apiResponse.error.user_message);
                console.log("Order could not be canceled. See error log.");
                return false;
            }

            if (apiResponse.success) {
                console.log("Order was canceled successfully.");
                return true;
            }

            return false;
        } catch (error) {
            console.error("An error occurred while canceling the order:", error);
            return false;
        }
    }
}

// Example usage
async function cancelOrderExample() {
    const apiKey = "your-api-key-here"; // Replace with actual API key
    const result = await CancelOrder.execute(apiKey);
    console.log(result ? "Order cancellation successful" : "Order cancellation failed");
}
<?php

/*
 * OrderApi.cancelOrder() will do just that.  It will cancel an order by rejecting it.
 * However, the following restrictions apply:
 * 1) If the order is already completed, this call will fail.
 * 2) If the order has already been rejected, this call will fail.
 * 3) If the order has already been transmitted to a fulfillment center, this call will fail.
 * 4) If the order is queued for transmission to a distribution center, this call will fail.
 */

require_once '../vendor/autoload.php';
require_once '../samples.php';

$order_api = Samples::getOrderApi();

$order_id = 'DEMO-0009104390';
$api_response = $order_api->cancelOrder($order_id);

if ($api_response->getError() != null) {
    error_log($api_response->getError()->getDeveloperMessage());
    error_log($api_response->getError()->getUserMessage());
    echo 'Order could not be canceled.  See php error log.';
    exit();
}

if($api_response->getSuccess()){
    echo 'Order was canceled successfully.';
}

"""
OrderApi.cancelOrder() cancels an order by rejecting it.

Restrictions:
1) Cannot cancel completed orders
2) Cannot cancel already rejected orders
3) Cannot cancel orders transmitted to fulfillment center
4) Cannot cancel orders queued for distribution center transmission
"""

from samples import api_client
from ultracart.apis import OrderApi
from ultracart import ApiException
import logging

# Configure logging
logging.basicConfig(level=logging.ERROR)
logger = logging.getLogger(__name__)

try:
    # Initialize Order API
    order_api = OrderApi(api_client())

    # Set order to cancel
    order_id = 'DEMO-0009104390'

    # Cancel order
    api_response = order_api.cancel_order(order_id)

    # Check for errors
    if api_response.error:
        logger.error(api_response.error.developer_message)
        logger.error(api_response.error.user_message)
        print('Order could not be canceled. See Python error log.')
        exit()

    # Check success
    if api_response.success:
        print('Order was canceled successfully.')

except ApiException as e:
    logger.error(f"API Exception: {e}")
    print('Order could not be canceled due to an API error.')
# OrderApi.cancel_order() will do just that.  It will cancel an order by rejecting it.
# However, the following restrictions apply:
# 1) If the order is already completed, this call will fail.
# 2) If the order has already been rejected, this call will fail.
# 3) If the order has already been transmitted to a fulfillment center, this call will fail.
# 4) If the order is queued for transmission to a distribution center, this call will fail.

require_relative '../constants'
require 'ultracart_api'

order_api = UltracartClient::OrderApi.new_using_api_key(Constants::API_KEY)

order_id = 'DEMO-0009104390'
api_response = order_api.cancel_order(order_id)

if api_response.get_error != nil
  # Log the error messages
  puts "Developer Message: #{api_response.get_error.get_developer_message}"
  puts "User Message: #{api_response.get_error.get_user_message}"
  puts 'Order could not be canceled. See ruby error log.'
  exit
end

if api_response.get_success
  puts 'Order was canceled successfully.'
end
import { orderApi } from '../api';
import { BaseResponse } from 'ultracart_rest_api_v2_typescript';

/**
 * OrderApi.CancelOrder() will do just that.  It will cancel an order by rejecting it.
 * However, the following restrictions apply:
 * 1) If the order is already completed, this call will fail.
 * 2) If the order has already been rejected, this call will fail.
 * 3) If the order has already been transmitted to a fulfillment center, this call will fail.
 * 4) If the order is queued for transmission to a distribution center, this call will fail.
 */
export class CancelOrder {
    /**
     * Attempts to cancel a specific order
     * @param apiKey The API key for authentication
     * @returns Promise resolving to whether the order was successfully canceled
     */
    public static async execute(apiKey: string): Promise<boolean> {
        const orderId = "DEMO-0009104390";

        try {
            const apiResponse: BaseResponse = await orderApi.cancelOrder({orderId});

            if (apiResponse.error) {
                console.error(apiResponse.error.developer_message);
                console.error(apiResponse.error.user_message);
                console.log("Order could not be canceled. See error log.");
                return false;
            }

            if (apiResponse.success) {
                console.log("Order was canceled successfully.");
                return true;
            }

            return false;
        } catch (error) {
            console.error("An error occurred while canceling the order:", error);
            return false;
        }
    }
}

// Example usage
async function cancelOrderExample() {
    const apiKey = "your-api-key-here"; // Replace with actual API key
    const result = await CancelOrder.execute(apiKey);
    console.log(result ? "Order cancellation successful" : "Order cancellation failed");
}

Duplicate an order

Permissions:
  • order_write

Produces: application/json
post
/order/orders/{order_id}/duplicate

Perform a duplicate of the specified order_id and return a new order located in Accounts Receivable.

SDK Function Name: duplicateOrder

Parameters
Parameter Description Location Data Type Required
order_id The order id to duplicate. path string required
_expand The object expansion to perform on the result. See documentation for examples query string optional
Responses
Status Code Reason Response Model
200
Successful response OrderResponse
400
Bad Request 400
401
Unauthorized 401
410
Authorized Application Disabled 410
429
Too Many Requests 429
500
Server Side 500
using System;
using System.Collections.Generic;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;

namespace SdkSample.order
{
    public class DuplicateOrder
    {
        /// <summary>
        /// OrderApi.DuplicateOrder() does not accomplish much on its own. The use-case for this method is to
        /// duplicate a customer's order and then charge them for it. DuplicateOrder() does not charge the customer again.
        ///
        /// These are the steps for cloning an existing order and charging the customer for it.
        /// 1. DuplicateOrder
        /// 2. UpdateOrder (if you wish to change any part of it)
        /// 3. ProcessPayment to charge the customer.
        ///
        /// As a reminder, if you wish to create a new order from scratch, use the CheckoutApi or ChannelPartnerApi.
        /// The OrderApi is for managing existing orders.
        /// </summary>
        public static void Execute()
        {
            OrderApi orderApi = new OrderApi(Constants.ApiKey);

            // For this example, we're going to change the items after we duplicate the order, so
            // the only expansion properties we need are the items.
            // See: https://www.ultracart.com/api/ for a list of all expansions.
            string expansion = "items";

            // Step 1. Duplicate the order
            string orderIdToDuplicate = "DEMO-0009104436";
            OrderResponse apiResponse = orderApi.DuplicateOrder(orderIdToDuplicate, expansion);
            Order newOrder = apiResponse.Order;

            // Step 2. Update the items. I will create a new items array and assign it to the order to remove the old ones completely.
            OrderItem[] items = new OrderItem[1];
            OrderItem item = new OrderItem();
            item.MerchantItemId = "simple_teapot";
            item.Quantity = 1;
            item.Description = "A lovely teapot";
            item.DistributionCenterCode = "DFLT"; // where is this item shipping out of?

            Currency cost = new Currency();
            cost.CurrencyCode = "USD";
            cost.Value = 9.99m;
            item.Cost = cost;

            Weight weight = new Weight();
            weight.Uom = Weight.UomEnum.OZ;
            weight.Value = 6;
            item.Weight = weight;
            
            newOrder.Items = new List<OrderItem>{item};
            OrderResponse updateResponse = orderApi.UpdateOrder(newOrder.OrderId, newOrder, expansion);

            Order updatedOrder = updateResponse.Order;

            // Step 3. process the payment.
            // the request object below takes two optional arguments.
            // The first is an amount if you wish to bill for an amount different from the order.
            // We do not bill differently in this example.
            // The second is card_verification_number_token, which is a token you can create by using our hosted fields to
            // upload a CVV value. This will create a token you may use here. However, most merchants using the duplicate
            // order method will be setting up an auto order for a customer. Those will not make use of the CVV, so we're
            // not including it here. That is why the request object below is does not have any values set.
            // For more info on hosted fields:
            // See: https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1377775/UltraCart+Hosted+Credit+Card+Fields
            // See: https://github.com/UltraCart/sdk_samples/blob/master/hosted_fields/hosted_fields.html

            OrderProcessPaymentRequest processPaymentRequest = new OrderProcessPaymentRequest();
            OrderProcessPaymentResponse paymentResponse = orderApi.ProcessPayment(newOrder.OrderId, processPaymentRequest);
            OrderPaymentTransaction transactionDetails = paymentResponse.PaymentTransaction; // do whatever you wish with this.

            Console.WriteLine("New Order (after updated items):");
            Console.WriteLine(updatedOrder);
            Console.WriteLine("Payment Response:");
            Console.WriteLine(paymentResponse);
        }
    }
}
package order;

import com.ultracart.admin.v2.OrderApi;
import com.ultracart.admin.v2.models.*;
import common.Constants;
import common.JSON;

import java.math.BigDecimal;
import java.util.ArrayList;

public class DuplicateOrder{

  public static void execute() throws Exception {

    // These are the steps for cloning an existing order and charging the customer for it.
    // 1. duplicateOrder
    // 2. updateOrder (if you wish to change any part of it)
    // 3. processPayment to charge the customer.
    //
    // As a reminder, if you wish to create a new order from scratch, use the CheckoutApi.
    // The OrderApi is for managing existing orders.

    OrderApi orderApi = new OrderApi(Constants.API_KEY, Constants.VERIFY_SSL_FLAG, Constants.DEBUG_MODE);

    String expansion = "items";
    // for this example, we're going to change the items after we duplicate the order, so
    // the only expansion properties we need are the items.
    // See: https://www.ultracart.com/api/  for a list of all expansions.

    // Step 1. Duplicate the order
    String orderIdToDuplicate = "DEMO-0009104436";
    OrderResponse apiResponse = orderApi.duplicateOrder(orderIdToDuplicate, expansion);
    Order newOrder = apiResponse.getOrder();

    // Step 2. Update the items.  I will create a new items array and assign it to the order to remove the old ones completely.
    ArrayList<OrderItem> orderItems = new ArrayList<>();
    
    OrderItem item = new OrderItem();
    
    item.setMerchantItemId("simple_teapot");
    item.setQuantity(BigDecimal.ONE);
    item.setDescription("A lovely teapot");
    item.setDistributionCenterCode("DFLT"); // where is this item shipping out of?

    Currency cost = new Currency();
    cost.setCurrencyCode("USD");
    cost.setValue(BigDecimal.valueOf(9.99));
    item.setCost(cost);

    Weight weight = new Weight();
    weight.setUom(Weight.UomEnum.OZ);
    weight.setValue(BigDecimal.valueOf(6));
    item.setWeight(weight);

    newOrder.setItems(orderItems);
    OrderResponse updateResponse = orderApi.updateOrder(newOrder.getOrderId(), newOrder, expansion);

    Order updatedOrder = updateResponse.getOrder();

    // Step 3. process the payment.
    // the request object below takes two optional arguments.
    // The first is an amount if you wish to bill for an amount different from the order.  We do not.
    // The second is card_verification_number_token, which is a token you can create by using our hosted fields to
    // upload a CVV value.  This will create a token you may use here.  However, most merchants using the duplicate
    // order method will be setting up an auto order for a customer.  Those will not make use of the CVV, so we're
    // not including it here.  That is why the request object below is does not have any values set.
    // For more info on hosted fields, see: https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1377775/UltraCart+Hosted+Credit+Card+Fields
    OrderProcessPaymentRequest request = new OrderProcessPaymentRequest();
    OrderProcessPaymentResponse paymentResponse = orderApi.processPayment(newOrder.getOrderId(), request);
    OrderPaymentTransaction transactionDetails = paymentResponse.getPaymentTransaction();
    
    System.out.println(JSON.toJSON(updatedOrder));
    System.out.println(JSON.toJSON(transactionDetails));

  }

}
import {orderApi} from '../api.js';

/**
 * OrderApi.DuplicateOrder() does not accomplish much on its own. The use-case for this method is to
 * duplicate a customer's order and then charge them for it. DuplicateOrder() does not charge the customer again.
 *
 * These are the steps for cloning an existing order and charging the customer for it.
 * 1. DuplicateOrder
 * 2. UpdateOrder (if you wish to change any part of it)
 * 3. ProcessPayment to charge the customer.
 *
 * As a reminder, if you wish to create a new order from scratch, use the CheckoutApi or ChannelPartnerApi.
 * The OrderApi is for managing existing orders.
 */
export async function execute() {
    try {
        // For this example, we're going to change the items after we duplicate the order, so
        // the only expansion properties we need are the items.
        // See: https://www.ultracart.com/api/ for a list of all expansions.
        const expansion = "items";

        // Step 1. Duplicate the order
        const orderIdToDuplicate = "DEMO-0009104436";
        const apiResponse = await new Promise((resolve, reject) => {
            orderApi.duplicateOrder(orderIdToDuplicate, {_expand: expansion}, function (error, data, response) {
                if (error) {
                    reject(error);
                } else {
                    resolve(data);
                }
            });
        });
        const newOrder = apiResponse.order;

        // Step 2. Update the items. Create a new items array and assign it to the order to remove the old ones completely.
        const item = {
            merchant_item_id: "simple_teapot",
            quantity: 1,
            description: "A lovely teapot",
            distribution_center_code: "DFLT", // where is this item shipping out of?
            cost: {
                currency_code: "USD",
                value: 9.99
            },
            weight: {
                uom: "OZ",
                value: 6
            }
        };

        newOrder.items = [item];
        const updateResponse = await new Promise((resolve, reject) => {
            orderApi.updateOrder(
                newOrder.order_id,
                newOrder,
                {_expand: expansion}
                , function (error, data, response) {
                    if (error) {
                        reject(error);
                    } else {
                        resolve(data);
                    }
                });
        });

        const updatedOrder = updateResponse.order;

        // Step 3. process the payment.
        // the request object below takes two optional arguments.
        // The first is an amount if you wish to bill for an amount different from the order.
        // We do not bill differently in this example.
        // The second is card_verification_number_token, which is a token you can create by using our hosted fields to
        // upload a CVV value. This will create a token you may use here. However, most merchants using the duplicate
        // order method will be setting up an auto order for a customer. Those will not make use of the CVV, so we're
        // not including it here. That is why the request object below is does not have any values set.
        // For more info on hosted fields:
        // See: https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1377775/UltraCart+Hosted+Credit+Card+Fields
        // See: https://github.com/UltraCart/sdk_samples/blob/master/hosted_fields/hosted_fields.html

        const processPaymentRequest = {};
        const paymentResponse = await new Promise((resolve, reject) => {
            orderApi.processPayment(
                newOrder.order_id,
                processPaymentRequest
                , function (error, data, response) {
                    if (error) {
                        reject(error);
                    } else {
                        resolve(data);
                    }
                });
        });

        // do whatever you wish with this
        const transactionDetails = paymentResponse.payment_transaction;

        console.log("New Order (after updated items):");
        console.log(JSON.stringify(updatedOrder, null, 2));
        console.log("Payment Response:");
        console.log(JSON.stringify(paymentResponse, null, 2));
    } catch (error) {
        console.error("An error occurred while duplicating and processing the order:", error);
    }
}
<?php /** @noinspection DuplicatedCode */

use ultracart\v2\api\OrderApi;
use ultracart\v2\models\OrderItem;
use ultracart\v2\models\Currency;
use ultracart\v2\models\Weight;
use ultracart\v2\models\OrderProcessPaymentRequest;


require_once '../vendor/autoload.php';
require_once '../samples.php';

$order_api = Samples::getOrderApi();

/*
 * OrderApi.duplicateOrder() does not accomplish much on its own.  The use-case for this method is to
 * duplicate a customer's order and then charge them for it.  duplicateOrder() does not charge the customer again.
 *
 * These are the steps for cloning an existing order and charging the customer for it.
 * 1. duplicateOrder
 * 2. updateOrder (if you wish to change any part of it)
 * 3. processPayment to charge the customer.
 *
 * As a reminder, if you wish to create a new order from scratch, use the CheckoutApi or ChannelPartnerApi.
 * The OrderApi is for managing existing orders.
 */


$expansion = "items";   // for this example, we're going to change the items after we duplicate the order, so
// the only expansion properties we need are the items.
// See: https://www.ultracart.com/api/  for a list of all expansions.

// Step 1. Duplicate the order
$order_id_to_duplicate = 'DEMO-0009104436';
$api_response = $order_api->duplicateOrder($order_id_to_duplicate, $expansion);
$new_order = $api_response->getOrder();

// Step 2. Update the items.  I will create a new items array and assign it to the order to remove the old ones completely.
$items = array();
$item = new OrderItem();
$item->setMerchantItemId('simple_teapot');
$item->setQuantity(1);
$item->setDescription("A lovely teapot");
$item->setDistributionCenterCode('DFLT'); // where is this item shipping out of?

$cost = new Currency();
$cost->setCurrencyCode('USD');
$cost->setValue(9.99);
$item->setCost($cost);

$weight = new Weight();
$weight->setUom("OZ");
$weight->setValue(6);
$item->setWeight($weight);

$items[] = $item;
$new_order->setItems($items);
$update_response = $order_api->updateOrder($new_order->getOrderId(), $new_order, $expansion);

$updated_order = $update_response->getOrder();

// Step 3. process the payment.
// the request object below takes two optional arguments.
// The first is an amount if you wish to bill for an amount different from the order.
// We do not bill differently in this example.
// The second is card_verification_number_token, which is a token you can create by using our hosted fields to
// upload a CVV value.  This will create a token you may use here.  However, most merchants using the duplicate
// order method will be setting up an auto order for a customer.  Those will not make use of the CVV, so we're
// not including it here.  That is why the request object below is does not have any values set.
// For more info on hosted fields:
// See: https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1377775/UltraCart+Hosted+Credit+Card+Fields
// See: https://github.com/UltraCart/sdk_samples/blob/master/hosted_fields/hosted_fields.html

$process_payment_request = new OrderProcessPaymentRequest();
$payment_response = $order_api->processPayment($new_order->getOrderId(), $process_payment_request);
$transaction_details = $payment_response->getPaymentTransaction(); // do whatever you wish with this.

echo '<html lang="en"><body><pre>';
echo 'New Order (after updated items):<br>';
var_dump($updated_order);
echo '<br>Payment Response:<br>';
var_dump($payment_response);
echo '</pre></body></html>';
from ultracart.apis import OrderApi
from ultracart.model.currency import Currency
from ultracart.model.order_item import OrderItem
from ultracart.model.order_process_payment_request import OrderProcessPaymentRequest
from ultracart.model.weight import Weight
from pprint import pprint
from samples import api_client

# These are the steps for cloning an existing order and charging the customer for it.
# 1. duplicateOrder
# 2. updateOrder (if you wish to change any part of it)
# 3. processPayment to charge the customer.
#
# As a reminder, if you wish to create a new order from scratch, use the CheckoutApi.
# The OrderApi is for managing existing orders.

api_instance = OrderApi(api_client())

expansion = "items"
# for this example, we're going to change the items after we duplicate the order, so
# the only expansion properties we need are the items.
# See: https://www.ultracart.com/api/  for a list of all expansions.

# Step 1. Duplicate the order
order_id_to_duplicate = 'DEMO-0009104436'
api_response = api_instance.duplicate_order(order_id_to_duplicate, expand=expansion)
new_order = api_response.order


# Step 2. Update the items.  I will create a new items array and assign it to the order to remove the old ones completely.
items = []
item = OrderItem()
item.merchant_item_id = 'simple_teapot'
item.quantity = 1.0
item.description = "A lovely teapot"
item.distribution_center_code = 'DFLT'  # where is this item shipping out of?

cost = Currency()
cost.currency_code = 'USD'
cost.value = 9.99
item.cost = cost

weight = Weight()
weight.uom = 'OZ'
weight.value = 6.0
item.weight = weight

items.append(item)
new_order.items = items
update_response = api_instance.update_order(order_id=new_order.order_id, order=new_order, expand=expansion)
updated_order = update_response.order


# Step 3. process the payment.
# the request object below takes two optional arguments.
# The first is an amount if you wish to bill for an amount different from the order.  We do not.
# The second is card_verification_number_token, which is a token you can create by using our hosted fields to
# upload a CVV value.  This will create a token you may use here.  However, most merchants using the duplicate
# order method will be setting up an auto order for a customer.  Those will not make use of the CVV, so we're
# not including it here.  That is why the request object below is does not have any values set.
# For more info on hosted fields, see: https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1377775/UltraCart+Hosted+Credit+Card+Fields

process_payment_request = OrderProcessPaymentRequest()
payment_response = api_instance.process_payment(new_order.order_id, process_payment_request)
if payment_response.error:
    print(payment_response.error.developer_message)
else:
    transaction_details = payment_response.payment_transaction  # do whatever you wish with this.
    pprint(updated_order)
    pprint(transaction_details)



# OrderApi.duplicate_order() does not accomplish much on its own.  The use-case for this method is to
# duplicate a customer's order and then charge them for it.  duplicate_order() does not charge the customer again.
#
# These are the steps for cloning an existing order and charging the customer for it.
# 1. duplicate_order
# 2. update_order (if you wish to change any part of it)
# 3. process_payment to charge the customer.
#
# As a reminder, if you wish to create a new order from scratch, use the CheckoutApi or ChannelPartnerApi.
# The OrderApi is for managing existing orders.

require_relative '../constants'
require 'ultracart_api'

order_api = UltracartClient::OrderApi.new_using_api_key(Constants::API_KEY)

# Step 1. Duplicate the order
expansion = '_expand=items'   # for this example, we're going to change the items after we duplicate the order, so
# the only expansion properties we need are the items.
# See: https://www.ultracart.com/api/  for a list of all expansions.

order_id_to_duplicate = 'DEMO-0009104436'
api_response = order_api.duplicate_order(order_id_to_duplicate, { '_expand' => expansion })
new_order = api_response.get_order

# Step 2. Update the items. Create a new items array and assign it to the order to remove the old ones completely.
items = []
item = UltracartClient::OrderItem.new
item.set_merchant_item_id('simple_teapot')
item.set_quantity(1)
item.set_description("A lovely teapot")
item.set_distribution_center_code('DFLT') # where is this item shipping out of?

cost = UltracartClient::Currency.new
cost.set_currency_code('USD')
cost.set_value(9.99)
item.set_cost(cost)

weight = UltracartClient::Weight.new
weight.set_uom("OZ")
weight.set_value(6)
item.set_weight(weight)

items << item
new_order.set_items(items)
update_response = order_api.update_order(new_order.get_order_id, new_order, { '_expand' => expansion })

updated_order = update_response.get_order

# Step 3. process the payment.
# the request object below takes two optional arguments.
# The first is an amount if you wish to bill for an amount different from the order.
# We do not bill differently in this example.
# The second is card_verification_number_token, which is a token you can create by using our hosted fields to
# upload a CVV value.  This will create a token you may use here.  However, most merchants using the duplicate
# order method will be setting up an auto order for a customer.  Those will not make use of the CVV, so we're
# not including it here.  That is why the request object below does not have any values set.
# For more info on hosted fields:
# See: https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1377775/UltraCart+Hosted+Credit+Card+Fields
# See: https://github.com/UltraCart/sdk_samples/blob/master/hosted_fields/hosted_fields.html

process_payment_request = UltracartClient::OrderProcessPaymentRequest.new
payment_response = order_api.process_payment(new_order.get_order_id, process_payment_request)
transaction_details = payment_response.get_payment_transaction # do whatever you wish with this.

puts 'New Order (after updated items):'
p updated_order
puts '\nPayment Response:'
p payment_response
import { orderApi } from '../api';
import { 
    Order, 
    OrderItem, 
    Currency, 
    Weight, 
    OrderResponse, 
    OrderProcessPaymentRequest, 
    OrderProcessPaymentResponse 
} from 'ultracart_rest_api_v2_typescript';

/**
 * OrderApi.DuplicateOrder() does not accomplish much on its own. The use-case for this method is to
 * duplicate a customer's order and then charge them for it. DuplicateOrder() does not charge the customer again.
 *
 * These are the steps for cloning an existing order and charging the customer for it.
 * 1. DuplicateOrder
 * 2. UpdateOrder (if you wish to change any part of it)
 * 3. ProcessPayment to charge the customer.
 *
 * As a reminder, if you wish to create a new order from scratch, use the CheckoutApi or ChannelPartnerApi.
 * The OrderApi is for managing existing orders.
 */
export async function execute(): Promise<void> {
    try {
        // For this example, we're going to change the items after we duplicate the order, so
        // the only expansion properties we need are the items.
        // See: https://www.ultracart.com/api/ for a list of all expansions.
        const expansion = "items";

        // Step 1. Duplicate the order
        const orderIdToDuplicate = "DEMO-0009104436";
        const apiResponse: OrderResponse = await orderApi.duplicateOrder({
            orderId: orderIdToDuplicate,
            expand: expansion
        });
        const newOrder: Order = apiResponse.order!;

        // Step 2. Update the items. Create a new items array and assign it to the order to remove the old ones completely.
        const item: OrderItem = {
            merchant_item_id: "simple_teapot",
            quantity: 1,
            description: "A lovely teapot",
            distribution_center_code: "DFLT", // where is this item shipping out of?
            cost: {
                currency_code: "USD",
                value: 9.99
            },
            weight: {
                uom: "OZ",
                value: 6
            }
        };

        newOrder.items = [item];
        const updateResponse: OrderResponse = await orderApi.updateOrder({
            orderId: newOrder.order_id!,
            order: newOrder,
            expand: expansion
        });

        const updatedOrder: Order = updateResponse.order!;

        // Step 3. process the payment.
        // the request object below takes two optional arguments.
        // The first is an amount if you wish to bill for an amount different from the order.
        // We do not bill differently in this example.
        // The second is card_verification_number_token, which is a token you can create by using our hosted fields to
        // upload a CVV value. This will create a token you may use here. However, most merchants using the duplicate
        // order method will be setting up an auto order for a customer. Those will not make use of the CVV, so we're
        // not including it here. That is why the request object below is does not have any values set.
        // For more info on hosted fields:
        // See: https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1377775/UltraCart+Hosted+Credit+Card+Fields
        // See: https://github.com/UltraCart/sdk_samples/blob/master/hosted_fields/hosted_fields.html

        const processPaymentRequest: OrderProcessPaymentRequest = {};
        const paymentResponse: OrderProcessPaymentResponse = await orderApi.processPayment({
            orderId: newOrder.order_id!,
            processPaymentRequest: processPaymentRequest
        });
        
        // do whatever you wish with this
        const transactionDetails = paymentResponse.payment_transaction;

        console.log("New Order (after updated items):");
        console.log(JSON.stringify(updatedOrder, null, 2));
        console.log("Payment Response:");
        console.log(JSON.stringify(paymentResponse, null, 2));
    } catch (error) {
        console.error("An error occurred while duplicating and processing the order:", error);
    }
}

Retrieve EDI documents associated with this order.

Permissions:
  • order_write

Consumes: application/json
Produces: application/json
get
/order/orders/{order_id}/edi

Retrieve EDI documents associated with this order.

SDK Function Name: getOrderEdiDocuments

Parameters
Parameter Description Location Data Type Required
order_id The order id to retrieve EDI documents for. path string required
Responses
Status Code Reason Response Model
200
Successful response OrderEdiDocumentsResponse
400
Bad Request 400
401
Unauthorized 401
410
Authorized Application Disabled 410
429
Too Many Requests 429
500
Server Side 500
using System;
using System.Collections.Generic;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;
using Newtonsoft.Json;

namespace SdkSample.order
{
    public class GetOrderEdiDocuments
    {
        /*
            getOrderEdiDocuments returns back all EDI documents associated with an order.

            Possible Errors:
            Order.channelPartnerOid is null -> "Order is not associated with an EDI channel partner."
         */
        public static void Execute()
        {
            OrderApi orderApi = new OrderApi(Constants.ApiKey);

            string orderId = "DEMO-0009104976";
            OrderEdiDocumentsResponse response = orderApi.GetOrderEdiDocuments(orderId);
            List<OrderEdiDocument> documents = response.EdiDocuments;

            foreach (OrderEdiDocument doc in documents)
            {
                Console.WriteLine(JsonConvert.SerializeObject(doc,
                    new JsonSerializerSettings { Formatting = Formatting.Indented }));
            }
            
        }
    }
}
package order;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.ultracart.admin.v2.OrderApi;
import com.ultracart.admin.v2.models.*;
import com.ultracart.admin.v2.util.ApiException;
import java.util.List;

public class GetOrderEdiDocuments {
   /*
       getOrderEdiDocuments returns back all EDI documents associated with an order.

       Possible Errors:
       Order.channelPartnerOid is null -> "Order is not associated with an EDI channel partner."
    */
   public void execute() throws ApiException {
       OrderApi orderApi = new OrderApi(common.Constants.API_KEY);

       String orderId = "DEMO-0009104976";
       OrderEdiDocumentsResponse response = orderApi.getOrderEdiDocuments(orderId);
       List<OrderEdiDocument> documents = response.getEdiDocuments();

       Gson gson = new GsonBuilder().setPrettyPrinting().create();
       for (OrderEdiDocument doc : documents) {
           System.out.println(gson.toJson(doc));
       }
   }
}
import {orderApi} from '../api.js';

/**
 * getOrderEdiDocuments returns back all EDI documents associated with an order.
 *
 * Possible Errors:
 * Order.channelPartnerOid is null -> "Order is not associated with an EDI channel partner."
 */
export async function execute() {
    const orderId = "DEMO-0009104976";

    try {
        const response = await new Promise((resolve, reject) => {
            orderApi.getOrderEdiDocuments(
                orderId
                , function (error, data, response) {
                    if (error) {
                        reject(error);
                    } else {
                        resolve(data);
                    }
                });
        });

        const documents = response.ediDocuments || [];

        for (const doc of documents) {
            console.log(JSON.stringify(doc, null, 2));
        }
    } catch (error) {
        console.error('Error fetching EDI documents:', error);
    }
}
<?php

ini_set('display_errors', 1);

use ultracart\v2\api\OrderApi;

require_once '../vendor/autoload.php';
require_once '../constants.php';

/*
    getOrderEdiDocuments returns back all EDI documents associated with an order.

    Possible Errors:
    Order.channelPartnerOid is null -> "Order is not associated with an EDI channel partner."

 */


$order_api = OrderApi::usingApiKey(Constants::API_KEY, false, false);


$order_id = 'DEMO-0009104976';
$documents = $order_api->getOrderEdiDocuments($order_id)->getEdiDocuments();

echo '<html lang="en"><body><pre>';
var_dump($documents);
echo '</pre></body></html>';

from ultracart.apis import OrderApi
from samples import api_client

# get_order_edi_documents() returns all EDI documents associated with an order.
#
# Possible Errors:
# Order.channel_partner_oid is null -> "Order is not associated with an EDI channel partner."

# Create Order API instance
order_api = OrderApi(api_client())

# Order ID to retrieve EDI documents for
order_id = "DEMO-0009104976"

# Retrieve EDI documents
edi_documents = order_api.get_order_edi_documents(order_id).edi_documents

# Print EDI documents
print(edi_documents)

require 'ultracart_api'
require_relative '../constants'

# getOrderEdiDocuments returns back all EDI documents associated with an order.
#
# Possible Errors:
# Order.channelPartnerOid is null -> "Order is not associated with an EDI channel partner."
order_api = UltracartClient::OrderApi.new_using_api_key(Constants::API_KEY)

order_id = 'DEMO-0009104976'

begin
  api_response = order_api.get_order_edi_documents(order_id)
  documents = api_response.edi_documents

  # Using inspect instead of var_dump for Ruby-style object representation
  puts documents.inspect
rescue StandardError => e
  puts "An error occurred: #{e.message}"
end
import { orderApi } from '../api';
import {
    OrderEdiDocumentsResponse,
    OrderEdiDocument
} from 'ultracart_rest_api_v2_typescript';

/**
 * getOrderEdiDocuments returns back all EDI documents associated with an order.
 *
 * Possible Errors:
 * Order.channelPartnerOid is null -> "Order is not associated with an EDI channel partner."
 */
export async function execute(): Promise<void> {
    const orderId = "DEMO-0009104976";

    try {
        const response: OrderEdiDocumentsResponse = await orderApi.getOrderEdiDocuments({
            orderId: orderId
        });

        const documents: OrderEdiDocument[] = response.ediDocuments || [];

        for (const doc of documents) {
            console.log(JSON.stringify(doc, null, 2));
        }
    } catch (error) {
        console.error('Error fetching EDI documents:', error);
    }
}

Format order

Permissions:
  • order_read

Produces: application/json
post
/order/orders/{order_id}/format

Format the order for display at text or html

SDK Function Name: format

Parameters
Parameter Description Location Data Type Required
order_id The order id to format path string required
format_options Format options body OrderFormat required
Responses
Status Code Reason Response Model
200
Successful response OrderFormatResponse
400
Bad Request 400
401
Unauthorized 401
410
Authorized Application Disabled 410
429
Too Many Requests 429
500
Server Side 500
using System;
using System.Collections.Generic;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;

namespace SdkSample.order
{
    public class Format
    {
        public static void Execute()
        {
            /*
             * format() returns back a text-formatted or html block for displaying an order. It is similar to what you would
             * see on a receipt page.
             */

            OrderApi orderApi = new OrderApi(Constants.ApiKey);

            OrderFormat formatOptions = new OrderFormat();
            formatOptions.Context = "receipt"; // unknown,receipt,shipment,refund,quote-request,quote
            formatOptions.Format = OrderFormat.FormatEnum.Table; // text,div,table,email
            formatOptions.ShowContactInfo = false;
            formatOptions.ShowPaymentInfo = false; // might not want to show this to just anyone.
            formatOptions.ShowMerchantNotes = false; // be careful showing these
            formatOptions.EmailAsLink = true; // makes the email addresses web links
            // if you only wish to show the items for a particular distribution center,
            // this might be useful if you have Context='shipment' and you're displaying this order to a fulfillment center, etc
            // formatOptions.FilterDistributionCenterOid = 1234321;
            formatOptions.LinkFileAttachments = true;
            formatOptions.ShowInternalInformation = true; // consider this carefully.
            formatOptions.ShowNonSensitivePaymentInfo = true; // what the customer usually sees
            formatOptions.ShowInMerchantCurrency = true;
            formatOptions.HideBillToAddress = false;
            // formatOptions.FilterToItemsInContainerOid = 123454321; // you probably won't need this.
            // when an order displays on the secure.ultracart.com site, we link the email to our order search so you can quickly
            // search for all orders for that email. I doubt you would have use for that. But maybe.
            formatOptions.DontLinkEmailToSearch = true;
            formatOptions.Translate = false; // if true, shows in customer's native language

            string orderId = "DEMO-0009104390";

            OrderFormatResponse apiResponse = orderApi.Format(orderId, formatOptions);
            
            string formattedResult = apiResponse.FormattedResult;
            Console.WriteLine("<html lang=\"en\">");
            Console.WriteLine("<head>");
            // you won't have css links for format=table
            foreach (string link in apiResponse.CssLinks)
            {
                Console.WriteLine("<style type=\"text/css\">" + link + "</style>");
            }
            Console.WriteLine("</head><body>");
            Console.WriteLine(formattedResult);
            Console.WriteLine("</body></html>");
        }
    }
}
package order;

import com.ultracart.admin.v2.OrderApi;
import com.ultracart.admin.v2.models.*;
import com.ultracart.admin.v2.util.ApiException;
import common.Constants;

public class Format {
   public static void execute() throws ApiException {
       /*
        * format() returns back a text-formatted or html block for displaying an order. It is similar to what you would
        * see on a receipt page.
        */

       OrderApi orderApi = new OrderApi(Constants.API_KEY);

       OrderFormat formatOptions = new OrderFormat();
       formatOptions.setContext("receipt"); // unknown,receipt,shipment,refund,quote-request,quote
       formatOptions.setFormat(OrderFormat.FormatEnum.TABLE); // text,div,table,email
       formatOptions.setShowContactInfo(false);
       formatOptions.setShowPaymentInfo(false); // might not want to show this to just anyone.
       formatOptions.setShowMerchantNotes(false); // be careful showing these
       formatOptions.setEmailAsLink(true); // makes the email addresses web links
       // if you only wish to show the items for a particular distribution center,
       // this might be useful if you have Context='shipment' and you're displaying this order to a fulfillment center, etc
       // formatOptions.setFilterDistributionCenterOid(1234321);
       formatOptions.setLinkFileAttachments(true);
       formatOptions.setShowInternalInformation(true); // consider this carefully.
       formatOptions.setShowNonSensitivePaymentInfo(true); // what the customer usually sees
       formatOptions.setShowInMerchantCurrency(true);
       formatOptions.setHideBillToAddress(false);
       // formatOptions.setFilterToItemsInContainerOid(123454321); // you probably won't need this.
       // when an order displays on the secure.ultracart.com site, we link the email to our order search so you can quickly
       // search for all orders for that email. I doubt you would have use for that. But maybe.
       formatOptions.setDontLinkEmailToSearch(true);
       formatOptions.setTranslate(false); // if true, shows in customer's native language

       String orderId = "DEMO-0009104390";

       OrderFormatResponse apiResponse = orderApi.format(orderId, formatOptions);
       
       String formattedResult = apiResponse.getFormattedResult();
       System.out.println("<html lang=\"en\">");
       System.out.println("<head>");
       // you won't have css links for format=table
       for (String link : apiResponse.getCssLinks()) {
           System.out.println("<style type=\"text/css\">" + link + "</style>");
       }
       System.out.println("</head><body>");
       System.out.println(formattedResult);
       System.out.println("</body></html>");
   }
}
import { orderApi } from '../api.js';

export class Format {
    /**
     * format() returns back a text-formatted or html block for displaying an order. It is similar to what you would
     * see on a receipt page.
     */
    static async execute() {
        // Create format options
        const formatOptions = {
            context: 'receipt', // unknown,receipt,shipment,refund,quote-request,quote
            format: 'table', // text,div,table,email
            show_contact_info: false,
            show_payment_info: false, // might not want to show this to just anyone.
            show_merchant_notes: false, // be careful showing these
            email_as_link: true, // makes the email addresses web links

            // if you only wish to show the items for a particular distribution center,
            // this might be useful if you have Context='shipment' and you're displaying this order to a fulfillment center, etc
            // filterDistributionCenterOid: 1234321,

            link_file_attachments: true,
            show_internal_information: true, // consider this carefully.
            show_non_sensitive_payment_info: true, // what the customer usually sees
            show_in_merchant_currency: true,
            hide_bill_to_address: false,

            // filterToItemsInContainerOid: 123454321, // you probably won't need this.

            // when an order displays on the secure.ultracart.com site, we link the email to our order search so you can quickly
            // search for all orders for that email. I doubt you would have use for that. But maybe.
            dont_link_email_to_search: true,
            translate: false // if true, shows in customer's native language
        };

        const orderId = 'DEMO-0009104390';

        try {
            // Await the API call
            const apiResponse = await new Promise((resolve, reject) => {
                orderApi.format(
                    orderId,
                    formatOptions
                , function (error, data, response) {
                    if (error) {
                        reject(error);
                    } else {
                        resolve(data);
                    }
                });
            });

            const formattedResult = apiResponse.formatted_result;

            // Construct HTML output
            console.log('<html lang="en">');
            console.log('<head>');

            // you won't have css links for format=table
            if (apiResponse.css_links) {
                apiResponse.css_links.forEach(link => {
                    console.log(`<style type="text/css">${link}</style>`);
                });
            }

            console.log('</head><body>');
            console.log(formattedResult);
            console.log('</body></html>');
        } catch (error) {
            console.error('Error formatting order:', error);
        }
    }
}

// Optional: If you want to call the method
// Format.execute();
<?php

ini_set('display_errors', 1);

/*
 * format() returns back a text-formatted or html block for displaying an order.  It is similar to what you would
 * see on a receipt page.
 */

use ultracart\v2\api\OrderApi;
use ultracart\v2\models\OrderFormat;

require_once '../vendor/autoload.php';
require_once '../constants.php';


$order_api = OrderApi::usingApiKey(Constants::API_KEY);


$format_options = new OrderFormat();
$format_options->setContext('receipt'); // unknown,receipt,shipment,refund,quote-request,quote
$format_options->setFormat('table'); // text,div,table,email
$format_options->setShowContactInfo(false);
$format_options->setShowPaymentInfo(false); // might not want to show this to just anyone.
$format_options->setShowMerchantNotes(false); // be careful showing these
$format_options->setEmailAsLink(true); // makes the email addresses web links
// if you only wish to show the items for a particular distribution center,
// this might be useful if you have setContext('shipment') and you're displaying this order to a fulfillment center, etc
// $format_options->setFilterDistributionCenterOid(1234321);
$format_options->setLinkFileAttachments(true);
$format_options->setShowInternalInformation(true); // consider this carefully.
$format_options->setShowNonSensitivePaymentInfo(true); // what the customer usually sees
$format_options->setShowInMerchantCurrency(true);
$format_options->setHideBillToAddress(false);
// $format_options->setFilterToItemsInContainerOid(123454321); // you probably won't need this.
// when an order displays on the secure.ultracart.com site, we link the email to our order search so you can quickly
// search for all orders for that email.  I doubt you would have use for that.  But maybe.
$format_options->setDontLinkEmailToSearch(true);
$format_options->setTranslate(false); // if true, shows in customer's native language


$order_id = 'DEMO-0009104390';


$api_response = $order_api->format($order_id, $format_options);

$formatted_result = $api_response->getFormattedResult();
echo '<html lang="en">';
echo '<head>';
// you won't have css links for format=table
foreach($api_response->getCssLinks() as $link){
    echo '<style type="text/css">' . $link . '</style>';
}
echo '</head><body>';
echo $formatted_result;
echo '</body></html>';

"""
Format an order for display with various customization options.

Returns a text or HTML-formatted block similar to a receipt page.
"""

from samples import api_client
from ultracart.apis import OrderApi
from ultracart.models import OrderFormat
from ultracart import ApiException
import logging

# Configure logging
logging.basicConfig(level=logging.ERROR)
logger = logging.getLogger(__name__)

try:
    # Initialize Order API
    order_api = OrderApi(api_client())

    # Configure format options
    format_options = OrderFormat(
        context='receipt',  # Options: unknown,receipt,shipment,refund,quote-request,quote
        format='table',     # Options: text,div,table,email
        show_contact_info=False,
        show_payment_info=False,
        show_merchant_notes=False,
        email_as_link=True,
        link_file_attachments=True,
        show_internal_information=True,
        show_non_sensitive_payment_info=True,
        show_in_merchant_currency=True,
        hide_bill_to_address=False,
        dont_link_email_to_search=True,
        translate=False
    )

    # Specify order ID
    order_id = 'DEMO-0009104390'

    # Format the order
    api_response = order_api.format(order_id, format_options)

    # Get formatted result
    formatted_result = api_response.formatted_result

    # Print CSS links (if needed)
    for link in api_response.css_links:
        print(f'CSS Link: {link}')

    # Print formatted result
    print(formatted_result)

except ApiException as e:
    logger.error(f"API Exception: {e}")
    print('Order formatting failed.')
# format() returns back a text-formatted or html block for displaying an order.  It is similar to what you would
# see on a receipt page.

require_relative '../constants'
require 'ultracart_api'

order_api = UltracartClient::OrderApi.new_using_api_key(Constants::API_KEY)

# Configure format options
format_options = UltracartClient::OrderFormat.new
format_options.set_context('receipt') # unknown,receipt,shipment,refund,quote-request,quote
format_options.set_format('table') # text,div,table,email
format_options.set_show_contact_info(false)
format_options.set_show_payment_info(false) # might not want to show this to just anyone.
format_options.set_show_merchant_notes(false) # be careful showing these
format_options.set_email_as_link(true) # makes the email addresses web links
# if you only wish to show the items for a particular distribution center,
# this might be useful if you have set_context('shipment') and you're displaying this order to a fulfillment center, etc
# format_options.set_filter_distribution_center_oid(1234321)
format_options.set_link_file_attachments(true)
format_options.set_show_internal_information(true) # consider this carefully.
format_options.set_show_non_sensitive_payment_info(true) # what the customer usually sees
format_options.set_show_in_merchant_currency(true)
format_options.set_hide_bill_to_address(false)
# format_options.set_filter_to_items_in_container_oid(123454321) # you probably won't need this.
# when an order displays on the secure.ultracart.com site, we link the email to our order search so you can quickly
# search for all orders for that email.  I doubt you would have use for that.  But maybe.
format_options.set_dont_link_email_to_search(true)
format_options.set_translate(false) # if true, shows in customer's native language

order_id = 'DEMO-0009104390'

api_response = order_api.format(order_id, format_options)

formatted_result = api_response.get_formatted_result

# Render the formatted result (note: removed HTML wrapping per guidelines)
api_response.get_css_links.each do |link|
  puts "<style type='text/css'>#{link}</style>"
end
puts formatted_result
import { orderApi } from '../api';
import { OrderFormat, OrderFormatResponse } from 'ultracart_rest_api_v2_typescript';

export class Format {
    /**
     * format() returns back a text-formatted or html block for displaying an order. It is similar to what you would
     * see on a receipt page.
     */
    public static async execute(): Promise<void> {
        // Create format options
        const formatOptions: OrderFormat = {
            context: 'receipt', // unknown,receipt,shipment,refund,quote-request,quote
            format: 'table', // text,div,table,email
            show_contact_info: false,
            show_payment_info: false, // might not want to show this to just anyone.
            show_merchant_notes: false, // be careful showing these
            email_as_link: true, // makes the email addresses web links

            // if you only wish to show the items for a particular distribution center,
            // this might be useful if you have Context='shipment' and you're displaying this order to a fulfillment center, etc
            // filterDistributionCenterOid: 1234321,

            link_file_attachments: true,
            show_internal_information: true, // consider this carefully.
            show_non_sensitive_payment_info: true, // what the customer usually sees
            show_in_merchant_currency: true,
            hide_bill_to_address: false,

            // filterToItemsInContainerOid: 123454321, // you probably won't need this.

            // when an order displays on the secure.ultracart.com site, we link the email to our order search so you can quickly
            // search for all orders for that email. I doubt you would have use for that. But maybe.
            dont_link_email_to_search: true,
            translate: false // if true, shows in customer's native language
        };

        const orderId = 'DEMO-0009104390';

        try {
            // Await the API call
            const apiResponse: OrderFormatResponse = await orderApi.format({orderId, formatOptions});

            const formattedResult = apiResponse.formatted_result;

            // Construct HTML output
            console.log('<html lang="en">');
            console.log('<head>');

            // you won't have css links for format=table
            if (apiResponse.css_links) {
                apiResponse.css_links.forEach(link => {
                    console.log(`<style type="text/css">${link}</style>`);
                });
            }

            console.log('</head><body>');
            console.log(formattedResult);
            console.log('</body></html>');
        } catch (error) {
            console.error('Error formatting order:', error);
        }
    }
}

// Optional: If you want to call the method
// Format.execute();

Generate an invoice for this order.

Permissions:
  • order_read

Produces: application/json
get
/order/orders/{order_id}/invoice

The invoice PDF that is returned is base 64 encoded

SDK Function Name: generateInvoice

Parameters
Parameter Description Location Data Type Required
order_id Order ID path string required
Responses
Status Code Reason Response Model
200
Successful response OrderInvoiceResponse
400
Bad Request 400
401
Unauthorized 401
410
Authorized Application Disabled 410
429
Too Many Requests 429
500
Server Side 500
using System;
using System.IO;
using System.Net;
using System.Text;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;

namespace SdkSample.order
{
    public class GenerateInvoice
    {
        public static void Execute()
        {
            /*
                generateInvoice returns back a base64 encoded byte array of the given order's Invoice in PDF format.
            */

            OrderApi orderApi = new OrderApi(Constants.ApiKey);

            string orderId = "DEMO-0009104976";
            OrderInvoiceResponse apiResponse = orderApi.GenerateInvoice(orderId);

            // the invoice will return as a base64 encoded
            // unpack, save off, email, whatever.
            string base64Pdf = apiResponse.PdfBase64;

            byte[] decodedPdf = Convert.FromBase64String(base64Pdf);
            File.WriteAllBytes("invoice.pdf", decodedPdf);

            // If this is running as a web application, you could return the PDF to the browser
            // using something like this (this is ASP.NET-specific code):
            /*
            HttpContext.Current.Response.ContentType = "application/pdf";
            HttpContext.Current.Response.AddHeader("Content-Disposition", "inline; filename=\"invoice.pdf\"");
            HttpContext.Current.Response.AddHeader("Cache-Control", "public, must-revalidate, max-age=0");
            HttpContext.Current.Response.AddHeader("Pragma", "public");
            HttpContext.Current.Response.AddHeader("Content-Length", decodedPdf.Length.ToString());
            HttpContext.Current.Response.BinaryWrite(decodedPdf);
            HttpContext.Current.Response.End();
            */

            Console.WriteLine("Invoice PDF saved to invoice.pdf");
        }
    }
}
package order;

import com.ultracart.admin.v2.OrderApi;
import com.ultracart.admin.v2.models.OrderInvoiceResponse;
import com.ultracart.admin.v2.util.ApiException;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;

public class GenerateInvoice {
   public void execute() throws IOException, ApiException {
       /*
           generateInvoice returns back a base64 encoded byte array of the given order's Invoice in PDF format.
       */

       OrderApi orderApi = new OrderApi(common.Constants.API_KEY);

       String orderId = "DEMO-0009104976";
       OrderInvoiceResponse apiResponse = orderApi.generateInvoice(orderId);

       // the invoice will return as a base64 encoded
       // unpack, save off, email, whatever.
       String base64Pdf = apiResponse.getPdfBase64();

       byte[] decodedPdf = Base64.getDecoder().decode(base64Pdf);
       try (FileOutputStream fos = new FileOutputStream("invoice.pdf")) {
           fos.write(decodedPdf);
       }

       // If this is running as a web application, you could return the PDF to the browser
       // using something like this (this is Java Servlet-specific code):
       /*
       response.setContentType("application/pdf");
       response.setHeader("Content-Disposition", "inline; filename=\"invoice.pdf\"");
       response.setHeader("Cache-Control", "public, must-revalidate, max-age=0");
       response.setHeader("Pragma", "public");
       response.setHeader("Content-Length", String.valueOf(decodedPdf.length));
       response.getOutputStream().write(decodedPdf);
       response.getOutputStream().flush();
       */

       System.out.println("Invoice PDF saved to invoice.pdf");
   }
}
import {orderApi} from '../api.js';
import fs from 'fs/promises';

export class GenerateInvoice {
    /**
     * generateInvoice returns back a base64 encoded byte array of the given order's Invoice in PDF format.
     */
    static async execute() {
        const orderId = 'DEMO-0009104976';

        try {
            // Await the API call
            const apiResponse = await new Promise((resolve, reject) => {
                orderApi.generateInvoice(
                    orderId
                    , function (error, data, response) {
                        if (error) {
                            reject(error);
                        } else {
                            resolve(data);
                        }
                    });
            });

            // the invoice will return as a base64 encoded
            // unpack, save off, email, whatever.
            const base64PdfOrUndefined = apiResponse.pdfBase64;
            if (base64PdfOrUndefined !== undefined) {
                const base64Pdf = base64PdfOrUndefined;
                // Decode base64 to buffer
                const decodedPdf = Buffer.from(base64Pdf, 'base64');

                // Write PDF to file
                await fs.writeFile('invoice.pdf', decodedPdf);

                // If this is running as a web application, you could return the PDF to the browser
                // using something like this (this is Express.js-specific code):
                /*
                app.get('/invoice', async (req, res) => {
                    res.contentType('application/pdf');
                    res.setHeader('Content-Disposition', 'inline; filename="invoice.pdf"');
                    res.setHeader('Cache-Control', 'public, must-revalidate, max-age=0');
                    res.setHeader('Pragma', 'public');
                    res.send(decodedPdf);
                });
                */

                console.log('Invoice PDF saved to invoice.pdf');
            }
        } catch (error) {
            console.error('Error generating invoice:', error);
        }
    }
}

// Optional: If you want to call the method
// GenerateInvoice.execute();
<?php

ini_set('display_errors', 1);

use ultracart\v2\api\OrderApi;

require_once '../vendor/autoload.php';
require_once '../constants.php';

/*
    generateInvoice returns back a base64 encoded byte array of the given order's Invoice in PDF format.

 */

$order_api = OrderApi::usingApiKey(Constants::API_KEY, false, false);


$order_id = 'DEMO-0009104976';
$api_response = $order_api->generateInvoice($order_id);

// the packing slip will return as a base64 encoded
// unpack, save off, email, whatever.
$base64_pdf = $api_response->getPdfBase64();

$decoded_pdf = base64_decode($base64_pdf);
file_put_contents('invoice.pdf', $decoded_pdf);


// Set the PDF headers
header('Content-Type: application/pdf');
header('Content-Disposition: inline; filename="invoice.pdf"');
header('Cache-Control: public, must-revalidate, max-age=0');
header('Pragma: public');
header('Content-Length: ' . strlen($decoded_pdf));

// Output the PDF bytes
echo $decoded_pdf;
exit;

from ultracart.apis import OrderApi
from samples import api_client
import base64

# Create Order API instance
order_api = OrderApi(api_client())

# Define order ID
order_id = 'DEMO-0009104976'

# Generate invoice (returns a base64-encoded PDF)
api_response = order_api.generate_invoice(order_id)
base64_pdf = api_response.pdf_base64

# Decode and save the PDF
decoded_pdf = base64.b64decode(base64_pdf)
with open('invoice.pdf', 'wb') as pdf_file:
    pdf_file.write(decoded_pdf)

print("Invoice PDF saved as 'invoice.pdf'.")

# generate_invoice returns back a base64 encoded byte array of the given order's Invoice in PDF format.

require_relative '../constants'
require 'base64'
require 'ultracart_api'

order_api = UltracartClient::OrderApi.new_using_api_key(Constants::API_KEY)

order_id = 'DEMO-0009104976'
api_response = order_api.generate_invoice(order_id)

# the packing slip will return as a base64 encoded
# unpack, save off, email, whatever.
base64_pdf = api_response.get_pdf_base64

decoded_pdf = Base64.decode64(base64_pdf)
File.write('invoice.pdf', decoded_pdf)

# Note: Direct file serving is typically handled by web frameworks in Ruby
# This script just saves the PDF locally
puts 'Invoice PDF has been saved as invoice.pdf'

import {orderApi} from '../api';
import {OrderInvoiceResponse} from 'ultracart_rest_api_v2_typescript';
import * as fs from 'fs/promises';

export class GenerateInvoice {
    /**
     * generateInvoice returns back a base64 encoded byte array of the given order's Invoice in PDF format.
     */
    public static async execute(): Promise<void> {
        const orderId = 'DEMO-0009104976';

        try {
            // Await the API call
            const apiResponse: OrderInvoiceResponse = await orderApi.generateInvoice({orderId});

            // the invoice will return as a base64 encoded
            // unpack, save off, email, whatever.
            const base64PdfOrUndefined = apiResponse.pdfBase64;
            if (base64PdfOrUndefined !== undefined) {
                const base64Pdf = base64PdfOrUndefined as string;
                // Decode base64 to buffer
                const decodedPdf = Buffer.from(base64Pdf, 'base64');

                // Write PDF to file
                await fs.writeFile('invoice.pdf', decodedPdf);

                // If this is running as a web application, you could return the PDF to the browser
                // using something like this (this is Express.js-specific code):
                /*
                app.get('/invoice', async (req, res) => {
                    res.contentType('application/pdf');
                    res.setHeader('Content-Disposition', 'inline; filename="invoice.pdf"');
                    res.setHeader('Cache-Control', 'public, must-revalidate, max-age=0');
                    res.setHeader('Pragma', 'public');
                    res.send(decodedPdf);
                });
                */

                console.log('Invoice PDF saved to invoice.pdf');
            }
        } catch (error) {
            console.error('Error generating invoice:', error);
        }
    }
}

// Optional: If you want to call the method
// GenerateInvoice.execute();

Generate a packing slip for this order across all distribution centers.

Permissions:
  • fulfillment_read

Produces: application/json
get
/order/orders/{order_id}/packing_slip

The packing slip PDF that is returned is base 64 encoded

SDK Function Name: generatePackingSlipAllDC

Parameters
Parameter Description Location Data Type Required
order_id Order ID path string required
Responses
Status Code Reason Response Model
200
Successful response OrderPackingSlipResponse
400
Bad Request 400
401
Unauthorized 401
410
Authorized Application Disabled 410
429
Too Many Requests 429
500
Server Side 500
using System;
using System.IO;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;

namespace SdkSample.order
{
    public class GeneratePackingSlipAllDC
    {
        public static void Execute()
        {
            /*
             * OrderApi.generatePackingSlipAllDC() is a method that might be used by a fulfillment center or distribution
             * center to generate a packing slip to include with a shipment.  This method will return a packing slip for
             * an order for all distribution centers involved.
             *
             */

            OrderApi orderApi = new OrderApi(Constants.ApiKey);

            string orderId = "DEMO-0009104390";

            OrderPackingSlipResponse apiResponse = orderApi.GeneratePackingSlipAllDC(orderId);

            if (apiResponse.Error != null)
            {
                Console.Error.WriteLine(apiResponse.Error.DeveloperMessage);
                Console.Error.WriteLine(apiResponse.Error.UserMessage);
                Environment.Exit(1);
            }

            // the packing slip will return as a base64 encoded
            // unpack, save off, email, whatever.
            string base64PackingSlip = apiResponse.PdfBase64;

            Console.WriteLine(base64PackingSlip);
            
            // Decode Base64 string into a byte array
            byte[] pdfBytes = Convert.FromBase64String(base64PackingSlip);

            // Save the byte array to a PDF file
            File.WriteAllBytes("packing_slip.pdf", pdfBytes);

            Console.WriteLine("PDF file saved successfully as 'packing_slip.pdf'");
        }
    }
}
package order;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;
import com.ultracart.admin.v2.OrderApi;
import com.ultracart.admin.v2.models.*;
import com.ultracart.admin.v2.util.ApiException;

public class GeneratePackingSlipAllDC {
   public void execute() throws IOException, ApiException {
       /*
        * OrderApi.generatePackingSlipAllDC() is a method that might be used by a fulfillment center or distribution
        * center to generate a packing slip to include with a shipment.  This method will return a packing slip for
        * an order for all distribution centers involved.
        *
        */

       OrderApi orderApi = new OrderApi(common.Constants.API_KEY);

       String orderId = "DEMO-0009104390";

       OrderPackingSlipResponse apiResponse = orderApi.generatePackingSlipAllDC(orderId);

       if (apiResponse.getError() != null) {
           System.err.println(apiResponse.getError().getDeveloperMessage());
           System.err.println(apiResponse.getError().getUserMessage());
           System.exit(1);
       }

       // the packing slip will return as a base64 encoded
       // unpack, save off, email, whatever.
       String base64PackingSlip = apiResponse.getPdfBase64();

       System.out.println(base64PackingSlip);

       // Decode Base64 string into a byte array
       byte[] pdfBytes = Base64.getDecoder().decode(base64PackingSlip);

       // Save the byte array to a PDF file
       try (FileOutputStream fos = new FileOutputStream("packing_slip.pdf")) {
           fos.write(pdfBytes);
       }

       System.out.println("PDF file saved successfully as 'packing_slip.pdf'");
   }
}
import { orderApi } from '../api.js';
import fs from 'fs/promises';
import { Buffer } from 'buffer';

export class GeneratePackingSlipAllDC {
    /**
     * OrderApi.generatePackingSlipAllDC() is a method that might be used by a fulfillment center or distribution
     * center to generate a packing slip to include with a shipment.  This method will return a packing slip for
     * an order for all distribution centers involved.
     */
    static async execute() {
        const orderId = 'DEMO-0009104390';

        try {
            // Generate packing slip for all distribution centers
            const apiResponse = await new Promise((resolve, reject) => {
                orderApi.generatePackingSlipAllDC(
                    orderId
                , function (error, data, response) {
                    if (error) {
                        reject(error);
                    } else {
                        resolve(data);
                    }
                });
            });

            // Check for errors
            if (apiResponse.error) {
                console.error('Developer Message:', apiResponse.error.developer_message);
                console.error('User Message:', apiResponse.error.user_message);
                throw new Error('Failed to generate packing slip');
            }

            // the packing slip will return as a base64 encoded
            // unpack, save off, email, whatever.
            const base64PackingSlipOrUndefined = apiResponse.pdfBase64;
            if (base64PackingSlipOrUndefined !== undefined) {
                const base64PackingSlip = base64PackingSlipOrUndefined;
                console.log(base64PackingSlip);

                // Decode Base64 string into a buffer
                const pdfBuffer = Buffer.from(base64PackingSlip, 'base64');

                // Save the buffer to a PDF file
                await fs.writeFile('packing_slip.pdf', pdfBuffer);

                console.log("PDF file saved successfully as 'packing_slip.pdf'");
            }
        } catch (error) {
            console.error('Error generating packing slip:', error);
            process.exit(1);
        }
    }
}

// Optional: If you want to call the method
// GeneratePackingSlipAllDC.execute();
<?php

ini_set('display_errors', 1);

/*
 * OrderApi.generatePackingSlipAllDC() is a method that might be used by a fulfillment center or distribution
 * center to generate a packing slip to include with a shipment.  This method will return a packing slip for
 * an order for all distribution centers involved.
 *
 */

use ultracart\v2\api\OrderApi;
use ultracart\v2\models\OrderFormat;

require_once '../vendor/autoload.php';
require_once '../constants.php';

$order_api = OrderApi::usingApiKey(Constants::API_KEY);

$order_id = 'DEMO-0009104390';


$api_response = $order_api->generatePackingSlipAllDC($order_id);

if ($api_response->getError() != null) {
    error_log($api_response->getError()->getDeveloperMessage());
    error_log($api_response->getError()->getUserMessage());
    exit();
}

// the packing slip will return as a base64 encoded
// unpack, save off, email, whatever.
$base64_packing_slip = $api_response->getPdfBase64();


echo '</head><body><pre>';
echo $base64_packing_slip;
echo '</pre></body></html>';

from ultracart.apis import OrderApi
from samples import api_client
import base64

# Create Order API instance
order_api = OrderApi(api_client())

# Define order ID
order_id = 'DEMO-0009104390'

# Generate packing slip for all distribution centers
api_response = order_api.generate_packing_slip_all_dc(order_id)

# Check for errors
if api_response.error:
    print(f"Developer Message: {api_response.error.developer_message}")
    print(f"User Message: {api_response.error.user_message}")
    exit()

# The packing slip is returned as a base64-encoded PDF
base64_packing_slip = api_response.pdf_base64

# Print the base64 packing slip
print(base64_packing_slip)

require 'ultracart_api'
require_relative '../constants'

# OrderApi.generatePackingSlipAllDC() is a method that might be used by a fulfillment center or distribution
# center to generate a packing slip to include with a shipment.  This method will return a packing slip for
# an order for all distribution centers involved.
order_api = UltracartClient::OrderApi.new_using_api_key(Constants::API_KEY)

order_id = 'DEMO-0009104390'

begin
  api_response = order_api.generate_packing_slip_all_dc(order_id)

  # Check for errors
  if api_response.error
    puts "Developer Message: #{api_response.error.developer_message}"
    puts "User Message: #{api_response.error.user_message}"
    exit
  end

  # The packing slip will return as a base64 encoded
  # unpack, save off, email, whatever.
  base64_packing_slip = api_response.pdf_base64

  puts base64_packing_slip
rescue StandardError => e
  puts "An error occurred: #{e.message}"
end
import {orderApi} from '../api';
import {OrderPackingSlipResponse} from 'ultracart_rest_api_v2_typescript';
import * as fs from 'fs/promises';

export class GeneratePackingSlipAllDC {
    /**
     * OrderApi.generatePackingSlipAllDC() is a method that might be used by a fulfillment center or distribution
     * center to generate a packing slip to include with a shipment.  This method will return a packing slip for
     * an order for all distribution centers involved.
     */
    public static async execute(): Promise<void> {
        const orderId = 'DEMO-0009104390';

        try {
            // Generate packing slip for all distribution centers
            const apiResponse: OrderPackingSlipResponse = await orderApi.generatePackingSlipAllDC({orderId});

            // Check for errors
            if (apiResponse.error) {
                console.error('Developer Message:', apiResponse.error.developer_message);
                console.error('User Message:', apiResponse.error.user_message);
                throw new Error('Failed to generate packing slip');
            }

            // the packing slip will return as a base64 encoded
            // unpack, save off, email, whatever.
            const base64PackingSlipOrUndefined = apiResponse.pdfBase64;
            if (base64PackingSlipOrUndefined !== undefined) {
                const base64PackingSlip = base64PackingSlipOrUndefined as string;
                console.log(base64PackingSlip);

                // Decode Base64 string into a buffer
                const pdfBuffer = Buffer.from(base64PackingSlip, 'base64');

                // Save the buffer to a PDF file
                await fs.writeFile('packing_slip.pdf', pdfBuffer);

                console.log("PDF file saved successfully as 'packing_slip.pdf'");
            }
        } catch (error) {
            console.error('Error generating packing slip:', error);
            process.exit(1);
        }
    }
}

// Optional: If you want to call the method
// GeneratePackingSlipAllDC.execute();

Generate a packing slip for this order for the given distribution center.

Permissions:
  • fulfillment_read

Produces: application/json
get
/order/orders/{order_id}/packing_slip/{distribution_center_code}

The packing slip PDF that is returned is base 64 encoded

SDK Function Name: generatePackingSlipSpecificDC

Parameters
Parameter Description Location Data Type Required
distribution_center_code Distribution center code path string required
order_id Order ID path string required
Responses
Status Code Reason Response Model
200
Successful response OrderPackingSlipResponse
400
Bad Request 400
401
Unauthorized 401
410
Authorized Application Disabled 410
429
Too Many Requests 429
500
Server Side 500
using System;
using System.IO;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;

namespace SdkSample.order
{
    public class GeneratePackingSlipSpecificDC
    {
        public static void Execute()
        {
            /*
             * OrderApi.generatePackingSlipSpecificDC() is a method that might be used by a fulfillment center or distribution
             * center to generate a packing slip to include with a shipment.  As such, this method allows for a packing slip
             * for a specific distribution center (DC) in the case that an order has multiple shipments from multiple DC.
             *
             * You must know the DC, which should not be a problem for any custom shipping application.
             * See: https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1377114/Distribution+Center
             */

            OrderApi orderApi = new OrderApi(Constants.ApiKey);

            string orderId = "DEMO-0009104390";
            string dc = "DFLT";

            OrderPackingSlipResponse apiResponse = orderApi.GeneratePackingSlipSpecificDC(dc, orderId);

            if (apiResponse.Error != null)
            {
                Console.Error.WriteLine(apiResponse.Error.DeveloperMessage);
                Console.Error.WriteLine(apiResponse.Error.UserMessage);
                Environment.Exit(1);
            }

            // the packing slip will return as a base64 encoded
            // unpack, save off, email, whatever.
            string base64PackingSlip = apiResponse.PdfBase64;


            Console.WriteLine(base64PackingSlip);
            
            // Decode Base64 string into a byte array
            byte[] pdfBytes = Convert.FromBase64String(base64PackingSlip);

            // Save the byte array to a PDF file
            File.WriteAllBytes("packing_slip.pdf", pdfBytes);

            Console.WriteLine("PDF file saved successfully as 'packing_slip.pdf'");
            

        }
    }
}
package order;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;
import com.ultracart.admin.v2.OrderApi;
import com.ultracart.admin.v2.models.*;
import com.ultracart.admin.v2.util.ApiException;

public class GeneratePackingSlipSpecificDC {
   public void execute() throws IOException, ApiException {
       /*
        * OrderApi.generatePackingSlipSpecificDC() is a method that might be used by a fulfillment center or distribution
        * center to generate a packing slip to include with a shipment.  As such, this method allows for a packing slip
        * for a specific distribution center (DC) in the case that an order has multiple shipments from multiple DC.
        *
        * You must know the DC, which should not be a problem for any custom shipping application.
        * See: https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1377114/Distribution+Center
        */

       OrderApi orderApi = new OrderApi(common.Constants.API_KEY);

       String orderId = "DEMO-0009104390";
       String dc = "DFLT";

       OrderPackingSlipResponse apiResponse = orderApi.generatePackingSlipSpecificDC(dc, orderId);

       if (apiResponse.getError() != null) {
           System.err.println(apiResponse.getError().getDeveloperMessage());
           System.err.println(apiResponse.getError().getUserMessage());
           System.exit(1);
       }

       // the packing slip will return as a base64 encoded
       // unpack, save off, email, whatever.
       String base64PackingSlip = apiResponse.getPdfBase64();

       System.out.println(base64PackingSlip);

       // Decode Base64 string into a byte array
       byte[] pdfBytes = Base64.getDecoder().decode(base64PackingSlip);

       // Save the byte array to a PDF file
       try (FileOutputStream fos = new FileOutputStream("packing_slip.pdf")) {
           fos.write(pdfBytes);
       }

       System.out.println("PDF file saved successfully as 'packing_slip.pdf'");
   }
}
import { orderApi } from '../api.js';
import fs from 'fs/promises';
import { Buffer } from 'buffer';

export class GeneratePackingSlipSpecificDC {
    /**
     * OrderApi.generatePackingSlipSpecificDC() is a method that might be used by a fulfillment center or distribution
     * center to generate a packing slip to include with a shipment.  As such, this method allows for a packing slip
     * for a specific distribution center (DC) in the case that an order has multiple shipments from multiple DC.
     *
     * You must know the DC, which should not be a problem for any custom shipping application.
     * See: https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1377114/Distribution+Center
     */
    static async execute() {
        const orderId = 'DEMO-0009104390';
        const dc = 'DFLT';

        try {
            // Generate packing slip for a specific distribution center
            const apiResponse = await new Promise((resolve, reject) => {
                orderApi.generatePackingSlipSpecificDC(dc,
                    orderId
                , function (error, data, response) {
                    if (error) {
                        reject(error);
                    } else {
                        resolve(data);
                    }
                });
            });

            // Check for errors
            if (apiResponse.error) {
                console.error('Developer Message:', apiResponse.error.developer_message);
                console.error('User Message:', apiResponse.error.user_message);
                throw new Error('Failed to generate packing slip');
            }

            // the packing slip will return as a base64 encoded
            // unpack, save off, email, whatever.
            const base64PackingSlipOrUndefined = apiResponse.pdfBase64;

            if (base64PackingSlipOrUndefined !== undefined) {
                const base64PackingSlip = base64PackingSlipOrUndefined;

                console.log(base64PackingSlip);

                // Decode Base64 string into a buffer
                const pdfBuffer = Buffer.from(base64PackingSlip, 'base64');

                // Save the buffer to a PDF file
                await fs.writeFile('packing_slip.pdf', pdfBuffer);

                console.log("PDF file saved successfully as 'packing_slip.pdf'");
            }
        } catch (error) {
            console.error('Error generating packing slip:', error);
            process.exit(1);
        }
    }
}

// Optional: If you want to call the method
// GeneratePackingSlipSpecificDC.execute();
<?php

ini_set('display_errors', 1);

/*
 * OrderApi.generatePackingSlipSpecificDC() is a method that might be used by a fulfillment center or distribution
 * center to generate a packing slip to include with a shipment.  As such, this method allows for a packing slip
 * for a specific distribution center (DC) in the case that an order has multiple shipments from multiple DC.
 *
 * You must know the DC, which should not be a problem for any custom shipping application.
 * See: https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1377114/Distribution+Center
 */

use ultracart\v2\api\OrderApi;
use ultracart\v2\models\OrderFormat;

require_once '../vendor/autoload.php';
require_once '../constants.php';

$order_api = OrderApi::usingApiKey(Constants::API_KEY);

$order_id = 'DEMO-0009104390';
$dc = 'DFLT';


$api_response = $order_api->generatePackingSlipSpecificDC($dc, $order_id);

if ($api_response->getError() != null) {
    error_log($api_response->getError()->getDeveloperMessage());
    error_log($api_response->getError()->getUserMessage());
    exit();
}

// the packing slip will return as a base64 encoded
// unpack, save off, email, whatever.
$base64_packing_slip = $api_response->getPdfBase64();


echo '</head><body><pre>';
echo $base64_packing_slip;
echo '</pre></body></html>';

from ultracart.apis import OrderApi
from samples import api_client
import base64

# Create Order API instance
order_api = OrderApi(api_client())

# Define order ID and distribution center (DC)
order_id = 'DEMO-0009104390'
dc = 'DFLT'

# Generate packing slip for a specific distribution center
api_response = order_api.generate_packing_slip_specific_dc(dc, order_id)

# Check for errors
if api_response.error:
    print(f"Developer Message: {api_response.error.developer_message}")
    print(f"User Message: {api_response.error.user_message}")
    exit()

# The packing slip is returned as a base64-encoded PDF
base64_packing_slip = api_response.pdf_base64

# Print the base64 packing slip
print(base64_packing_slip)

require 'ultracart_api'
require_relative '../constants'

# OrderApi.generatePackingSlipSpecificDC() is a method that might be used by a fulfillment center or distribution
# center to generate a packing slip to include with a shipment.  As such, this method allows for a packing slip
# for a specific distribution center (DC) in the case that an order has multiple shipments from multiple DC.
#
# You must know the DC, which should not be a problem for any custom shipping application.
# See: https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1377114/Distribution+Center
order_api = UltracartClient::OrderApi.new_using_api_key(Constants::API_KEY)

order_id = 'DEMO-0009104390'
dc = 'DFLT'

begin
  api_response = order_api.generate_packing_slip_specific_dc(dc, order_id)

  # Check for errors
  if api_response.error
    puts "Developer Message: #{api_response.error.developer_message}"
    puts "User Message: #{api_response.error.user_message}"
    exit
  end

  # The packing slip will return as a base64 encoded
  # unpack, save off, email, whatever.
  base64_packing_slip = api_response.pdf_base64

  puts base64_packing_slip
rescue StandardError => e
  puts "An error occurred: #{e.message}"
end
import {orderApi} from '../api';
import {OrderPackingSlipResponse} from 'ultracart_rest_api_v2_typescript';
import * as fs from 'fs/promises';

export class GeneratePackingSlipSpecificDC {
    /**
     * OrderApi.generatePackingSlipSpecificDC() is a method that might be used by a fulfillment center or distribution
     * center to generate a packing slip to include with a shipment.  As such, this method allows for a packing slip
     * for a specific distribution center (DC) in the case that an order has multiple shipments from multiple DC.
     *
     * You must know the DC, which should not be a problem for any custom shipping application.
     * See: https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1377114/Distribution+Center
     */
    public static async execute(): Promise<void> {
        const orderId = 'DEMO-0009104390';
        const dc = 'DFLT';

        try {
            // Generate packing slip for a specific distribution center
            const apiResponse: OrderPackingSlipResponse = await orderApi.generatePackingSlipSpecificDC({distributionCenterCode: dc, orderId});

            // Check for errors
            if (apiResponse.error) {
                console.error('Developer Message:', apiResponse.error.developer_message);
                console.error('User Message:', apiResponse.error.user_message);
                throw new Error('Failed to generate packing slip');
            }

            // the packing slip will return as a base64 encoded
            // unpack, save off, email, whatever.
            const base64PackingSlipOrUndefined = apiResponse.pdfBase64;

            if (base64PackingSlipOrUndefined !== undefined) {
                const base64PackingSlip = base64PackingSlipOrUndefined as string;


                console.log(base64PackingSlip);

                // Decode Base64 string into a buffer
                const pdfBuffer = Buffer.from(base64PackingSlip, 'base64');

                // Save the buffer to a PDF file
                await fs.writeFile('packing_slip.pdf', pdfBuffer);

                console.log("PDF file saved successfully as 'packing_slip.pdf'");
            }
        } catch (error) {
            console.error('Error generating packing slip:', error);
            process.exit(1);
        }
    }
}

// Optional: If you want to call the method
// GeneratePackingSlipSpecificDC.execute();

Process payment

Permissions:
  • order_write

Produces: application/json
post
/order/orders/{order_id}/process_payment

Process payment on order

SDK Function Name: processPayment

Parameters
Parameter Description Location Data Type Required
order_id The order id to process payment on path string required
process_payment_request Process payment parameters body OrderProcessPaymentRequest required
Responses
Status Code Reason Response Model
200
Successful response OrderProcessPaymentResponse
400
Bad Request 400
401
Unauthorized 401
410
Authorized Application Disabled 410
429
Too Many Requests 429
500
Server Side 500
using System;
using System.Collections.Generic;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;
using Newtonsoft.Json;

namespace SdkSample.order
{
    public class ProcessPayment
    {
        /*
         * OrderApi.processPayment() was designed to charge a customer for an order. It was created to work in tandem with
         * duplicateOrder(), which does not accomplish payment on its own. The use-case for this method is to
         * duplicate a customer's order and then charge them for it. duplicateOrder() does not charge the customer again,
         * which is why processPayment() exists.
         *
         * These are the steps for cloning an existing order and charging the customer for it.
         * 1. duplicateOrder
         * 2. updateOrder (if you wish to change any part of it)
         * 3. processPayment to charge the customer.
         *
         * As a reminder, if you wish to create a new order from scratch, use the CheckoutApi or ChannelPartnerApi.
         * The OrderApi is for managing existing orders.
         */
        public static void Execute()
        {
            OrderApi orderApi = new OrderApi(Constants.ApiKey);

            string expansion = "items";   // for this example, we're going to change the items after we duplicate the order, so
                                          // the only expansion properties we need are the items.
                                          // See: https://www.ultracart.com/api/  for a list of all expansions.

            // Step 1. Duplicate the order
            string orderIdToDuplicate = "DEMO-0009104436";
            OrderResponse apiResponse = orderApi.DuplicateOrder(orderIdToDuplicate, expansion);
            Order newOrder = apiResponse.Order;

            // Step 2. Update the items. I will create a new items list and assign it to the order to remove the old ones completely.
            List<OrderItem> items = new List<OrderItem>();
            OrderItem item = new OrderItem();
            item.MerchantItemId = "simple_teapot";
            item.Quantity = 1;
            item.Description = "A lovely teapot";
            item.DistributionCenterCode = "DFLT"; // where is this item shipping out of?

            Currency cost = new Currency();
            cost.CurrencyCode = "USD";
            cost.Value = 9.99m;
            item.Cost = cost;

            Weight weight = new Weight();
            weight.Uom = Weight.UomEnum.OZ;
            weight.Value = 6;
            item.Weight = weight;

            items.Add(item);
            newOrder.Items = items;
            OrderResponse updateResponse = orderApi.UpdateOrder(newOrder.OrderId, newOrder, expansion);

            Order updatedOrder = updateResponse.Order;

            // Step 3. process the payment.
            // the request object below takes two optional arguments.
            // The first is an amount if you wish to bill for an amount different from the order.
            // We do not bill differently in this example.
            // The second is card_verification_number_token, which is a token you can create by using our hosted fields to
            // upload a CVV value. This will create a token you may use here. However, most merchants using the duplicate
            // order method will be setting up an auto order for a customer. Those will not make use of the CVV, so we're
            // not including it here. That is why the request object below is does not have any values set.
            // For more info on hosted fields:
            // See: https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1377775/UltraCart+Hosted+Credit+Card+Fields
            // See: https://github.com/UltraCart/sdk_samples/blob/master/hosted_fields/hosted_fields.html

            OrderProcessPaymentRequest processPaymentRequest = new OrderProcessPaymentRequest();
            OrderProcessPaymentResponse paymentResponse = orderApi.ProcessPayment(newOrder.OrderId, processPaymentRequest);
            OrderPaymentTransaction transactionDetails = paymentResponse.PaymentTransaction; // do whatever you wish with this.

            Console.WriteLine("New Order (after updated items):");
            DisplayOrderInfo(updatedOrder);
            Console.WriteLine("\nPayment Response:");
            DisplayPaymentResponse(paymentResponse);
        }

        private static void DisplayOrderInfo(Order order)
        {
            Console.WriteLine($"Order ID: {order.OrderId}");
            Console.WriteLine($"Total: {order.Summary?.Total?.Value} {order.Summary?.Total?.CurrencyCode}");
            Console.WriteLine("Items:");
            foreach (OrderItem item in order.Items)
            {
                Console.WriteLine($"  - {item.Quantity}x {item.Description} ({item.MerchantItemId})");
                Console.WriteLine($"    Cost: {item.Cost.Value} {item.Cost.CurrencyCode}");
            }
        }

        private static void DisplayPaymentResponse(OrderProcessPaymentResponse response)
        {
            Console.WriteLine($"Successfully Processed: {response.Success}");
            if (response.PaymentTransaction != null)
            {
                Console.WriteLine($"Transaction ID: {response.PaymentTransaction.TransactionId}");
                Console.WriteLine($"Transaction Timestamp: {response.PaymentTransaction.TransactionTimestamp}");
            }
            
            // here's the entire object:
            Console.WriteLine(JsonConvert.SerializeObject(response, new JsonSerializerSettings { Formatting = Formatting.Indented}));
            
            if (response.Error != null)
            {
                Console.WriteLine($"Error: {response.Error.UserMessage}");
            }
        }
    }
}
package order;

import com.ultracart.admin.v2.OrderApi;
import com.ultracart.admin.v2.models.*;
import com.ultracart.admin.v2.util.ApiException;
import common.Constants;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class ProcessPayment {
    /*
     * OrderApi.processPayment() was designed to charge a customer for an order. It was created to work in tandem with
     * duplicateOrder(), which does not accomplish payment on its own. The use-case for this method is to
     * duplicate a customer's order and then charge them for it. duplicateOrder() does not charge the customer again,
     * which is why processPayment() exists.
     *
     * These are the steps for cloning an existing order and charging the customer for it.
     * 1. duplicateOrder
     * 2. updateOrder (if you wish to change any part of it)
     * 3. processPayment to charge the customer.
     *
     * As a reminder, if you wish to create a new order from scratch, use the CheckoutApi or ChannelPartnerApi.
     * The OrderApi is for managing existing orders.
     */
    public static void execute() throws ApiException {
        OrderApi orderApi = new OrderApi(Constants.API_KEY);

        String expansion = "items";   // for this example, we're going to change the items after we duplicate the order, so
                                     // the only expansion properties we need are the items.
                                     // See: https://www.ultracart.com/api/  for a list of all expansions.

        // Step 1. Duplicate the order
        String orderIdToDuplicate = "DEMO-0009104436";
        OrderResponse apiResponse = orderApi.duplicateOrder(orderIdToDuplicate, expansion);
        Order newOrder = apiResponse.getOrder();

        // Step 2. Update the items. I will create a new items list and assign it to the order to remove the old ones completely.
        List<OrderItem> items = new ArrayList<>();
        OrderItem item = new OrderItem();
        item.setMerchantItemId("simple_teapot");
        item.setQuantity(BigDecimal.valueOf(1.0));
        item.setDescription("A lovely teapot");
        item.setDistributionCenterCode("DFLT"); // where is this item shipping out of?

        Currency cost = new Currency();
        cost.setCurrencyCode("USD");
        cost.setValue(BigDecimal.valueOf(9.99));
        item.setCost(cost);

        Weight weight = new Weight();
        weight.setUom(Weight.UomEnum.OZ);
        weight.setValue(BigDecimal.valueOf(6.0));
        item.setWeight(weight);

        items.add(item);
        newOrder.setItems(items);
        OrderResponse updateResponse = orderApi.updateOrder(newOrder.getOrderId(), newOrder, expansion);

        Order updatedOrder = updateResponse.getOrder();

        // Step 3. process the payment.
        // the request object below takes two optional arguments.
        // The first is an amount if you wish to bill for an amount different from the order.
        // We do not bill differently in this example.
        // The second is card_verification_number_token, which is a token you can create by using our hosted fields to
        // upload a CVV value. This will create a token you may use here. However, most merchants using the duplicate
        // order method will be setting up an auto order for a customer. Those will not make use of the CVV, so we're
        // not including it here. That is why the request object below is does not have any values set.
        // For more info on hosted fields:
        // See: https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1377775/UltraCart+Hosted+Credit+Card+Fields
        // See: https://github.com/UltraCart/sdk_samples/blob/master/hosted_fields/hosted_fields.html

        OrderProcessPaymentRequest processPaymentRequest = new OrderProcessPaymentRequest();
        OrderProcessPaymentResponse paymentResponse = orderApi.processPayment(newOrder.getOrderId(), processPaymentRequest);
        OrderPaymentTransaction transactionDetails = paymentResponse.getPaymentTransaction(); // do whatever you wish with this.

        System.out.println("New Order (after updated items):");
        displayOrderInfo(updatedOrder);
        System.out.println("\nPayment Response:");
        displayPaymentResponse(paymentResponse);
    }

    private static void displayOrderInfo(Order order) {
        System.out.println("Order ID: " + order.getOrderId());
        System.out.println("Total: " + order.getSummary().getTotal().getValue() + " " + 
                          order.getSummary().getTotal().getCurrencyCode());
        System.out.println("Items:");
        for (OrderItem item : order.getItems()) {
            System.out.println("  - " + item.getQuantity() + "x " + item.getDescription() + 
                             " (" + item.getMerchantItemId() + ")");
            System.out.println("    Cost: " + item.getCost().getValue() + " " + 
                             item.getCost().getCurrencyCode());
        }
    }

    private static void displayPaymentResponse(OrderProcessPaymentResponse response) {
        System.out.println("Successfully Processed: " + response.getSuccess());
        if (response.getPaymentTransaction() != null) {
            System.out.println("Transaction ID: " + response.getPaymentTransaction().getTransactionId());
            System.out.println("Transaction Timestamp: " + response.getPaymentTransaction().getTransactionTimestamp());
        }

        // here's the entire object:
        System.out.println(response.toString());

        if (response.getError() != null) {
            System.out.println("Error: " + response.getError().getUserMessage());
        }
    }
}
import {orderApi} from '../api.js';

class ProcessPayment {
    /*
     * OrderApi.processPayment() was designed to charge a customer for an order. It was created to work in tandem with
     * duplicateOrder(), which does not accomplish payment on its own. The use-case for this method is to
     * duplicate a customer's order and then charge them for it. duplicateOrder() does not charge the customer again,
     * which is why processPayment() exists.
     *
     * These are the steps for cloning an existing order and charging the customer for it.
     * 1. duplicateOrder
     * 2. updateOrder (if you wish to change any part of it)
     * 3. processPayment to charge the customer.
     *
     * As a reminder, if you wish to create a new order from scratch, use the CheckoutApi or ChannelPartnerApi.
     * The OrderApi is for managing existing orders.
     */
    static async execute() {
        const expansion = "items";   // for this example, we're going to change the items after we duplicate the order, so
                                     // the only expansion properties we need are the items.
                                     // See: https://www.ultracart.com/api/  for a list of all expansions.

        // Step 1. Duplicate the order
        const orderIdToDuplicate = "DEMO-0009104436";
        const apiResponse = await new Promise((resolve, reject) => {
            orderApi.duplicateOrder(
                orderIdToDuplicate, {
                    _expand: expansion
                }, function (error, data, response) {
                    if (error) {
                        reject(error);
                    } else {
                        resolve(data);
                    }
                });
        });
        const newOrder = apiResponse.order;

        if (!newOrder) {
            throw new Error("Order duplication failed");
        }

        // Step 2. Update the items. I will create a new items list and assign it to the order to remove the old ones completely.
        const items = [];
        const item = {
            merchant_item_id: "simple_teapot",
            quantity: 1,
            description: "A lovely teapot",
            distribution_center_code: "DFLT", // where is this item shipping out of?

            cost: {
                currency_code: "USD",
                value: 9.99
            },

            weight: {
                uom: "OZ",
                value: 6
            }
        };

        items.push(item);
        newOrder.items = items;
        const updateResponse = await new Promise((resolve, reject) => {
            orderApi.updateOrder(
                newOrder.order_id,
                newOrder,
                {
                    _expand: expansion
                }, function (error, data, response) {
                    if (error) {
                        reject(error);
                    } else {
                        resolve(data);
                    }
                });
        });

        const updatedOrder = updateResponse.order;

        // Step 3. process the payment.
        // the request object below takes two optional arguments.
        // The first is an amount if you wish to bill for an amount different from the order.
        // We do not bill differently in this example.
        // The second is card_verification_number_token, which is a token you can create by using our hosted fields to
        // upload a CVV value. This will create a token you may use here. However, most merchants using the duplicate
        // order method will be setting up an auto order for a customer. Those will not make use of the CVV, so we're
        // not including it here. That is why the request object below is does not have any values set.
        // For more info on hosted fields:
        // See: https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1377775/UltraCart+Hosted+Credit+Card+Fields
        // See: https://github.com/UltraCart/sdk_samples/blob/master/hosted_fields/hosted_fields.html

        const processPaymentRequest = {};
        const paymentResponse = await new Promise((resolve, reject) => {
            orderApi.processPayment(
                newOrder.order_id,
                processPaymentRequest
                , function (error, data, response) {
                    if (error) {
                        reject(error);
                    } else {
                        resolve(data);
                    }
                });
        });
        const transactionDetails = paymentResponse.payment_transaction; // do whatever you wish with this.

        console.log("New Order (after updated items):");
        this.displayOrderInfo(updatedOrder);
        console.log("\nPayment Response:");
        this.displayPaymentResponse(paymentResponse);
    }

    static displayOrderInfo(order) {
        if (!order) {
            console.log("No order information available");
            return;
        }

        console.log(`Order ID: ${order.order_id}`);
        console.log(`Total: ${order.summary?.total?.value} ${order.summary?.total?.currency_code}`);
        console.log("Items:");

        order.items?.forEach(item => {
            console.log(`  - ${item.quantity}x ${item.description} (${item.merchant_item_id})`);
            console.log(`    Cost: ${item.cost?.value} ${item.cost?.currency_code}`);
        });
    }

    static displayPaymentResponse(response) {
        console.log(`Successfully Processed: ${response.success}`);

        if (response.payment_transaction) {
            console.log(`Transaction ID: ${response.payment_transaction.transaction_id}`);
            console.log(`Transaction Timestamp: ${response.payment_transaction.transaction_timestamp}`);
        }

        // here's the entire object:
        console.log(JSON.stringify(response, null, 2));

        if (response.error) {
            console.log(`Error: ${response.error.user_message}`);
        }
    }
}

export default ProcessPayment;
<?php /** @noinspection DuplicatedCode */

require_once '../vendor/autoload.php';
require_once '../constants.php';

/*
 * OrderApi.processPayment() was designed to charge a customer for an order.  It was created to work in tandem with
 * duplicateOrder(), which does not accomplish payment on its own.  The use-case for this method is to
 * duplicate a customer's order and then charge them for it.  duplicateOrder() does not charge the customer again,
 * which is why processPayment() exists.
 *
 * These are the steps for cloning an existing order and charging the customer for it.
 * 1. duplicateOrder
 * 2. updateOrder (if you wish to change any part of it)
 * 3. processPayment to charge the customer.
 *
 * As a reminder, if you wish to create a new order from scratch, use the CheckoutApi or ChannelPartnerApi.
 * The OrderApi is for managing existing orders.
 */

use ultracart\v2\api\OrderApi;
use ultracart\v2\models\OrderItem;
use ultracart\v2\models\Currency;
use ultracart\v2\models\Weight;
use ultracart\v2\models\OrderProcessPaymentRequest;

$order_api = OrderApi::usingApiKey(Constants::API_KEY);

$expansion = "items";   // for this example, we're going to change the items after we duplicate the order, so
// the only expansion properties we need are the items.
// See: https://www.ultracart.com/api/  for a list of all expansions.

// Step 1. Duplicate the order
$order_id_to_duplicate = 'DEMO-0009104436';
$api_response = $order_api->duplicateOrder($order_id_to_duplicate, $expansion);
$new_order = $api_response->getOrder();

// Step 2. Update the items.  I will create a new items array and assign it to the order to remove the old ones completely.
$items = array();
$item = new OrderItem();
$item->setMerchantItemId('simple_teapot');
$item->setQuantity(1);
$item->setDescription("A lovely teapot");
$item->setDistributionCenterCode('DFLT'); // where is this item shipping out of?

$cost = new Currency();
$cost->setCurrencyCode('USD');
$cost->setValue(9.99);
$item->setCost($cost);

$weight = new Weight();
$weight->setUom("OZ");
$weight->setValue(6);
$item->setWeight($weight);

$items[] = $item;
$new_order->setItems($items);
$update_response = $order_api->updateOrder($new_order->getOrderId(), $new_order, $expansion);

$updated_order = $update_response->getOrder();

// Step 3. process the payment.
// the request object below takes two optional arguments.
// The first is an amount if you wish to bill for an amount different from the order.
// We do not bill differently in this example.
// The second is card_verification_number_token, which is a token you can create by using our hosted fields to
// upload a CVV value.  This will create a token you may use here.  However, most merchants using the duplicate
// order method will be setting up an auto order for a customer.  Those will not make use of the CVV, so we're
// not including it here.  That is why the request object below is does not have any values set.
// For more info on hosted fields:
// See: https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1377775/UltraCart+Hosted+Credit+Card+Fields
// See: https://github.com/UltraCart/sdk_samples/blob/master/hosted_fields/hosted_fields.html

$process_payment_request = new OrderProcessPaymentRequest();
$payment_response = $order_api->processPayment($new_order->getOrderId(), $process_payment_request);
$transaction_details = $payment_response->getPaymentTransaction(); // do whatever you wish with this.

echo '<html lang="en"><body><pre>';
echo 'New Order (after updated items):<br>';
var_dump($updated_order);
echo '<br>Payment Response:<br>';
var_dump($payment_response);
echo '</pre></body></html>';
import logging
from ultracart import ApiException
from ultracart.apis import OrderApi
from ultracart.models import OrderItem, Currency, Weight, OrderProcessPaymentRequest
from samples import api_client

# Enable error logging
logging.basicConfig(level=logging.DEBUG)

# OrderApi.processPayment() was designed to charge a customer for an order. It was created to work in tandem with
# duplicateOrder(), which does not accomplish payment on its own. The use-case for this method is to
# duplicate a customer's order and then charge them for it. duplicateOrder() does not charge the customer again,
# which is why processPayment() exists.
#
# These are the steps for cloning an existing order and charging the customer for it.
# 1. duplicateOrder
# 2. updateOrder (if you wish to change any part of it)
# 3. processPayment to charge the customer.
#
# As a reminder, if you wish to create a new order from scratch, use the CheckoutApi or ChannelPartnerApi.
# The OrderApi is for managing existing orders.

# Using the API key to initialize the order API
order_api = OrderApi(api_client())

expand = "items"   # For this example, we're going to change the items after we duplicate the order, so
# the only expansion properties we need are the items.
# See: https://www.ultracart.com/api/ for a list of all expansions.

# Step 1. Duplicate the order
order_id_to_duplicate = 'DEMO-0009104436'
try:
    api_response = order_api.duplicate_order(order_id_to_duplicate, expand=expand)
except ApiException as e:
    logging.error(f"Exception when calling OrderApi->duplicate_order: {e}")
    exit()

new_order = api_response.order

# Step 2. Update the items. I will create a new items array and assign it to the order to remove the old ones completely.
items = []
item = OrderItem()
item.merchant_item_id = 'simple_teapot'
item.quantity = 1
item.description = "A lovely teapot"
item.distribution_center_code = 'DFLT'  # Where is this item shipping out of?

cost = Currency()
cost.currency_code = 'USD'
cost.value = 9.99
item.cost = cost

weight = Weight()
weight.uom = "OZ"
weight.value = 6
item.weight = weight

items.append(item)
new_order.items = items

try:
    update_response = order_api.update_order(new_order.order_id, new_order, expand=expand)
except ApiException as e:
    logging.error(f"Exception when calling OrderApi->update_order: {e}")
    exit()

updated_order = update_response.order

# Step 3. Process the payment.
# The request object below takes two optional arguments.
# The first is an amount if you wish to bill for an amount different from the order.
# We do not bill differently in this example.
# The second is card_verification_number_token, which is a token you can create by using our hosted fields to
# upload a CVV value. This will create a token you may use here. However, most merchants using the duplicate
# order method will be setting up an auto order for a customer. Those will not make use of the CVV, so we're
# not including it here. That is why the request object below is does not have any values set.

process_payment_request = OrderProcessPaymentRequest()
try:
    payment_response = order_api.process_payment(new_order.order_id, process_payment_request)
except ApiException as e:
    logging.error(f"Exception when calling OrderApi->process_payment: {e}")
    exit()

transaction_details = payment_response.payment_transaction  # Do whatever you wish with this.

# This could get verbose...
import pprint
print("New Order (after updated items):")
pprint.pprint(updated_order)
print("\nPayment Response:")
pprint.pprint(payment_response)

require 'ultracart_api'
require_relative '../constants'
require_relative '../item_functions'

# OrderApi.process_payment() was designed to charge a customer for an order. It was created to work in tandem with
# duplicate_order(), which does not accomplish payment on its own. The use-case for this method is to
# duplicate a customer's order and then charge them for it. duplicate_order() does not charge the customer again,
# which is why process_payment() exists.
#
# These are the steps for cloning an existing order and charging the customer for it.
# 1. duplicate_order
# 2. update_order (if you wish to change any part of it)
# 3. process_payment to charge the customer.
#
# As a reminder, if you wish to create a new order from scratch, use the CheckoutApi or ChannelPartnerApi.
# The OrderApi is for managing existing orders.

order_api = UltracartClient::OrderApi.new_using_api_key(Constants::API_KEY)

expansion = "items"   # for this example, we're going to change the items after we duplicate the order, so
# the only expansion properties we need are the items.
# See: https://www.ultracart.com/api/  for a list of all expansions.

# Step 1. Duplicate the order
order_id_to_duplicate = 'DEMO-0009104436'
api_response = order_api.duplicate_order(order_id_to_duplicate, opts = { _expand: expansion })
new_order = api_response.order

# Step 2. Update the items. I will create a new items array and assign it to the order to remove the old ones completely.
items = []
item = UltracartClient::OrderItem.new
item.merchant_item_id = 'simple_teapot'
item.quantity = 1
item.description = "A lovely teapot"
item.distribution_center_code = 'DFLT' # where is this item shipping out of?

cost = UltracartClient::Currency.new
cost.currency_code = 'USD'
cost.value = 9.99
item.cost = cost

weight = UltracartClient::Weight.new
weight.uom = "OZ"
weight.value = 6
item.weight = weight

items << item
new_order.items = items
update_response = order_api.update_order(new_order.order_id, new_order, opts = { _expand: expansion })

updated_order = update_response.order

# Step 3. process the payment.
# the request object below takes two optional arguments.
# The first is an amount if you wish to bill for an amount different from the order.
# We do not bill differently in this example.
# The second is card_verification_number_token, which is a token you can create by using our hosted fields to
# upload a CVV value. This will create a token you may use here. However, most merchants using the duplicate
# order method will be setting up an auto order for a customer. Those will not make use of the CVV, so we're
# not including it here. That is why the request object below is does not have any values set.
# For more info on hosted fields:
# See: https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1377775/UltraCart+Hosted+Credit+Card+Fields
# See: https://github.com/UltraCart/sdk_samples/blob/master/hosted_fields/hosted_fields.html

process_payment_request = UltracartClient::OrderProcessPaymentRequest.new
payment_response = order_api.process_payment(new_order.order_id, process_payment_request)
transaction_details = payment_response.payment_transaction # do whatever you wish with this.

puts 'New Order (after updated items):'
p updated_order
puts 'Payment Response:'
p payment_response
import {
    Order,
    OrderItem,
    OrderProcessPaymentRequest,
    OrderProcessPaymentResponse
} from 'ultracart_rest_api_v2_typescript';
import { orderApi } from '../api';

class ProcessPayment {
    /*
     * OrderApi.processPayment() was designed to charge a customer for an order. It was created to work in tandem with
     * duplicateOrder(), which does not accomplish payment on its own. The use-case for this method is to
     * duplicate a customer's order and then charge them for it. duplicateOrder() does not charge the customer again,
     * which is why processPayment() exists.
     *
     * These are the steps for cloning an existing order and charging the customer for it.
     * 1. duplicateOrder
     * 2. updateOrder (if you wish to change any part of it)
     * 3. processPayment to charge the customer.
     *
     * As a reminder, if you wish to create a new order from scratch, use the CheckoutApi or ChannelPartnerApi.
     * The OrderApi is for managing existing orders.
     */
    static async execute(): Promise<void> {
        const expansion = "items";   // for this example, we're going to change the items after we duplicate the order, so
                                     // the only expansion properties we need are the items.
                                     // See: https://www.ultracart.com/api/  for a list of all expansions.

        // Step 1. Duplicate the order
        const orderIdToDuplicate = "DEMO-0009104436";
        const apiResponse = await orderApi.duplicateOrder({orderId: orderIdToDuplicate, expand: expansion});
        const newOrder = apiResponse.order;

        if (!newOrder) {
            throw new Error("Order duplication failed");
        }

        // Step 2. Update the items. I will create a new items list and assign it to the order to remove the old ones completely.
        const items: OrderItem[] = [];
        const item: OrderItem = {
            merchant_item_id: "simple_teapot",
            quantity: 1,
            description: "A lovely teapot",
            distribution_center_code: "DFLT", // where is this item shipping out of?

            cost: {
                currency_code: "USD",
                value: 9.99
            },

            weight: {
                uom: "OZ",
                value: 6
            }
        };

        items.push(item);
        newOrder.items = items;
        const updateResponse = await orderApi.updateOrder({orderId: newOrder.order_id!, order: newOrder, expand: expansion});

        const updatedOrder = updateResponse.order;

        // Step 3. process the payment.
        // the request object below takes two optional arguments.
        // The first is an amount if you wish to bill for an amount different from the order.
        // We do not bill differently in this example.
        // The second is card_verification_number_token, which is a token you can create by using our hosted fields to
        // upload a CVV value. This will create a token you may use here. However, most merchants using the duplicate
        // order method will be setting up an auto order for a customer. Those will not make use of the CVV, so we're
        // not including it here. That is why the request object below is does not have any values set.
        // For more info on hosted fields:
        // See: https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1377775/UltraCart+Hosted+Credit+Card+Fields
        // See: https://github.com/UltraCart/sdk_samples/blob/master/hosted_fields/hosted_fields.html

        const processPaymentRequest: OrderProcessPaymentRequest = {};
        const paymentResponse = await orderApi.processPayment({orderId: newOrder.order_id!, processPaymentRequest});
        const transactionDetails = paymentResponse.payment_transaction; // do whatever you wish with this.

        console.log("New Order (after updated items):");
        this.displayOrderInfo(updatedOrder);
        console.log("\nPayment Response:");
        this.displayPaymentResponse(paymentResponse);
    }

    private static displayOrderInfo(order?: Order): void {
        if (!order) {
            console.log("No order information available");
            return;
        }

        console.log(`Order ID: ${order.order_id}`);
        console.log(`Total: ${order.summary?.total?.value} ${order.summary?.total?.currency_code}`);
        console.log("Items:");

        order.items?.forEach(item => {
            console.log(`  - ${item.quantity}x ${item.description} (${item.merchant_item_id})`);
            console.log(`    Cost: ${item.cost?.value} ${item.cost?.currency_code}`);
        });
    }

    private static displayPaymentResponse(response: OrderProcessPaymentResponse): void {
        console.log(`Successfully Processed: ${response.success}`);

        if (response.payment_transaction) {
            console.log(`Transaction ID: ${response.payment_transaction.transaction_id}`);
            console.log(`Transaction Timestamp: ${response.payment_transaction.transaction_timestamp}`);
        }

        // here's the entire object:
        console.log(JSON.stringify(response, null, 2));

        if (response.error) {
            console.log(`Error: ${response.error.user_message}`);
        }
    }
}

export default ProcessPayment;

Refund an order

Permissions:
  • order_write

Consumes: application/json
Produces: application/json
put
/order/orders/{order_id}/refund

Perform a refund operation on an order and then update the order if successful. All of the object properties ending in _refunded should be the TOTAL amount that should end up being refunded. UltraCart will calculate the actual amount to refund based upon the prior refunds.

SDK Function Name: refundOrder

Parameters
Parameter Description Location Data Type Required
order Order to refund body Order required
order_id The order id to refund. path string required
reject_after_refund Reject order after refund
Default: false
query boolean optional
skip_customer_notification Skip customer email notification
Default: false
query boolean optional
auto_order_cancel Cancel associated auto orders
Default: false
query boolean optional
manual_refund Consider a manual refund done externally
Default: false
query boolean optional
reverse_affiliate_transactions Reverse affiliate transactions
Default: true
query boolean optional
issue_store_credit Issue a store credit instead of refunding the original payment method, loyalty must be configured on merchant account
Default: false
query boolean optional
auto_order_cancel_reason Reason for auto orders cancellation query string optional
_expand The object expansion to perform on the result. See documentation for examples query string optional
Responses
Status Code Reason Response Model
200
Successful response OrderResponse
400
Bad Request 400
401
Unauthorized 401
410
Authorized Application Disabled 410
429
Too Many Requests 429
500
Server Side 500
using System;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;
using Newtonsoft.Json;

namespace SdkSample.order
{
    public class RefundOrder
    {
        /*
         * refundOrder() allows for both partial and complete refunds. Both are accomplished with the same steps.
         * 1) retrieve an order object using the SDK.
         * 2) input the refunded quantities for any or all items
         * 3) call refundOrder, passing in the modified object.
         * 4) To do a full refund, set all item refund quantities to their purchased quantities.
         *
         * This example will perform a full refund.
         */
        public static void Execute()
        {
            OrderApi orderApi = new OrderApi(Constants.ApiKey);

            // for the refund, I only need the items expanded to adjust their quantities.
            // See: https://www.ultracart.com/api/ for a list of all expansions.
            string expand = "items";

            // Step 1. Retrieve the order
            string orderId = "DEMO-0009104436";
            Order order = orderApi.GetOrder(orderId, expand).Order;

            foreach (OrderItem item in order.Items)
            {
                item.QuantityRefunded = item.Quantity;
            }

            bool rejectAfterRefund = false;
            bool skipCustomerNotification = true;
            bool cancelAssociatedAutoOrders = true; // does not matter for this sample. the order is not a recurring order.
            bool considerManualRefundDoneExternally = false; // no, I want an actual refund done through my gateway
            bool reverseAffiliateTransactions = true; // can't let my affiliates get money on a refunded order. bad business.
            bool issueStoreCredit = false;
            string autoCancelReason = null;

            OrderResponse apiResponse = orderApi.RefundOrder(
                orderId,
                order, 
                rejectAfterRefund, 
                skipCustomerNotification,
                cancelAssociatedAutoOrders, 
                considerManualRefundDoneExternally, 
                reverseAffiliateTransactions,
                issueStoreCredit,
                autoCancelReason,
                expand
            );

            Order refundedOrder = apiResponse.Order;

            // examine the subtotals and ensure everything was refunded correctly.
            Console.WriteLine(JsonConvert.SerializeObject(refundedOrder, new JsonSerializerSettings { Formatting = Formatting.Indented}));
        }
    }
}
package order;

import com.ultracart.admin.v2.OrderApi;
import com.ultracart.admin.v2.models.*;
import com.ultracart.admin.v2.util.ApiException;

/*
 * refundOrder() allows for both partial and complete refunds. Both are accomplished with the same steps.
 * 1) retrieve an order object using the SDK.
 * 2) input the refunded quantities for any or all items
 * 3) call refundOrder, passing in the modified object.
 * 4) To do a full refund, set all item refund quantities to their purchased quantities.
 *
 * This example will perform a full refund.
 */
public class RefundOrder {
    public static void execute() throws ApiException {
        OrderApi orderApi = new OrderApi(common.Constants.API_KEY);

        // for the refund, I only need the items expanded to adjust their quantities.
        // See: https://www.ultracart.com/api/ for a list of all expansions.
        String expand = "items";

        // Step 1. Retrieve the order
        String orderId = "DEMO-0009104436";
        Order order = orderApi.getOrder(orderId, expand).getOrder();

        for (OrderItem item : order.getItems()) {
            item.setQuantityRefunded(item.getQuantity());
        }

        boolean rejectAfterRefund = false;
        boolean skipCustomerNotification = true;
        boolean cancelAssociatedAutoOrders = true; // does not matter for this sample. the order is not a recurring order.
        boolean considerManualRefundDoneExternally = false; // no, I want an actual refund done through my gateway
        boolean reverseAffiliateTransactions = true; // can't let my affiliates get money on a refunded order. bad business.
        boolean issueStoreCredit = false;
        String autoCancelReason = null;

        OrderResponse apiResponse = orderApi.refundOrder(
            orderId,
            order,
            rejectAfterRefund,
            skipCustomerNotification,
            cancelAssociatedAutoOrders,
            considerManualRefundDoneExternally,
            reverseAffiliateTransactions,
            issueStoreCredit,
            autoCancelReason,
            expand
        );

        Order refundedOrder = apiResponse.getOrder();

        // examine the subtotals and ensure everything was refunded correctly.
        System.out.println(refundedOrder.toString());
    }
}
import {orderApi} from '../api.js';

/*
 * refundOrder() allows for both partial and complete refunds. Both are accomplished with the same steps.
 * 1) retrieve an order object using the SDK.
 * 2) input the refunded quantities for any or all items
 * 3) call refundOrder, passing in the modified object.
 * 4) To do a full refund, set all item refund quantities to their purchased quantities.
 *
 * This example will perform a full refund.
 */
export class RefundOrder {
    static async execute() {
        // for the refund, I only need the items expanded to adjust their quantities.
        // See: https://www.ultracart.com/api/ for a list of all expansions.
        const expand = "items";

        // Step 1. Retrieve the order
        const orderId = "DEMO-0009104436";
        const orderResponse = await new Promise((resolve, reject) => {
            orderApi.getOrder(orderId,
                {
                    _expand: expand
                }, function (error, data, response) {
                    if (error) {
                        reject(error);
                    } else {
                        resolve(data);
                    }
                });
        });

        const order = orderResponse.order;
        if (order) {
            for (const item of order.items) {
                item.quantity_refunded = item.quantity;
            }

            const rejectAfterRefund = false;
            const skipCustomerNotification = true;
            const cancelAssociatedAutoOrders = true; // does not matter for this sample. the order is not a recurring order.
            const considerManualRefundDoneExternally = false; // no, I want an actual refund done through my gateway
            const reverseAffiliateTransactions = true; // can't let my affiliates get money on a refunded order. bad business.
            const issueStoreCredit = false;
            const autoCancelReason = undefined;

            const apiResponse = await new Promise((resolve, reject) => {
                orderApi.refundOrder(
                    orderId,
                    order,
                    {
                        rejectAfterRefund: rejectAfterRefund,
                        skipCustomerNotification: skipCustomerNotification,
                        autoOrderCancel: cancelAssociatedAutoOrders,
                        manualRefund: considerManualRefundDoneExternally,
                        reverseAffiliateTransactions: reverseAffiliateTransactions,
                        issueStoreCredit: issueStoreCredit,
                        autoOrderCancelReason: autoCancelReason,
                        _expand: expand
                    }, function (error, data, response) {
                        if (error) {
                            reject(error);
                        } else {
                            resolve(data);
                        }
                    });
            });

            const refundedOrder = apiResponse.order;

            // examine the subtotals and ensure everything was refunded correctly.
            console.log(JSON.stringify(refundedOrder, null, 2));
        }
    }
}
<?php /** @noinspection DuplicatedCode */

require_once '../vendor/autoload.php';
require_once '../constants.php';

/*
 * refundOrder() allows for both partial and complete refunds.  Both are accomplished with the same steps.
 * 1) retrieve an order object using the SDK.
 * 2) input the refunded quantities for any or all items
 * 3) call refundOrder, passing in the modified object.
 * 4) To do a full refund, set all item refund quantities to their purchased quantities.
 *
 * This example will perform a full refund.
 *
 */

use ultracart\v2\api\OrderApi;
use ultracart\v2\models\Order;
use ultracart\v2\models\OrderItem;

$order_api = OrderApi::usingApiKey(Constants::API_KEY, 0, false);

// for the refund, I only need the items expanded to adjust their quantities.
// See: https://www.ultracart.com/api/  for a list of all expansions.
$expansion = "items";

// Step 1. Retrieve the order
$order_id = 'DEMO-0009104436';
$order = $order_api->getOrder($order_id, $expansion)->getOrder();


foreach($order->getItems() as $item){
    $item->setQuantityRefunded($item->getQuantity());
}

$reject_after_refund = false;
$skip_customer_notification = true;
$cancel_associated_auto_orders = true; // does not matter for this sample. the order is not a recurring order.
$consider_manual_refund_done_externally = false; // no, I want an actual refund done through my gateway
$reverse_affiliate_transactions = true; // can't let my affiliates get money on a refunded order.  bad business.

/** @noinspection PhpConditionAlreadyCheckedInspection */
$api_response = $order_api->refundOrder($order_id, $order, $reject_after_refund, $skip_customer_notification,
    $cancel_associated_auto_orders, $consider_manual_refund_done_externally, $reverse_affiliate_transactions, false, null, $expansion);

$refunded_order = $api_response->getOrder();

// examined the subtotals and ensure everything was refunded correctly.
echo '<html lang="en"><body><pre>';
var_dump($refunded_order);
echo '</pre></body></html>';

import logging
from ultracart import ApiException
from ultracart.apis import OrderApi
from ultracart.models import OrderItem
from samples import api_client

# Enable error logging
logging.basicConfig(level=logging.DEBUG)

# refundOrder() allows for both partial and complete refunds. Both are accomplished with the same steps.
# 1) Retrieve an order object using the SDK.
# 2) Input the refunded quantities for any or all items.
# 3) Call refundOrder, passing in the modified object.
# 4) To do a full refund, set all item refund quantities to their purchased quantities.
#
# This example will perform a full refund.

# Using the API key to initialize the order API
order_api = OrderApi(api_client())

# For the refund, we only need the items expanded to adjust their quantities.
# See: https://www.ultracart.com/api/ for a list of all expansions.
expand = "items"

# Step 1. Retrieve the order
order_id = 'DEMO-0009104436'
try:
    api_response = order_api.get_order(order_id, expand=expand)
except ApiException as e:
    logging.error(f"Exception when calling OrderApi->get_order: {e}")
    exit()

order = api_response.order

# Step 2. Adjust the refunded quantities
for item in order.items:
    item.quantity_refunded = item.quantity

# Step 3. Refund the order with the modified items
reject_after_refund = False
skip_customer_notification = True
cancel_associated_auto_orders = True  # Does not matter for this sample. The order is not a recurring order.
consider_manual_refund_done_externally = False  # No, I want an actual refund done through my gateway.
reverse_affiliate_transactions = True  # Can't let my affiliates get money on a refunded order. Bad business.

try:
    refund_response = order_api.refund_order(order_id, order, reject_after_refund, skip_customer_notification,
                                             cancel_associated_auto_orders, consider_manual_refund_done_externally,
                                             reverse_affiliate_transactions, include_refunded_amounts=False,
                                             reason=None, expand=expand)
except ApiException as e:
    logging.error(f"Exception when calling OrderApi->refund_order: {e}")
    exit()

refunded_order = refund_response.order

# Examining the refunded order and ensuring everything was refunded correctly
import pprint
print("Refunded Order:")
pprint.pprint(refunded_order)

require 'ultracart_api'
require_relative '../constants'

# refund_order() allows for both partial and complete refunds. Both are accomplished with the same steps.
# 1) retrieve an order object using the SDK.
# 2) input the refunded quantities for any or all items
# 3) call refund_order, passing in the modified object.
# 4) To do a full refund, set all item refund quantities to their purchased quantities.
#
# This example will perform a full refund.

order_api = UltracartClient::OrderApi.new_using_api_key(Constants::API_KEY)

# for the refund, I only need the items expanded to adjust their quantities.
# See: https://www.ultracart.com/api/  for a list of all expansions.
expansion = "items"

# Step 1. Retrieve the order
order_id = 'DEMO-0009104436'
order = order_api.get_order(order_id, opts = { _expand: expansion }).order

order.items.each do |item|
  item.quantity_refunded = item.quantity
end

reject_after_refund = false
skip_customer_notification = true
cancel_associated_auto_orders = true # does not matter for this sample. the order is not a recurring order.
consider_manual_refund_done_externally = false # no, I want an actual refund done through my gateway
reverse_affiliate_transactions = true # can't let my affiliates get money on a refunded order. bad business.

opts = {
  _expand: expansion,
  'skip_customer_notification': skip_customer_notification,
  'cancel_associated_auto_orders': cancel_associated_auto_orders,
  'consider_manual_refund_done_externally': consider_manual_refund_done_externally,
  'reverse_affiliate_transactions': reverse_affiliate_transactions
}

api_response = order_api.refund_order(order_id, order, opts)

refunded_order = api_response.order

# examined the subtotals and ensure everything was refunded correctly.
p refunded_order
import {orderApi} from '../api';
import {Order, OrderItem, OrderResponse} from 'ultracart_rest_api_v2_typescript';
import {DateTime} from 'luxon';

/*
 * refundOrder() allows for both partial and complete refunds. Both are accomplished with the same steps.
 * 1) retrieve an order object using the SDK.
 * 2) input the refunded quantities for any or all items
 * 3) call refundOrder, passing in the modified object.
 * 4) To do a full refund, set all item refund quantities to their purchased quantities.
 *
 * This example will perform a full refund.
 */
export class RefundOrder {
    public static async execute(): Promise<void> {
        // for the refund, I only need the items expanded to adjust their quantities.
        // See: https://www.ultracart.com/api/ for a list of all expansions.
        const expand: string = "items";

        // Step 1. Retrieve the order
        const orderId: string = "DEMO-0009104436";
        const orderOrUndefined: Order | undefined = (await orderApi.getOrder({orderId, expand})).order;
        if (orderOrUndefined !== undefined) {
            const order = orderOrUndefined as Order;


            for (const item of order.items as OrderItem[]) {
                item.quantity_refunded = item.quantity;
            }

            const rejectAfterRefund: boolean = false;
            const skipCustomerNotification: boolean = true;
            const cancelAssociatedAutoOrders: boolean = true; // does not matter for this sample. the order is not a recurring order.
            const considerManualRefundDoneExternally: boolean = false; // no, I want an actual refund done through my gateway
            const reverseAffiliateTransactions: boolean = true; // can't let my affiliates get money on a refunded order. bad business.
            const issueStoreCredit: boolean = false;
            const autoCancelReason: string | undefined = undefined;

            const apiResponse: OrderResponse = await orderApi.refundOrder({
                orderId: orderId,
                order: order,
                rejectAfterRefund: rejectAfterRefund,
                skipCustomerNotification: skipCustomerNotification,
                autoOrderCancel: cancelAssociatedAutoOrders,
                manualRefund: considerManualRefundDoneExternally,
                reverseAffiliateTransactions: reverseAffiliateTransactions,
                issueStoreCredit: issueStoreCredit,
                autoOrderCancelReason: autoCancelReason,
                expand: expand
            });

            const refundedOrder: Order | undefined = apiResponse.order;

            // examine the subtotals and ensure everything was refunded correctly.
            console.log(JSON.stringify(refundedOrder, null, 2));
        }
    }
}

Determine if an order can be refunded

Permissions:
  • order_write

Consumes: application/json
Produces: application/json
get
/order/orders/{order_id}/refundable

Determine if an order can be refunded based upon payment method and age

SDK Function Name: isRefundableOrder

Parameters
Parameter Description Location Data Type Required
order_id The order id to check for refundable order. path string required
Responses
Status Code Reason Response Model
200
Successful response OrderRefundableResponse
400
Bad Request 400
401
Unauthorized 401
410
Authorized Application Disabled 410
429
Too Many Requests 429
500
Server Side 500
using System;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;
using Newtonsoft.Json;

namespace SdkSample.order
{
    public class IsRefundableOrder
    {
        /*
            isRefundable queries the UltraCart system whether an order is refundable or not.
            In addition to a simple boolean response, UltraCart also returns back any reasons why
            an order is not refundable.
            Finally, the response also contains any refund or return reasons configured on the account in the event
            that this merchant account is configured to require a reason for a return or refund.
         */
        public static void Execute()
        {
            OrderApi orderApi = new OrderApi(Constants.ApiKey);

            string orderId = "DEMO-0009104976";
            OrderRefundableResponse refundableResponse = orderApi.IsRefundableOrder(orderId);
            Console.WriteLine($"Is Refundable: {refundableResponse.Refundable}");

            // the response contains dropdown values and additional information.  It's much more than a true/false flag.
            Console.WriteLine("API Response:");
            Console.WriteLine(JsonConvert.SerializeObject(refundableResponse, new JsonSerializerSettings { Formatting = Formatting.Indented}));            
        }
    }
}
package order;

import com.ultracart.admin.v2.OrderApi;
import com.ultracart.admin.v2.models.*;
import com.ultracart.admin.v2.util.ApiException;
import common.Constants;

public class IsRefundableOrder {
    /*
        isRefundable queries the UltraCart system whether an order is refundable or not.
        In addition to a simple boolean response, UltraCart also returns back any reasons why
        an order is not refundable.
        Finally, the response also contains any refund or return reasons configured on the account in the event
        that this merchant account is configured to require a reason for a return or refund.
     */
    public static void execute() throws ApiException {
        OrderApi orderApi = new OrderApi(Constants.API_KEY);

        String orderId = "DEMO-0009104976";
        OrderRefundableResponse refundableResponse = orderApi.isRefundableOrder(orderId);
        System.out.println("Is Refundable: " + refundableResponse.getRefundable());

        // the response contains dropdown values and additional information.  It's much more than a true/false flag.
        System.out.println("API Response:");
        System.out.println(refundableResponse.toString());
    }
}
import { orderApi } from '../api.js';

/**
 * isRefundable queries the UltraCart system whether an order is refundable or not.
 * In addition to a simple boolean response, UltraCart also returns back any reasons why
 * an order is not refundable.
 * Finally, the response also contains any refund or return reasons configured on the account in the event
 * that this merchant account is configured to require a reason for a return or refund.
 */
export class IsRefundableOrder {
    /**
     * Execute the refundable order check
     */
    static async execute() {
        const orderId = "DEMO-0009104976";

        try {
            const refundableResponse = await new Promise((resolve, reject) => {
                orderApi.isRefundableOrder(orderId, function(error, data, response) {
                    if (error) {
                        reject(error);
                    } else {
                        resolve(data);
                    }
                });
            });

            console.log(`Is Refundable: ${refundableResponse.refundable}`);

            // the response contains dropdown values and additional information.  It's much more than a true/false flag.
            console.log("API Response:");
            console.log(JSON.stringify(refundableResponse, null, 2));
        } catch (error) {
            console.error("Error checking refundable status:", error);
        }
    }
}
<?php

ini_set('display_errors', 1);

use ultracart\v2\api\OrderApi;

require_once '../vendor/autoload.php';
require_once '../constants.php';

/*
    isRefundable queries the UltraCart system whether an order is refundable or not.
    In addition to a simple boolean response, UltraCart also returns back any reasons why
    an order is not refundable.
    Finally, the response also contains any refund or return reasons configured on the account in the event
    that this merchant account is configured to require a reason for a return or refund.

 */


$order_api = OrderApi::usingApiKey(Constants::API_KEY, false, false);


$order_id = 'DEMO-0009104976';
$api_response = $order_api->isRefundableOrder($order_id);

echo '<html lang="en"><body><pre>';
var_dump($api_response);
echo '</pre></body></html>';

import logging
from ultracart import ApiException
from ultracart.apis import OrderApi
from samples import api_client

# Enable error logging
logging.basicConfig(level=logging.DEBUG)

# isRefundable queries the UltraCart system whether an order is refundable or not.
# In addition to a simple boolean response, UltraCart also returns back any reasons why
# an order is not refundable.
# Finally, the response also contains any refund or return reasons configured on the account
# in the event that this merchant account is configured to require a reason for a return or refund.

# Using the API key to initialize the order API
order_api = OrderApi(api_client())

order_id = 'DEMO-0009104976'

try:
    api_response = order_api.is_refundable_order(order_id)
except ApiException as e:
    logging.error(f"Exception when calling OrderApi->is_refundable_order: {e}")
    exit()

# This could get verbose...
import pprint
pprint.pprint(api_response)

require 'ultracart_api'
require_relative '../constants'

# isRefundable queries the UltraCart system whether an order is refundable or not.
# In addition to a simple boolean response, UltraCart also returns back any reasons why
# an order is not refundable.
# Finally, the response also contains any refund or return reasons configured on the account in the event
# that this merchant account is configured to require a reason for a return or refund.

order_api = UltracartClient::OrderApi.new_using_api_key(Constants::API_KEY)

order_id = 'DEMO-0009104976'
api_response = order_api.is_refundable_order(order_id)

p api_response
import { orderApi } from '../api';
import { OrderRefundableResponse } from 'ultracart_rest_api_v2_typescript';

/**
 * isRefundable queries the UltraCart system whether an order is refundable or not.
 * In addition to a simple boolean response, UltraCart also returns back any reasons why
 * an order is not refundable.
 * Finally, the response also contains any refund or return reasons configured on the account in the event
 * that this merchant account is configured to require a reason for a return or refund.
 */
export class IsRefundableOrder {
    /**
     * Execute the refundable order check
     */
    public static async execute(): Promise<void> {
        const orderId = "DEMO-0009104976";

        try {
            const refundableResponse: OrderRefundableResponse = await orderApi.isRefundableOrder({
                orderId: orderId
            });

            console.log(`Is Refundable: ${refundableResponse.refundable}`);

            // the response contains dropdown values and additional information.  It's much more than a true/false flag.
            console.log("API Response:");
            console.log(JSON.stringify(refundableResponse, null, 2));
        } catch (error) {
            console.error("Error checking refundable status:", error);
        }
    }
}


Replacement order

Permissions:
  • order_write

Produces: application/json
post
/order/orders/{order_id}/replacement

Create a replacement order based upon a previous order

SDK Function Name: replacement

Parameters
Parameter Description Location Data Type Required
order_id The order id to generate a replacement for. path string required
replacement Replacement order details body OrderReplacement required
Responses
Status Code Reason Response Model
200
Successful response OrderReplacementResponse
400
Bad Request 400
401
Unauthorized 401
410
Authorized Application Disabled 410
429
Too Many Requests 429
500
Server Side 500
using System;
using System.Collections.Generic;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;

namespace SdkSample.order
{
    public class Replacement
    {
        /*
         * The use-case for replacement() is to create another order for a customer to replace the items of the existing
         * order. For example, a merchant is selling perishable goods and the goods arrive late, spoiled. replacement()
         * helps to create another order to send more goods to the customer.
         *
         * You MUST supply the items you desire in the replacement order. This is done with the OrderReplacement.items field.
         * All options are displayed below including whether to charge the customer for this replacement order or not.
         */
        public static void Execute()
        {
            OrderApi orderApi = new OrderApi(Constants.ApiKey);

            // Step 1. Replace the order
            string orderIdToReplace = "DEMO-0009104436";
            OrderReplacement replacementOptions = new OrderReplacement();
            replacementOptions.OriginalOrderId = orderIdToReplace;

            List<OrderReplacementItem> items = new List<OrderReplacementItem>();

            OrderReplacementItem item1 = new OrderReplacementItem();
            item1.MerchantItemId = "TSHIRT";
            item1.Quantity = 1;
            // item1.ArbitraryUnitCost = 9.99m;
            items.Add(item1);

            OrderReplacementItem item2 = new OrderReplacementItem();
            item2.MerchantItemId = "BONE";
            item2.Quantity = 2;
            items.Add(item2);

            replacementOptions.Items = items;

            // replacementOptions.ShippingMethod = "FedEx: Ground";
            replacementOptions.ImmediateCharge = true;
            replacementOptions.SkipPayment = true;
            replacementOptions.Free = true;
            replacementOptions.CustomField1 = "Whatever";
            replacementOptions.CustomField4 = "More Whatever";
            replacementOptions.AdditionalMerchantNotesNewOrder = "Replacement order for spoiled ice cream";
            replacementOptions.AdditionalMerchantNotesOriginalOrder = "This order was replaced.";

            OrderReplacementResponse apiResponse = orderApi.Replacement(orderIdToReplace, replacementOptions);

            Console.WriteLine($"Replacement Order: {apiResponse.OrderId}");
            Console.WriteLine($"Success flag: {apiResponse.Successful}");
        }
    }
}
package order;

import com.ultracart.admin.v2.OrderApi;
import com.ultracart.admin.v2.models.OrderReplacement;
import com.ultracart.admin.v2.models.OrderReplacementItem;
import com.ultracart.admin.v2.models.OrderReplacementResponse;
import com.ultracart.admin.v2.util.ApiException;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/*
* The use-case for replacement() is to create another order for a customer to replace the items of the existing
* order. For example, a merchant is selling perishable goods and the goods arrive late, spoiled. replacement()
* helps to create another order to send more goods to the customer.
*
* You MUST supply the items you desire in the replacement order. This is done with the OrderReplacement.items field.
* All options are displayed below including whether to charge the customer for this replacement order or not.
*/
public class Replacement {
   public static void execute() throws ApiException {
       OrderApi orderApi = new OrderApi(common.Constants.API_KEY);

       // Step 1. Replace the order
       String orderIdToReplace = "DEMO-0009104436";
       OrderReplacement replacementOptions = new OrderReplacement();
       replacementOptions.setOriginalOrderId(orderIdToReplace);

       List<OrderReplacementItem> items = new ArrayList<>();

       OrderReplacementItem item1 = new OrderReplacementItem();
       item1.setMerchantItemId("TSHIRT");
       item1.setQuantity(BigDecimal.valueOf(1));
       // item1.setArbitraryUnitCost(9.99);
       items.add(item1);

       OrderReplacementItem item2 = new OrderReplacementItem();
       item2.setMerchantItemId("BONE");
       item2.setQuantity(BigDecimal.valueOf(2));
       items.add(item2);

       replacementOptions.setItems(items);

       // replacementOptions.setShippingMethod("FedEx: Ground");
       replacementOptions.setImmediateCharge(true);
       replacementOptions.setSkipPayment(true);
       replacementOptions.setFree(true);
       replacementOptions.setCustomField1("Whatever");
       replacementOptions.setCustomField4("More Whatever");
       replacementOptions.setAdditionalMerchantNotesNewOrder("Replacement order for spoiled ice cream");
       replacementOptions.setAdditionalMerchantNotesOriginalOrder("This order was replaced.");

       OrderReplacementResponse apiResponse = orderApi.replacement(orderIdToReplace, replacementOptions);

       System.out.println("Replacement Order: " + apiResponse.getOrderId());
       System.out.println("Success flag: " + apiResponse.getSuccessful());
   }
}
import {orderApi} from '../api.js';

/*
 * The use-case for replacement() is to create another order for a customer to replace the items of the existing
 * order. For example, a merchant is selling perishable goods and the goods arrive late, spoiled. replacement()
 * helps to create another order to send more goods to the customer.
 *
 * You MUST supply the items you desire in the replacement order. This is done with the OrderReplacement.items field.
 * All options are displayed below including whether to charge the customer for this replacement order or not.
 */
export class Replacement {
    static async execute() {
        // Step 1. Replace the order
        const orderIdToReplace = "DEMO-0009104436";
        const replacementOptions = {
            original_order_id: orderIdToReplace,
            items: [
                {
                    merchant_item_id: "TSHIRT",
                    quantity: 1,
                    // arbitraryUnitCost: 9.99 // Commented out as in original
                },
                {
                    merchant_item_id: "BONE",
                    quantity: 2
                }
            ],
            // shippingMethod: "FedEx: Ground", // Commented out as in original
            immediate_charge: true,
            skip_payment: true,
            free: true,
            custom_field1: "Whatever",
            custom_field4: "More Whatever",
            additional_merchant_notes_new_order: "Replacement order for spoiled ice cream",
            additional_merchant_notes_original_order: "This order was replaced."
        };

        const apiResponse = await new Promise((resolve, reject) => {
            orderApi.replacement(
                orderIdToReplace,
                replacementOptions
                , function (error, data, response) {
                    if (error) {
                        reject(error);
                    } else {
                        resolve(data, response);
                    }
                });
        });

        console.log(`Replacement Order: ${apiResponse.orderId}`);
        console.log(`Success flag: ${apiResponse.successful}`);
    }
}
<?php /** @noinspection DuplicatedCode */

require_once '../vendor/autoload.php';
require_once '../constants.php';

/*
 * The use-case for replacement() is to create another order for a customer to replace the items of the existing
 * order.  For example, a merchant is selling perishable goods and the goods arrive late, spoiled.  replacement()
 * helps to create another order to send more goods to the customer.
 *
 * You MUST supply the items you desire in the replacement order.  This is done with the OrderReplacement.items field.
 * All options are displayed below including whether to charge the customer for this replacement order or not.
 *
 */

use ultracart\v2\api\OrderApi;
use ultracart\v2\models\OrderReplacement;
use ultracart\v2\models\OrderReplacementItem;

$order_api = OrderApi::usingApiKey(Constants::API_KEY);

// Step 1. Replace the order
$order_id_to_replace = 'DEMO-0009104436';
$replacement_options = new OrderReplacement();
$replacement_options->setOriginalOrderId($order_id_to_replace);

$items = array();

$item1 = new OrderReplacementItem();
$item1->setMerchantItemId('TSHIRT');
$item1->setQuantity(1);
// $item1->setArbitraryUnitCost(9.99);
$items[] = $item1;

$item2 = new OrderReplacementItem();
$item2->setMerchantItemId('BONE');
$item2->setQuantity(2);
$items[] = $item2;

$replacement_options->setItems($items);

// $replacement_options->getShippingMethod('FedEx: Ground');
$replacement_options->setImmediateCharge(true);
$replacement_options->setSkipPayment(true);
$replacement_options->setFree(true);
$replacement_options->setCustomField1('Whatever');
$replacement_options->setCustomField4('More Whatever');
$replacement_options->setAdditionalMerchantNotesNewOrder('Replacement order for spoiled ice cream');
$replacement_options->setAdditionalMerchantNotesOriginalOrder('This order was replaced.');

$api_response = $order_api->replacement($order_id_to_replace, $replacement_options);


echo '<html lang="en"><body><pre>';
echo 'Replacement Order: ' . $api_response->getOrderId();
echo 'Success flag: ' . $api_response->getSuccessful();
echo '</pre></body></html>';
from ultracart import ApiException
from ultracart.apis import OrderApi
from ultracart.models import OrderReplacement, OrderReplacementItem
from samples import api_client


'''
 * The use-case for replacement() is to create another order for a customer to replace the items of the existing
 * order.  For example, a merchant is selling perishable goods and the goods arrive late, spoiled.  replacement()
 * helps to create another order to send more goods to the customer.
 *
 * You MUST supply the items you desire in the replacement order.  This is done with the OrderReplacement.items field.
 * All options are displayed below including whether to charge the customer for this replacement order or not.
'''

# Initialize the Order API with the API key
order_api = OrderApi(api_client())

# Step 1. Replace the order
order_id_to_replace = 'DEMO-0009104436'
replacement_options = OrderReplacement()
replacement_options.original_order_id = order_id_to_replace

# Create replacement items
items = []

item1 = OrderReplacementItem()
item1.merchant_item_id = 'TSHIRT'
item1.quantity = 1
# $item1->setArbitraryUnitCost(9.99);  # Optional: Set cost if needed
items.append(item1)

item2 = OrderReplacementItem()
item2.merchant_item_id = 'BONE'
item2.quantity = 2
items.append(item2)

replacement_options.items = items

# Optional: Set various replacement options
replacement_options.immediate_charge = True
replacement_options.skip_payment = True
replacement_options.free = True
replacement_options.custom_field_1 = 'Whatever'
replacement_options.custom_field_4 = 'More Whatever'
replacement_options.additional_merchant_notes_new_order = 'Replacement order for spoiled ice cream'
replacement_options.additional_merchant_notes_original_order = 'This order was replaced.'

# Step 2. Call the replacement API
try:
    api_response = order_api.replacement(order_id_to_replace, replacement_options)
except ApiException as e:
    print(f"Exception when calling OrderApi->replacement: {e}")
    exit()

# Output the replacement order details
print(f"Replacement Order: {api_response.order_id}")
print(f"Success flag: {api_response.successful}")


require 'ultracart_api'
require_relative '../constants'

# The use-case for replacement() is to create another order for a customer to replace the items of the existing
# order. For example, a merchant is selling perishable goods and the goods arrive late, spoiled. replacement()
# helps to create another order to send more goods to the customer.
#
# You MUST supply the items you desire in the replacement order. This is done with the OrderReplacement.items field.
# All options are displayed below including whether to charge the customer for this replacement order or not.

order_api = UltracartClient::OrderApi.new_using_api_key(Constants::API_KEY)

# Step 1. Replace the order
order_id_to_replace = 'DEMO-0009104436'
replacement_options = UltracartClient::OrderReplacement.new
replacement_options.original_order_id = order_id_to_replace

items = []

item1 = UltracartClient::OrderReplacementItem.new
item1.merchant_item_id = 'TSHIRT'
item1.quantity = 1
# item1.arbitrary_unit_cost = 9.99
items << item1

item2 = UltracartClient::OrderReplacementItem.new
item2.merchant_item_id = 'BONE'
item2.quantity = 2
items << item2

replacement_options.items = items

# replacement_options.shipping_method = 'FedEx: Ground'
replacement_options.immediate_charge = true
replacement_options.skip_payment = true
replacement_options.free = true
replacement_options.custom_field1 = 'Whatever'
replacement_options.custom_field4 = 'More Whatever'
replacement_options.additional_merchant_notes_new_order = 'Replacement order for spoiled ice cream'
replacement_options.additional_merchant_notes_original_order = 'This order was replaced.'

api_response = order_api.replacement(order_id_to_replace, replacement_options)

puts "Replacement Order: #{api_response.order_id}"
puts "Success flag: #{api_response.successful}"
import {orderApi} from '../api';
import {OrderReplacement, OrderReplacementItem, OrderReplacementResponse} from 'ultracart_rest_api_v2_typescript';

/*
 * The use-case for replacement() is to create another order for a customer to replace the items of the existing
 * order. For example, a merchant is selling perishable goods and the goods arrive late, spoiled. replacement()
 * helps to create another order to send more goods to the customer.
 *
 * You MUST supply the items you desire in the replacement order. This is done with the OrderReplacement.items field.
 * All options are displayed below including whether to charge the customer for this replacement order or not.
 */
export class Replacement {
    public static async execute(): Promise<void> {
        // Step 1. Replace the order
        const orderIdToReplace: string = "DEMO-0009104436";
        const replacementOptions: OrderReplacement = {
            original_order_id: orderIdToReplace,
            items: [
                {
                    merchant_item_id: "TSHIRT",
                    quantity: 1,
                    // arbitraryUnitCost: 9.99 // Commented out as in original
                },
                {
                    merchant_item_id: "BONE",
                    quantity: 2
                }
            ],
            // shippingMethod: "FedEx: Ground", // Commented out as in original
            immediate_charge: true,
            skip_payment: true,
            free: true,
            custom_field1: "Whatever",
            custom_field4: "More Whatever",
            additional_merchant_notes_new_order: "Replacement order for spoiled ice cream",
            additional_merchant_notes_original_order: "This order was replaced."
        };

        const apiResponse: OrderReplacementResponse = await orderApi.replacement({
            orderId: orderIdToReplace,
            replacement: replacementOptions
        });

        console.log(`Replacement Order: ${apiResponse.orderId}`);
        console.log(`Success flag: ${apiResponse.successful}`);
    }
}

Resend receipt

Permissions:
  • order_write

Produces: application/json
post
/order/orders/{order_id}/resend_receipt

Resend the receipt for an order on the UltraCart account.

SDK Function Name: resendReceipt

Parameters
Parameter Description Location Data Type Required
order_id The order id to resend the receipt for. path string required
Responses
Status Code Reason Response Model
200
Successful response BaseResponse
400
Bad Request 400
401
Unauthorized 401
410
Authorized Application Disabled 410
429
Too Many Requests 429
500
Server Side 500
using System;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;

namespace SdkSample.order
{
    public class ResendReceipt
    {
        /*
         * OrderApi.resendReceipt() will resend (email) a receipt to a customer.
         */
        public static void Execute()
        {
            OrderApi orderApi = new OrderApi(Constants.ApiKey);

            string orderId = "DEMO-0009104436";

            BaseResponse apiResponse = orderApi.ResendReceipt(orderId);

            if (apiResponse.Error != null)
            {
                Console.Error.WriteLine(apiResponse.Error.DeveloperMessage);
                Console.Error.WriteLine(apiResponse.Error.UserMessage);
                Console.WriteLine("Order receipt could not be resent. See error log.");
                return;
            }

            if (apiResponse.Success)
            {
                Console.WriteLine("Receipt was resent.");
            }
            else
            {
                Console.WriteLine("Failed to resend receipt.");
            }
        }
    }
}
package order;

import com.ultracart.admin.v2.OrderApi;
import com.ultracart.admin.v2.models.*;
import com.ultracart.admin.v2.util.ApiException;

/*
* OrderApi.resendReceipt() will resend (email) a receipt to a customer.
*/
public class ResendReceipt {
   public static void execute() throws ApiException {
       OrderApi orderApi = new OrderApi(common.Constants.API_KEY);

       String orderId = "DEMO-0009104436";

       BaseResponse apiResponse = orderApi.resendReceipt(orderId);

       if (apiResponse.getError() != null) {
           System.err.println(apiResponse.getError().getDeveloperMessage());
           System.err.println(apiResponse.getError().getUserMessage());
           System.out.println("Order receipt could not be resent. See error log.");
           return;
       }

       if (apiResponse.getSuccess()) {
           System.out.println("Receipt was resent.");
       } else {
           System.out.println("Failed to resend receipt.");
       }
   }
}
import {orderApi} from '../api.js';

/*
 * OrderApi.resendReceipt() will resend (email) a receipt to a customer.
 */
export class ResendReceipt {
    static async execute() {
        const orderId = "DEMO-0009104436";

        const apiResponse = await new Promise((resolve, reject) => {
            orderApi.resendReceipt(
                orderId
                , function (error, data, response) {
                    if (error) {
                        reject(error);
                    } else {
                        resolve(data, response);
                    }
                });
        });

        if (apiResponse.error !== undefined) {
            console.error(apiResponse.error.developer_message);
            console.error(apiResponse.error.user_message);
            console.log("Order receipt could not be resent. See error log.");
            return;
        }

        if (apiResponse.success) {
            console.log("Receipt was resent.");
        } else {
            console.log("Failed to resend receipt.");
        }
    }
}
<?php /** @noinspection DuplicatedCode */

require_once '../vendor/autoload.php';
require_once '../constants.php';

/*
 * OrderApi.resendReceipt() will resend (email) a receipt to a customer.
 *
 */

use ultracart\v2\api\OrderApi;

$order_api = OrderApi::usingApiKey(Constants::API_KEY);

$order_id = 'DEMO-0009104436';

$api_response = $order_api->resendReceipt($order_id);

if ($api_response->getError() != null) {
    error_log($api_response->getError()->getDeveloperMessage());
    error_log($api_response->getError()->getUserMessage());
    echo 'Order could not be adjusted.  See php error log.';
    exit();
}

echo '<html lang="en"><body><pre>';
if($api_response->getSuccess()){
    echo 'Receipt was resent.';
} else {
    echo 'Failed to resend receipt.';
}
echo '</pre></body></html>';
from ultracart import ApiException
from ultracart.apis import OrderApi
from samples import api_client

# OrderApi.resendReceipt() will resend (email) a receipt to a customer.

# Initialize the Order API with the API key
order_api = OrderApi(api_client())

# The order ID to resend the receipt for
order_id = 'DEMO-0009104436'

# Call to resend the receipt
try:
    api_response = order_api.resend_receipt(order_id)
except ApiException as e:
    print(f"Exception when calling OrderApi->resend_receipt: {e}")
    exit()

# Check if there was an error in the API response
if api_response.error is not None:
    print(f"Developer Message: {api_response.error.developer_message}")
    print(f"User Message: {api_response.error.user_message}")
    print('Order could not be adjusted. See the error log.')
    exit()

# Output the result
if api_response.success:
    print('Receipt was resent.')
else:
    print('Failed to resend receipt.')

require 'ultracart_api'
require_relative '../constants'

# OrderApi.resend_receipt() will resend (email) a receipt to a customer.

order_api = UltracartClient::OrderApi.new_using_api_key(Constants::API_KEY)

order_id = 'DEMO-0009104436'

api_response = order_api.resend_receipt(order_id)

if api_response.error
  puts api_response.error.developer_message
  puts api_response.error.user_message
  puts 'Order could not be adjusted. See output above.'
  exit
end

if api_response.success
  puts 'Receipt was resent.'
else
  puts 'Failed to resend receipt.'
end
import {orderApi} from '../api';
import {BaseResponse} from 'ultracart_rest_api_v2_typescript';

/*
 * OrderApi.resendReceipt() will resend (email) a receipt to a customer.
 */
export class ResendReceipt {
    public static async execute(): Promise<void> {
        const orderId: string = "DEMO-0009104436";

        const apiResponse: BaseResponse = await orderApi.resendReceipt({
            orderId: orderId
        });

        if (apiResponse.error !== undefined) {
            console.error(apiResponse.error.developer_message);
            console.error(apiResponse.error.user_message);
            console.log("Order receipt could not be resent. See error log.");
            return;
        }

        if (apiResponse.success) {
            console.log("Receipt was resent.");
        } else {
            console.log("Failed to resend receipt.");
        }
    }
}

Resend shipment confirmation

Permissions:
  • order_write

Produces: application/json
post
/order/orders/{order_id}/resend_shipment_confirmation

Resend shipment confirmation for an order on the UltraCart account.

SDK Function Name: resendShipmentConfirmation

Parameters
Parameter Description Location Data Type Required
order_id The order id to resend the shipment notification for. path string required
Responses
Status Code Reason Response Model
200
Successful response BaseResponse
400
Bad Request 400
401
Unauthorized 401
410
Authorized Application Disabled 410
429
Too Many Requests 429
500
Server Side 500
using System;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;

namespace SdkSample.order
{
    public class ResendShipmentConfirmation
    {
        /*
         * OrderApi.resendShipmentConfirmation() will resend (email) a shipment confirmation to a customer.
         */
        public static void Execute()
        {
            OrderApi orderApi = new OrderApi(Constants.ApiKey);

            string orderId = "DEMO-0009104436";

            BaseResponse apiResponse = orderApi.ResendShipmentConfirmation(orderId);

            if (apiResponse.Error != null)
            {
                Console.Error.WriteLine(apiResponse.Error.DeveloperMessage);
                Console.Error.WriteLine(apiResponse.Error.UserMessage);
                Console.WriteLine("Order could not be adjusted. See error log.");
                return;
            }

            if (apiResponse.Success)
            {
                Console.WriteLine("Shipment confirmation was resent.");
            }
            else
            {
                Console.WriteLine("Failed to resend shipment confirmation.");
            }
        }
    }
}
package order;

import com.ultracart.admin.v2.OrderApi;
import com.ultracart.admin.v2.models.*;
import com.ultracart.admin.v2.util.ApiException;

/*
* OrderApi.resendShipmentConfirmation() will resend (email) a shipment confirmation to a customer.
*/
public class ResendShipmentConfirmation {
   public static void execute() throws ApiException {
       OrderApi orderApi = new OrderApi(common.Constants.API_KEY);

       String orderId = "DEMO-0009104436";

       BaseResponse apiResponse = orderApi.resendShipmentConfirmation(orderId);

       if (apiResponse.getError() != null) {
           System.err.println(apiResponse.getError().getDeveloperMessage());
           System.err.println(apiResponse.getError().getUserMessage());
           System.out.println("Order could not be adjusted. See error log.");
           return;
       }

       if (apiResponse.getSuccess()) {
           System.out.println("Shipment confirmation was resent.");
       } else {
           System.out.println("Failed to resend shipment confirmation.");
       }
   }
}
import { orderApi } from '../api.js';

/*
 * OrderApi.resendShipmentConfirmation() will resend (email) a shipment confirmation to a customer.
 */
export class ResendShipmentConfirmation {
    static async execute() {
        const orderId = "DEMO-0009104436";

        const apiResponse = await new Promise((resolve, reject) => {
            orderApi.resendShipmentConfirmation(
                orderId
            , function (error, data, response) {
                if (error) {
                    reject(error);
                } else {
                    resolve(data, response);
                }
            });
        });

        if (apiResponse.error !== undefined) {
            console.error(apiResponse.error.developer_message);
            console.error(apiResponse.error.user_message);
            console.log("Order could not be adjusted. See error log.");
            return;
        }

        if (apiResponse.success) {
            console.log("Shipment confirmation was resent.");
        } else {
            console.log("Failed to resend shipment confirmation.");
        }
    }
}
<?php /** @noinspection DuplicatedCode */

require_once '../vendor/autoload.php';
require_once '../constants.php';

use ultracart\v2\api\OrderApi;

/*
 * OrderApi.resendShipmentConfirmation() will resend (email) a shipment confirmation to a customer.
 *
 */

$order_api = OrderApi::usingApiKey(Constants::API_KEY);

$order_id = 'DEMO-0009104436';

$api_response = $order_api->resendShipmentConfirmation($order_id);

if ($api_response->getError() != null) {
    error_log($api_response->getError()->getDeveloperMessage());
    error_log($api_response->getError()->getUserMessage());
    echo 'Order could not be adjusted.  See php error log.';
    exit();
}

echo '<html lang="en"><body><pre>';
if($api_response->getSuccess()){
    echo 'Shipment confirmation was resent.';
} else {
    echo 'Failed to resend shipment confirmation.';
}
echo '</pre></body></html>';
from ultracart import ApiException
from ultracart.apis import OrderApi
from samples import api_client

# OrderApi.resendShipmentConfirmation() will resend (email) a shipment confirmation to a customer.

# Initialize the Order API with the API key
order_api = OrderApi(api_client())

# The order ID to resend the shipment confirmation for
order_id = 'DEMO-0009104436'

# Call to resend the shipment confirmation
try:
    api_response = order_api.resend_shipment_confirmation(order_id)
except ApiException as e:
    print(f"Exception when calling OrderApi->resend_shipment_confirmation: {e}")
    exit()

# Check if there was an error in the API response
if api_response.error is not None:
    print(f"Developer Message: {api_response.error.developer_message}")
    print(f"User Message: {api_response.error.user_message}")
    print('Order could not be adjusted. See the error log.')
    exit()

# Output the result
if api_response.success:
    print('Shipment confirmation was resent.')
else:
    print('Failed to resend shipment confirmation.')

require 'ultracart_api'
require_relative '../constants'

# OrderApi.resend_shipment_confirmation() will resend (email) a shipment confirmation to a customer.

order_api = UltracartClient::OrderApi.new_using_api_key(Constants::API_KEY)

order_id = 'DEMO-0009104436'

api_response = order_api.resend_shipment_confirmation(order_id)

if api_response.error
  puts api_response.error.developer_message
  puts api_response.error.user_message
  puts 'Order could not be adjusted. See output above.'
  exit
end

if api_response.success
  puts 'Shipment confirmation was resent.'
else
  puts 'Failed to resend shipment confirmation.'
end
import { orderApi } from '../api';
import { BaseResponse } from 'ultracart_rest_api_v2_typescript';

/*
 * OrderApi.resendShipmentConfirmation() will resend (email) a shipment confirmation to a customer.
 */
export class ResendShipmentConfirmation {
    public static async execute(): Promise<void> {
        const orderId: string = "DEMO-0009104436";

        const apiResponse: BaseResponse = await orderApi.resendShipmentConfirmation({
            orderId: orderId
        });

        if (apiResponse.error !== undefined) {
            console.error(apiResponse.error.developer_message);
            console.error(apiResponse.error.user_message);
            console.log("Order could not be adjusted. See error log.");
            return;
        }

        if (apiResponse.success) {
            console.log("Shipment confirmation was resent.");
        } else {
            console.log("Failed to resend shipment confirmation.");
        }
    }
}

Validate

Permissions:
  • order_read
  • order_write

Produces: application/json
post
/order/validate

Validate the order for errors. Specific checks can be passed to fine tune what is validated. Read and write permissions are required because the validate method may fix obvious address issues automatically which require update permission.This rest call makes use of the built-in translation of rest objects to UltraCart internal objects which also contains a multitude of validation checks that cannot be trapped. Therefore any time this call is made, you should also trap api exceptions and examine their content because it may contain validation issues. So check the response object and trap any exceptions.

SDK Function Name: validateOrder

Parameters
Parameter Description Location Data Type Required
validation_request Validation request body OrderValidationRequest required
Responses
Status Code Reason Response Model
200
Successful response OrderValidationResponse
400
Bad Request 400
401
Unauthorized 401
410
Authorized Application Disabled 410
429
Too Many Requests 429
500
Server Side 500
using System;
using System.Collections.Generic;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;
using Newtonsoft.Json;

namespace SdkSample.order
{
    public class ValidateOrder
    {
        /*
            validateOrder may be used to check for any and all validation errors that may result from an insertOrder
            or updateOrder call. Because those method are built on our existing infrastructure, some validation
            errors may not bubble up to the rest api call and instead be returned as generic "something went wrong" errors.
            This call will return detail validation issues needing correction.

            Within the ValidationRequest, you may leave the 'checks' array null to check for everything, or pass
            an array of the specific checks you desire. Here is a list of the checks:

            "Billing Address Provided"
            "Billing Destination Restriction"
            "Billing Phone Numbers Provided"
            "Billing State Abbreviation Valid"
            "Billing Validate City State Zip"
            "Email provided if required"
            "Gift Message Length"
            "Item Quantity Valid"
            "Items Present"
            "Merchant Specific Item Relationships"
            "One per customer violations"
            "Referral Code Provided"
            "Shipping Address Provided"
            "Shipping Destination Restriction"
            "Shipping Method Ignore Invalid"
            "Shipping Method Provided"
            "Shipping State Abbreviation Valid"
            "Shipping Validate City State Zip"
            "Special Instructions Length"
         */
        public static void Execute()
        {
            OrderApi orderApi = new OrderApi(Constants.ApiKey);

            string expansion = "checkout"; // see the getOrder sample for expansion discussion

            string orderId = "DEMO-0009104976";
            Order order = orderApi.GetOrder(orderId, expansion).Order;

            Console.WriteLine(JsonConvert.SerializeObject(order, new JsonSerializerSettings { Formatting = Formatting.Indented}));

            // TODO: do some updates to the order.
            OrderValidationRequest validationRequest = new OrderValidationRequest();
            validationRequest.Order = order;
            validationRequest.Checks = null; // leaving this null to perform all validations.

            OrderValidationResponse apiResponse = orderApi.ValidateOrder(validationRequest);

            Console.WriteLine("Validation errors:");
            if (apiResponse.Errors != null)
            {
                foreach (string error in apiResponse.Errors)
                {
                    Console.WriteLine($"- {error}");
                }
            }
            else
            {
                Console.WriteLine("No validation errors found.");
            }

            Console.WriteLine("\nValidation messages:");
            if (apiResponse.Messages != null)
            {
                foreach (string message in apiResponse.Messages)
                {
                    Console.WriteLine($"- {message}");
                }
            }
            else
            {
                Console.WriteLine("No validation messages found.");
            }
        }
    }
}
package order;

import com.ultracart.admin.v2.OrderApi;
import com.ultracart.admin.v2.models.Order;
import com.ultracart.admin.v2.models.OrderValidationRequest;
import com.ultracart.admin.v2.models.OrderValidationResponse;
import com.ultracart.admin.v2.util.ApiException;

/*
   validateOrder may be used to check for any and all validation errors that may result from an insertOrder
   or updateOrder call. Because those method are built on our existing infrastructure, some validation
   errors may not bubble up to the rest api call and instead be returned as generic "something went wrong" errors.
   This call will return detail validation issues needing correction.

   Within the ValidationRequest, you may leave the 'checks' array null to check for everything, or pass
   an array of the specific checks you desire. Here is a list of the checks:

   "Billing Address Provided"
   "Billing Destination Restriction"
   "Billing Phone Numbers Provided"
   "Billing State Abbreviation Valid"
   "Billing Validate City State Zip"
   "Email provided if required"
   "Gift Message Length"
   "Item Quantity Valid"
   "Items Present"
   "Merchant Specific Item Relationships"
   "One per customer violations"
   "Referral Code Provided"
   "Shipping Address Provided"
   "Shipping Destination Restriction"
   "Shipping Method Ignore Invalid"
   "Shipping Method Provided"
   "Shipping State Abbreviation Valid"
   "Shipping Validate City State Zip"
   "Special Instructions Length"
*/
public class ValidateOrder {
   public static void execute() throws ApiException {
       OrderApi orderApi = new OrderApi(common.Constants.API_KEY);

       String expansion = "checkout"; // see the getOrder sample for expansion discussion

       String orderId = "DEMO-0009104976";
       Order order = orderApi.getOrder(orderId, expansion).getOrder();

       System.out.println(order.toString());

       // TODO: do some updates to the order.
       OrderValidationRequest validationRequest = new OrderValidationRequest();
       validationRequest.setOrder(order);
       validationRequest.setChecks(null); // leaving this null to perform all validations.

       OrderValidationResponse apiResponse = orderApi.validateOrder(validationRequest);

       System.out.println("Validation errors:");
       if (apiResponse.getErrors() != null) {
           for (String error : apiResponse.getErrors()) {
               System.out.println("- " + error);
           }
       } else {
           System.out.println("No validation errors found.");
       }

       System.out.println("\nValidation messages:");
       if (apiResponse.getMessages() != null) {
           for (String message : apiResponse.getMessages()) {
               System.out.println("- " + message);
           }
       } else {
           System.out.println("No validation messages found.");
       }
   }
}
import {orderApi} from '../api.js';

export class ValidateOrder {
    /*
        validateOrder may be used to check for any and all validation errors that may result from an insertOrder
        or updateOrder call. Because those method are built on our existing infrastructure, some validation
        errors may not bubble up to the rest api call and instead be returned as generic "something went wrong" errors.
        This call will return detail validation issues needing correction.

        Within the ValidationRequest, you may leave the 'checks' array null to check for everything, or pass
        an array of the specific checks you desire. Here is a list of the checks:

        "Billing Address Provided"
        "Billing Destination Restriction"
        "Billing Phone Numbers Provided"
        "Billing State Abbreviation Valid"
        "Billing Validate City State Zip"
        "Email provided if required"
        "Gift Message Length"
        "Item Quantity Valid"
        "Items Present"
        "Merchant Specific Item Relationships"
        "One per customer violations"
        "Referral Code Provided"
        "Shipping Address Provided"
        "Shipping Destination Restriction"
        "Shipping Method Ignore Invalid"
        "Shipping Method Provided"
        "Shipping State Abbreviation Valid"
        "Shipping Validate City State Zip"
        "Special Instructions Length"
     */
    static async execute() {
        const expansion = "checkout"; // see the getOrder sample for expansion discussion

        const orderId = "DEMO-0009104976";
        const orderOrUndefined = await new Promise((resolve, reject) => {
            orderApi.getOrder(
                orderId,
                {_expand: expansion}, function (error, data, response) {
                    if (error) {
                        reject(error);
                    } else {
                        resolve(data);
                    }
                });
        });

        if (orderOrUndefined.order !== undefined) {
            const order = orderOrUndefined.order;

            console.log(JSON.stringify(order, null, 2));

            // TODO: do some updates to the order.
            const validationRequest = {
                order: order,
                checks: undefined // leaving this undefined to perform all validations.
            };

            const apiResponse = await new Promise((resolve, reject) => {
                orderApi.validateOrder(
                    validationRequest
                    , function (error, data, response) {
                        if (error) {
                            reject(error);
                        } else {
                            resolve(data);
                        }
                    });
            });

            console.log("Validation errors:");
            if (apiResponse.errors !== undefined) {
                for (const error of apiResponse.errors) {
                    console.log(`- ${error}`);
                }
            } else {
                console.log("No validation errors found.");
            }

            console.log("\nValidation messages:");
            if (apiResponse.messages !== undefined) {
                for (const message of apiResponse.messages) {
                    console.log(`- ${message}`);
                }
            } else {
                console.log("No validation messages found.");
            }
        }
    }
}
<?php

ini_set('display_errors', 1);

use ultracart\v2\api\OrderApi;
use ultracart\v2\models\OrderValidationRequest;

require_once '../vendor/autoload.php';
require_once '../constants.php';

/*
    validateOrder may be used to check for any and all validation errors that may result from an insertOrder
    or updateOrder call.  Because those method are built on our existing infrastructure, some validation
    errors may not bubble up to the rest api call and instead be returned as generic "something went wrong" errors.
    This call will return detail validation issues needing correction.

    Within the ValidationRequest, you may leave the 'checks' array null to check for everything, or pass
    an array of the specific checks you desire.  Here is a list of the checks:

    "Billing Address Provided"
    "Billing Destination Restriction"
    "Billing Phone Numbers Provided"
    "Billing State Abbreviation Valid"
    "Billing Validate City State Zip"
    "Email provided if required"
    "Gift Message Length"
    "Item Quantity Valid"
    "Items Present"
    "Merchant Specific Item Relationships"
    "One per customer violations"
    "Referral Code Provided"
    "Shipping Address Provided"
    "Shipping Destination Restriction"
    "Shipping Method Ignore Invalid"
    "Shipping Method Provided"
    "Shipping State Abbreviation Valid"
    "Shipping Validate City State Zip"
    "Special Instructions Length"

 */


$order_api = OrderApi::usingApiKey(Constants::API_KEY, false, false);

$expansion = "checkout"; // see the getOrder sample for expansion discussion

$order_id = 'DEMO-0009104976';
$order = $order_api->getOrder($order_id, $expansion)->getOrder();

echo '<html lang="en"><body><pre>';
var_dump($order);

// TODO: do some updates to the order.
$validationRequest = new OrderValidationRequest();
$validationRequest->setOrder($order);
$validationRequest->setChecks(null); // leaving this null to perform all validations.

$api_response = $order_api->validateOrder($validationRequest);

echo 'Validation errors:<br>';
if ($api_response->getErrors() != null) {
    foreach ($api_response->getErrors() as $error) {
        echo $error . "\n";
    }
}

echo 'Validation messages:<br>';
if ($api_response->getMessages() != null) {
    foreach ($api_response->getMessages() as $message) {
        echo $message . "\n";
    }
}

echo '</pre></body></html>';

from ultracart import ApiException
from ultracart.apis import OrderApi
from ultracart.models import OrderValidationRequest
from samples import api_client

# /*
#     validateOrder may be used to check for any and all validation errors that may result from an insertOrder
#     or updateOrder call.  Because those method are built on our existing infrastructure, some validation
#     errors may not bubble up to the rest api call and instead be returned as generic "something went wrong" errors.
#     This call will return detail validation issues needing correction.
#
#     Within the ValidationRequest, you may leave the 'checks' array null to check for everything, or pass
#     an array of the specific checks you desire.  Here is a list of the checks:
#
#     "Billing Address Provided"
#     "Billing Destination Restriction"
#     "Billing Phone Numbers Provided"
#     "Billing State Abbreviation Valid"
#     "Billing Validate City State Zip"
#     "Email provided if required"
#     "Gift Message Length"
#     "Item Quantity Valid"
#     "Items Present"
#     "Merchant Specific Item Relationships"
#     "One per customer violations"
#     "Referral Code Provided"
#     "Shipping Address Provided"
#     "Shipping Destination Restriction"
#     "Shipping Method Ignore Invalid"
#     "Shipping Method Provided"
#     "Shipping State Abbreviation Valid"
#     "Shipping Validate City State Zip"
#     "Special Instructions Length"
# */


# Initialize the Order API with the API key
order_api = OrderApi(api_client())

# Define the expansion to be used in the API call (related to checkout)
expansion = "checkout"  # see the getOrder sample for expansion discussion

# The order ID to retrieve
order_id = 'DEMO-0009104976'

# Step 1: Retrieve the order
try:
    api_response = order_api.get_order(order_id, expansion)
    order = api_response.order
except ApiException as e:
    print(f"Exception when calling OrderApi->get_order: {e}")
    exit()

# Output the current order details
print("<html lang='en'><body><pre>")
print(order)

# TODO: Do some updates to the order here.

# Step 2: Validate the order
validation_request = OrderValidationRequest()
validation_request.order = order
validation_request.checks = None  # leaving this null to perform all validations

try:
    api_response = order_api.validate_order(validation_request)
except ApiException as e:
    print(f"Exception when calling OrderApi->validate_order: {e}")
    exit()

# Output validation errors, if any
print('Validation errors:<br>')
if api_response.errors is not None:
    for error in api_response.errors:
        print(error)

# Output validation messages, if any
print('Validation messages:<br>')
if api_response.messages is not None:
    for message in api_response.messages:
        print(message)

print('</pre></body></html>')

require 'ultracart_api'
require_relative '../constants'

# validateOrder may be used to check for any and all validation errors that may result from an insert_order
# or update_order call. Because those methods are built on our existing infrastructure, some validation
# errors may not bubble up to the rest api call and instead be returned as generic "something went wrong" errors.
# This call will return detail validation issues needing correction.
#
# Within the ValidationRequest, you may leave the 'checks' array null to check for everything, or pass
# an array of the specific checks you desire. Here is a list of the checks:
#
# "Billing Address Provided"
# "Billing Destination Restriction"
# "Billing Phone Numbers Provided"
# "Billing State Abbreviation Valid"
# "Billing Validate City State Zip"
# "Email provided if required"
# "Gift Message Length"
# "Item Quantity Valid"
# "Items Present"
# "Merchant Specific Item Relationships"
# "One per customer violations"
# "Referral Code Provided"
# "Shipping Address Provided"
# "Shipping Destination Restriction"
# "Shipping Method Ignore Invalid"
# "Shipping Method Provided"
# "Shipping State Abbreviation Valid"
# "Shipping Validate City State Zip"
# "Special Instructions Length"

order_api = UltracartClient::OrderApi.new_using_api_key(Constants::API_KEY)

expansion = "checkout" # see the get_order sample for expansion discussion

order_id = 'DEMO-0009104976'
order = order_api.get_order(order_id, opts = { _expand: expansion }).order

p order

# TODO: do some updates to the order.
validation_request = UltracartClient::OrderValidationRequest.new
validation_request.order = order
validation_request.checks = nil # leaving this null to perform all validations.

api_response = order_api.validate_order(validation_request)

puts 'Validation errors:'
if api_response.errors
  api_response.errors.each do |error|
    puts error
  end
end

puts 'Validation messages:'
if api_response.messages
  api_response.messages.each do |message|
    puts message
  end
end
import {orderApi} from '../api';
import {Order, OrderValidationRequest, OrderValidationResponse} from 'ultracart_rest_api_v2_typescript';

export class ValidateOrder {
    /*
        validateOrder may be used to check for any and all validation errors that may result from an insertOrder
        or updateOrder call. Because those method are built on our existing infrastructure, some validation
        errors may not bubble up to the rest api call and instead be returned as generic "something went wrong" errors.
        This call will return detail validation issues needing correction.

        Within the ValidationRequest, you may leave the 'checks' array null to check for everything, or pass
        an array of the specific checks you desire. Here is a list of the checks:

        "Billing Address Provided"
        "Billing Destination Restriction"
        "Billing Phone Numbers Provided"
        "Billing State Abbreviation Valid"
        "Billing Validate City State Zip"
        "Email provided if required"
        "Gift Message Length"
        "Item Quantity Valid"
        "Items Present"
        "Merchant Specific Item Relationships"
        "One per customer violations"
        "Referral Code Provided"
        "Shipping Address Provided"
        "Shipping Destination Restriction"
        "Shipping Method Ignore Invalid"
        "Shipping Method Provided"
        "Shipping State Abbreviation Valid"
        "Shipping Validate City State Zip"
        "Special Instructions Length"
     */
    public static async execute(): Promise<void> {
        const expansion: string = "checkout"; // see the getOrder sample for expansion discussion

        const orderId: string = "DEMO-0009104976";
        const orderOrUndefined: Order | undefined = (await orderApi.getOrder({orderId, expand: expansion})).order;

        if (orderOrUndefined !== undefined) {
            const order = orderOrUndefined as Order;

            console.log(JSON.stringify(order, null, 2));

            // TODO: do some updates to the order.
            const validationRequest: OrderValidationRequest = {
                order: order,
                checks: undefined // leaving this undefined to perform all validations.
            };

            const apiResponse: OrderValidationResponse = await orderApi.validateOrder({validationRequest});

            console.log("Validation errors:");
            if (apiResponse.errors !== undefined) {
                for (const error of apiResponse.errors) {
                    console.log(`- ${error}`);
                }
            } else {
                console.log("No validation errors found.");
            }

            console.log("\nValidation messages:");
            if (apiResponse.messages !== undefined) {
                for (const message of apiResponse.messages) {
                    console.log(`- ${message}`);
                }
            } else {
                console.log("No validation messages found.");
            }
        }
    }
}

Webhooks

The following webhook events are generated for this resource.

Event Description Response Expansion
order_abandon_recovery Fired when an order happens after an abandon cart signifying a recovery. Order Yes
order_create Fired when an order is placed. Order Yes
order_update Fired when an order is updated. Order Yes
order_delete Fired when an order is deleted. Order Yes
order_stage_change Fired when an order stage changes. Order Yes
order_payment_failed Fired when a payment fails. Order Yes
order_payment_process Fired when a payment is processed. Order Yes
order_ship Fired when an order is shipped. Order Yes
order_ship_expected Fired when an order has an expected delivery date. Order Yes
order_ship_out_for_delivery Fired when an order is out for delivery. Order Yes
order_ship_delivered Fired when an order is delivered. Order Yes
order_reject Fired when an order is rejected. Order Yes
order_refund Fired when an order is refunded. Order Yes
order_s3_invoice Fired when an order has a PDF invoice archived to S3. Order Yes

AccountsReceivableRetryConfig

Attributes
Name Data Type Description
active boolean True if the retry should run daily. False puts the retry service into an inactive state for this merchant.
allow_process_linked_accounts boolean True if this account has linked accounts that it can process.
cancel_auto_order boolean If true also cancel the auto order if the order is rejected at the end
current_service_plan (read only) string The current service plan that the account is on.
daily_activity_list array of AccountsReceivableRetryDayActivity A list of days and what actions should take place on those days after an order reaches accounts receivable
managed_by_linked_account_merchant_id (read only) boolean If not null, this account is managed by the specified parent merchant id.
merchant_id string UltraCart merchant ID
notify_emails array of string A list of email addresses to receive summary notifications from the retry service.
notify_rejections boolean If true, email addresses are notified of rejections.
notify_successes boolean If true, email addresses are notified of successful charges.
process_linked_accounts boolean If true, all linked accounts are also processed using the same rules.
processing_percentage (read only) string The percentage rate charged for the service.
reject_at_end boolean If true, the order is rejected the day after the last configured activity day
transaction_rejects array of AccountsReceivableRetryTransactionReject Array of key/value pairs that when found in the response cause the rejection of the transaction.
trial_mode boolean True if the account is currently in trial mode. Set to false to exit trial mode.
trial_mode_expiration_dts (read only) string (dateTime) The date when trial mode expires. If this date is reached without exiting trial mode, the service will de-activate.

AccountsReceivableRetryConfigResponse

Attributes
Name Data Type Description
config AccountsReceivableRetryConfig
coupon_codes array of string
emails array of string
error Error Error object if unsuccessful
has_linked_accounts boolean
metadata ResponseMetadata Meta-data about the response such as payload or paging information
success boolean Indicates if API call was successful
warning Warning Warning object if a non-fatal issue or side-effect occurs

AccountsReceivableRetryDayActivity

Attributes
Name Data Type Description
charge boolean True if a charge attempt should be made on this day. False means the order should be rejected on this day.
coupon_code string The coupon code that should be applied to this order.
day integer (int32) The number of days since the order placed in Accounts Receivable

AccountsReceivableRetryStatAccount

Attributes
Name Data Type Description
days array of AccountsReceivableRetryStatMetrics
merchant_id string
overall AccountsReceivableRetryStatMetrics
revenue_for_period array of AccountsReceivableRetryStatRevenue

AccountsReceivableRetryStatMetrics

Attributes
Name Data Type Description
attempts integer (int32)
attempts_formatted string
conversion_rate number
conversion_rate_formatted string
day integer (int32)
discounts number
discounts_formatted string
revenue number
revenue_formatted string
successes integer (int32)
successes_formatted string

AccountsReceivableRetryStatRevenue

Attributes
Name Data Type Description
label string
revenue number

AccountsReceivableRetryStatsResponse

Attributes
Name Data Type Description
error Error Error object if unsuccessful
linked_accounts array of AccountsReceivableRetryStatAccount
metadata ResponseMetadata Meta-data about the response such as payload or paging information
overall AccountsReceivableRetryStatAccount
success boolean Indicates if API call was successful
warning Warning Warning object if a non-fatal issue or side-effect occurs

AccountsReceivableRetryTransactionReject

Attributes
Name Data Type Description
name string Transaction response name
value string Transaction response value

Activity

Attributes
Name Data Type Description
action string
channel string
metric string
storefront_oid integer (int32)
subject string
ts integer (int64)
type string
uuid string

AutoOrderItem

Attributes
Name Data Type Description
arbitrary_item_id string Arbitrary item id that should be rebilled instead of the normal schedule
arbitrary_percentage_discount number An arbitrary percentage discount to provide on future rebills
arbitrary_quantity number Arbitrary quantity to rebill
arbitrary_schedule_days integer (int32) The number of days to rebill if the frequency is set to an arbitrary number of days
arbitrary_unit_cost number Arbitrary unit cost that rebills of this item should occur at
arbitrary_unit_cost_remaining_orders integer (int32) The number of rebills to give the arbitrary unit cost on before reverting to normal pricing.
auto_order_item_oid integer (int32) Primary key of AutoOrderItem
calculated_next_shipment_dts (read only) string (dateTime) Calculated Date/time that this item is scheduled to rebill. Will be null if no more shipments are going to occur on this item
first_order_dts (read only) string (dateTime) Date/time of the first order of this item. Null if item added to auto order and has not been rebilled yet.
frequency string Frequency of the rebill if not a fixed schedule
Allowed Values
  • Weekly
  • Biweekly
  • Every...
  • Every 10 Days
  • Every 24 Days
  • Every 28 Days
  • Monthly
  • Every 45 Days
  • Every 2 Months
  • Every 3 Months
  • Every 4 Months
  • Every 5 Months
  • Every 6 Months
  • Yearly
  • Every 4 Weeks
  • Every 6 Weeks
  • Every 8 Weeks
future_schedules array of AutoOrderItemFutureSchedule The future rebill schedule for this item up to the next ten rebills
last_order_dts string (dateTime) Date/time of the last order of this item
life_time_value number The life time value of this item including the original purchase
next_item_id (read only) string Calculated next item id
next_preshipment_notice_dts string (dateTime) The date/time of when the next pre-shipment notice should be sent
next_shipment_dts string (dateTime) Date/time that this item is scheduled to rebill
no_order_after_dts string (dateTime) Date/time after which no additional rebills of this item should occur
number_of_rebills integer (int32) The number of times this item has rebilled
options array of AutoOrderItemOption Options associated with this item
original_item_id string The original item id purchased. This item controls scheduling. If you wish to modify a schedule, for example, from monthly to yearly, change this item from your monthly item to your yearly item, and then change the next_shipment_dts to your desired date.
original_quantity number The original quantity purchased
paused boolean True if paused. This field is an object instead of a primitive for backwards compatibility.
paypal_payer_id string The PayPal Payer ID tied to this item
paypal_recurring_payment_profile_id string The PayPal Profile ID tied to this item
preshipment_notice_sent boolean True if the preshipment notice associated with the next rebill has been sent
rebill_value number The value of the rebills of this item
remaining_repeat_count integer (int32) The number of rebills remaining before this item is complete
simple_schedule AutoOrderItemSimpleSchedule If the item is configured as an automatic rebill and only has a simple single step schedule then details are provided within this object

AutoOrderItemFutureSchedule

Attributes
Name Data Type Description
item_id string Item ID that should rebill
rebill_count integer (int32) The number of times this rebill represents
shipment_dts string (dateTime) Date/time that this item is scheduled to rebill
unit_cost number The unit cost of the item rebilling

AutoOrderItemOption

Attributes
Name Data Type Description
label string(50) Label
value string(1024) Value

AutoOrderItemSimpleSchedule

Attributes
Name Data Type Description
frequency (read only) string Frequency of the rebill if not a fixed schedule
Allowed Values
  • Weekly
  • Biweekly
  • Every...
  • Every 10 Days
  • Every 24 Days
  • Every 28 Days
  • Monthly
  • Every 45 Days
  • Every 2 Months
  • Every 3 Months
  • Every 4 Months
  • Every 5 Months
  • Every 6 Months
  • Yearly
  • Every 4 Weeks
  • Every 6 Weeks
  • Every 8 Weeks
item_id (read only) string Item ID that should rebill
repeat_count integer (int32) The number of times this simple schedule is configured for

BaseResponse

Attributes
Name Data Type Description
error Error Error object if unsuccessful
metadata ResponseMetadata Meta-data about the response such as payload or paging information
success boolean Indicates if API call was successful
warning Warning Warning object if a non-fatal issue or side-effect occurs

Browser

Attributes
Name Data Type Description
device BrowserDevice
os BrowserOS
user_agent BrowserUserAgent

BrowserDevice

Attributes
Name Data Type Description
family string

BrowserOS

Attributes
Name Data Type Description
family string
major string
minor string
patch string
patch_minor string

BrowserUserAgent

Attributes
Name Data Type Description
family string
major string
minor string
patch string

Currency

Attributes
Name Data Type Description
currency_code string Currency code of the localized value
exchange_rate number Exchange rate used to localize
localized number Value localized to the customer
localized_formatted string Value localized and formatted for the customer
value number Value in base currency

Customer

Attributes
Name Data Type Description
activity CustomerActivity activity by this customer
affiliate_oid integer (int32) Affiliate oid
allow_3rd_party_billing boolean Allow 3rd party billing
allow_cod boolean Allow COD
allow_drop_shipping boolean Allow Drop Shipping
allow_purchase_order boolean Allow purchase orders by this customer
allow_quote_request boolean Allow quote request
allow_selection_of_address_type boolean Allow selection of residential or business address type
attachments array of CustomerAttachment Attachments
auto_approve_cod boolean Auto approve COD
auto_approve_purchase_order boolean Auto approve purchase orders by this customer
automatic_merchant_notes string Automatic merchant notes are added to every order placed
billing array of CustomerBilling Billing addresses for this customer
business_notes string(2000) Business notes (internally visible only)
cards array of CustomerCard Credit Cards for this customer
cc_emails array of CustomerEmail Additional emails to CC notification
customer_profile_oid (read only) integer (int32) Customer profile object identifier
dhl_account_number string(20) DHL account number
dhl_duty_account_number string(20) DHL duty account number
do_not_send_mail boolean Do not send mail (null will not update)
edi CustomerEDI EDI settings
email string Email address of this customer profile
exempt_shipping_handling_charge boolean Exempt shipping handling charge
fedex_account_number string(20) FedEx account number
free_shipping boolean This customer always receives free shipping
free_shipping_minimum number If free_shipping is true, this is the minimum subtotal required for free shipping
last_modified_by (read only) string(100) Last modified by
last_modified_dts (read only) string (dateTime) Last modified date
loyalty CustomerLoyalty Loyalty
maximum_item_count integer (int32) Maximum item count
merchant_id (read only) string Merchant ID
minimum_item_count integer (int32) Minimum item count
minimum_subtotal number Minimum subtotal
no_coupons boolean No coupons
no_free_shipping boolean No free shipping regardless of coupons or item level settings
no_realtime_charge boolean No realtime charge
orders array of Order Orders associated with this customer profile
orders_summary CustomerOrdersSummary Summary of orders placed by this customer profile
password string(30) Password (may only be set, never read)
pricing_tiers array of CustomerPricingTier Pricing tiers for this customer
privacy CustomerPrivacy Privacy settings of the customer profile
properties array of CustomerProperty Properties for this customer
qb_class string QuickBooks class to import this customer as
qb_code string QuickBooks name to import this customer as
qb_tax_exemption_reason_code integer (int32) QuickBooks tax exemption reason code
quotes array of Order Quotes associated with this customer profile
quotes_summary CustomerQuotesSummary Summary of the quotes submitted by this customer profile
referral_source string(50) Referral Source
reviewer CustomerReviewer Item reviewer information
sales_rep_code string(10) Sales rep code
send_signup_notification boolean Send signup notification, if true during customer creation, will send a notification.
shipping array of CustomerShipping Shipping addresses for this customer
signup_dts (read only) string Signup date
software_entitlements array of CustomerSoftwareEntitlement Software entitlements owned by this customer
suppress_buysafe boolean Suppress buySAFE (deprecated)
tags array of CustomerTag Tags for this customer
tax_codes CustomerTaxCodes Tax codes used by tax integrations
tax_exempt boolean True if the customer is tax exempt
tax_id string(15) Tax ID
terms string Terms for this customer
track_separately boolean True if the customer should be tracked separately in QuickBooks
unapproved boolean Unapproved
ups_account_number string(20) UPS account number
website_url string(100) Website url

CustomerActivity

Attributes
Name Data Type Description
activities array of Activity
global_unsubscribed boolean
global_unsubscribed_dts string
memberships array of ListSegmentMembership
metrics array of Metric
properties_list array of Property
spam_complaint boolean
spam_complaint_dts string

CustomerAttachment

Attributes
Name Data Type Description
customer_profile_attachment_oid (read only) integer (int32) Attachment identifier
description string Description
file_name (read only) string File name
mime_type (read only) string Mime type
upload_dts (read only) string (dateTime) Upload date/time

CustomerBilling

Attributes
Name Data Type Description
address1 string(50) Address line 1
address2 string(50) Address line 2
city string(32) City
company string(50) Company
country_code string(2) ISO-3166 two letter country code
customer_billing_oid (read only) integer (int32) Customer profile billing object identifier
customer_profile_oid (read only) integer (int32) Customer profile object identifier
day_phone string(25) Day phone
default_billing boolean Default billing
evening_phone string(25) Evening phone
first_name string(30) First name
last_name string(30) Last name
last_used_dts string (dateTime) Last used date
postal_code string(20) Postal code
state_region string(32) State for United States otherwise region or province for other countries
tax_county string(32) Tax County
title string(50) Title

CustomerCard

Attributes
Name Data Type Description
card_expiration_month integer (int32) Card expiration month (1-12)
card_expiration_year integer (int32) Card expiration year (four digit year)
card_number string Card number (masked to the last 4)
card_number_token string Hosted field token for the card number
card_type string Card type
customer_profile_credit_card_id integer (int32) ID of the stored credit card to use
customer_profile_oid (read only) integer (int32) Customer profile object identifier
last_used_dts string (dateTime) Last used date

CustomerEDI

Attributes
Name Data Type Description
channel_partner_oid integer (int32) EDI channel partner this customer profile is associated with
distribution_center_number string The EDI distribution center number associated with this customer profile.
store_number string The EDI store number associated with this customer profile.

CustomerEmail

Attributes
Name Data Type Description
customer_profile_email_oid integer (int32) ID of the email
email string(100) Email
label string(100) Label
receipt_notification boolean CC this email on receipt notifications
refund_notification boolean CC this email on refund notifications
shipment_notification boolean CC this email on shipment notifications

CustomerLoyalty

Attributes
Name Data Type Description
current_points (read only) integer (int32) Current points
internal_gift_certificate GiftCertificate The internal gift certificate that is used to manage cashback points under the hood
internal_gift_certificate_balance (read only) string Loyalty Cashback / Store credit balance (internal gift certificate balance)
internal_gift_certificate_oid (read only) integer (int32) Internal gift certificate oid used to tracking loyalty cashback / store credit.
ledger_entries (read only) array of CustomerLoyaltyLedger Ledger entries
pending_points (read only) integer (int32) Pending Points
redemptions (read only) array of CustomerLoyaltyRedemption Redemptions

CustomerLoyaltyLedger

Attributes
Name Data Type Description
created_by (read only) string Created By
created_dts (read only) string (dateTime) Created date
description (read only) string Description
email (read only) string Email
item_id (read only) string Item Id
item_index (read only) integer (int32) Item Index
ledger_dts (read only) string (dateTime) Ledger date
loyalty_campaign_oid (read only) integer (int32) Loyalty campaign oid
loyalty_ledger_oid (read only) integer (int32) Loyalty ledger oid
loyalty_points (read only) integer (int32) Loyalty points
modified_by (read only) string Modified By
modified_dts (read only) string (dateTime) Modified date
order_id (read only) string Order Id
quantity (read only) integer (int32) Quantity
vesting_dts (read only) string (dateTime) Vesting date

CustomerLoyaltyRedemption

Attributes
Name Data Type Description
coupon_code (read only) string Coupon code
coupon_code_oid (read only) integer (int32) Coupon code OID
coupon_used (read only) boolean Coupon used
description_for_customer (read only) string Description for customer
expiration_dts (read only) string (dateTime) Expiration date
gift_certificate_code (read only) string Gift certificate code
gift_certificate_oid (read only) integer (int32) Gift certificate oid
loyalty_ledger_oid (read only) integer (int32) Loyalty ledger OID
loyalty_points (read only) integer (int32) Loyalty points
loyalty_redemption_oid (read only) integer (int32) Loyalty redemption OID
order_id (read only) string Order id
redemption_dts (read only) string (dateTime) Redemption date
remaining_balance (read only) number Remaining balance

CustomerOrdersSummary

Attributes
Name Data Type Description
first_order_dts (read only) string (dateTime) First order date
last_order_dts (read only) string (dateTime) Last order date
order_count integer (int32) Total number of orders
total number Total amount associated with the orders

CustomerPricingTier

Attributes
Name Data Type Description
name string(50) Name
pricing_tier_oid integer (int32) Pricing Tier Oid

CustomerPrivacy

Attributes
Name Data Type Description
last_update_dts (read only) string (dateTime) Last update date
marketing (read only) boolean The customer has opted in to marketing
preference (read only) boolean The customer has opted in to preference tracking
statistics (read only) boolean The customer has opted in to statistics collection

CustomerProperty

Attributes
Name Data Type Description
customer_profile_property_oid integer (int32) Customer profile property oid
expiration_dts string (dateTime) The date/time that the property expires and is deleted
name string(100) Name
value string(1500) Value

CustomerQuotesSummary

Attributes
Name Data Type Description
first_quote_dts (read only) string (dateTime) First quote date
last_quote_dts (read only) string (dateTime) Last quote date
quote_count integer (int32) Total number of quote
total number Total amount associated with the quotes

CustomerReviewer

Attributes
Name Data Type Description
auto_approve boolean True if reviewes from this customer profile should automatically be approved
average_overall_rating (read only) number Average overall rating of items reviewed
expert boolean True if the customer is an expert
first_review (read only) string (dateTime) First review
last_review (read only) string (dateTime) Last review
location string Location of the reviewer
nickname string Nickname of the reviewer
number_helpful_review_votes (read only) integer (int32) Number of helpful review votes
rank (read only) integer (int32) Rank of this reviewer
reviews_contributed (read only) integer (int32) Number of reviews contributed

CustomerShipping

Attributes
Name Data Type Description
address1 string(50) Address line 1
address2 string(50) Address line 2
city string(32) City
company string(50) Company
country_code string(2) ISO-3166 two letter country code
customer_profile_oid (read only) integer (int32) Customer profile object identifier
customer_shipping_oid (read only) integer (int32) Customer profile shipping object identifier
day_phone string(25) Day phone
default_shipping boolean Default shipping
evening_phone string(25) Evening phone
first_name string(30) First name
last_name string(30) Last name
last_used_dts string (dateTime) Last used date
postal_code string(20) Postal code
state_region string(32) State for United States otherwise region or province for other countries
tax_county string(32) Tax County
title string(50) Title

CustomerSoftwareEntitlement

Attributes
Name Data Type Description
activation_code string(50) Activation Code Associated with the software
activation_dts string (dateTime) Date/time when the activation code was created
customer_software_entitlement_oid (read only) integer (int32) Customer profile software entitlement object identifier
expiration_dts string (dateTime) Date/time when the activation code will expire
purchased_via_item_description (read only) string(512) Item description used to purchase this software.
purchased_via_item_id (read only) string(20) Item ID used to purchase this software.
purchased_via_order_id (read only) string(30) Order ID used to purchase this software.
software_sku string(30) SKU of the software

CustomerTag

Attributes
Name Data Type Description
tag_value string(250) Tag Value

CustomerTaxCodes

Attributes
Name Data Type Description
avalara_customer_code string Avalara customer code
avalara_entity_use_code string Avalara entity use code
sovos_customer_code string Sovos customer code
taxjar_customer_id string TaxJar customer id
taxjar_exemption_type string TaxJar exemption type

Distance

Attributes
Name Data Type Description
uom string Unit of measure
Allowed Values
  • IN
  • CM
value number The distance measured in UOM

Error

Attributes
Name Data Type Description
developer_message string A technical message meant to be read by a developer
error_code string HTTP status code
more_info string Additional information often a link to additional documentation
object_id string Object id that the error is associated with
user_message string An end-user friendly message suitable for display to the customer

ErrorResponse

Attributes
Name Data Type Description
error Error Error object if unsuccessful
metadata ResponseMetadata Meta-data about the response such as payload or paging information
success boolean Indicates if API call was successful
warning Warning Warning object if a non-fatal issue or side-effect occurs

GiftCertificate

Attributes
Name Data Type Description
activated boolean True if this gift certificate is activated and ready to apply to purchases.
code (read only) string The code used by the customer to purchase against this gift certificate.
customer_profile_oid (read only) integer (int32) This is the customer profile oid associated with this internally managed gift certificate.
deleted boolean True if this gift certificate was deleted.
email string(100) Email of the customer associated with this gift certificate.
expiration_dts string (dateTime) Expiration date time.
gift_certificate_oid (read only) integer (int32) Gift certificate oid.
internal (read only) boolean This is an internally managed gift certificate associated with the loyalty cash rewards program.
ledger_entries (read only) array of GiftCertificateLedgerEntry A list of all ledger activity for this gift certificate.
merchant_id string Merchant Id
merchant_note string A list of all ledger activity for this gift certificate.
original_balance (read only) number Original balance of the gift certificate.
reference_order_id (read only) string The order used to purchase this gift certificate. This value is ONLY set during checkout when a certificate is purchased, not when it is used. Any usage is recorded in the ledger
remaining_balance (read only) number The remaining balance on the gift certificate. This is never set directly, but calculated from the ledger. To change the remaining balance, add a ledger entry.

GiftCertificateLedgerEntry

Attributes
Name Data Type Description
amount number The amount of the activity.
description string(50) Description of what this ledger entry is used.
entry_dts string (dateTime) Date time of this ledger activity.
gift_certificate_ledger_oid integer (int32) Gift certificate ledger oid is a primary key for this object, used internally.
gift_certificate_oid integer (int32) Gift certificate oid.
reference_order_id string The order id if this gift certificate was used as part of the payment.

ListSegmentMembership

Attributes
Name Data Type Description
name string
type string
uuid string

Metric

Attributes
Name Data Type Description
all_time number
all_time_formatted string
last_30 number
last_30_formatted string
name string
prior_30 number
prior_30_formatted string
type string

Order

Attributes
Name Data Type Description
affiliates (read only) array of OrderAffiliate Affiliates if any were associated with the order. The first one in the array sent the order and each subsequent affiliate is the recruiter that earns a downline commission.
auto_order (read only) OrderAutoOrder Auto Order. If this is the original order then expansion can be done. If it is a rebill then the record is a small pointer to the auto order and original order records.
billing OrderBilling Billing
buysafe OrderBuysafe buySAFE bond
channel_partner (read only) OrderChannelPartner Channel Partner if one is associated with the order
checkout OrderCheckout Checkout
coupons array of OrderCoupon Coupons
creation_dts (read only) string (dateTime) Date/time that the order was created
currency_code string(3) Currency code that the customer used if different than the merchant's base currency code
Allowed Values
  • ARS
  • AUD
  • BRL
  • CAD
  • CHF
  • COP
  • EUR
  • GBP
  • JPY
  • MXN
  • MYR
  • NOK
  • NZD
  • RUB
  • SEK
  • SGD
  • TRY
  • USD
current_stage string Current stage that the order is in.
Allowed Values
  • Accounts Receivable
  • Pending Clearance
  • Fraud Review
  • Rejected
  • Shipping Department
  • Completed Order
  • Quote Request
  • Quote Sent
  • Least Cost Routing
  • Unknown
  • Pre-ordered
  • Advanced Order Routing
  • Hold
current_stage_histories (read only) array of OrderCurrentStageHistory History of the changes to the current_stage field
customer_profile (read only) Customer Customer profile if one is associated with the order
digital_order OrderDigitalOrder Digital order details
edi OrderEdi EDI related information (only for orders received via EDI channel partner)
exchange_rate number Exchange rate at the time the order was placed if currency code is different than the base currency
fraud_score (read only) OrderFraudScore Fraud score if checked on the order
gift OrderGift Gift giving information
gift_certificate (read only) OrderGiftCertificate Gift certificate used on the order
internal OrderInternal Internal
items array of OrderItem Items
language_iso_code (read only) string(3) Three letter ISO-639 language code used by the customer during the checkout if different than the default language
linked_shipment (read only) OrderLinkedShipment Linked shipment information (CCBill orders only)
marketing OrderMarketing Marketing
merchant_id (read only) string UltraCart merchant ID owning this order
order_id (read only) string Order ID
payment OrderPayment Payment
point_of_sale (read only) OrderPointOfSale If the order was a point of sale order, this this object contains the details of where the transaction took place.
properties array of OrderProperty Properties, available only through update, not through insert due to the nature of how properties are handled internally
quote (read only) OrderQuote Quote
refund_dts (read only) string (dateTime) If the order was refunded, the date/time that the last refund occurred
refund_reason string Refund reason code. This can only be written during a refund operation otherwise this field is read only.
reject_dts (read only) string (dateTime) If the order was rejected, the date/time that the rejection occurred
reject_reason string Reject reason code. This can only be written during a reject operation otherwise this field is read only.
salesforce (read only) OrderSalesforce Salesforce.com identifiers
shipping OrderShipping Shipping
summary OrderSummary Summary
Tags array of OrderTag tags, available only through update, not through insert due to the nature of how tags are handled internally
taxes OrderTaxes Taxes
utms (read only) array of OrderUtm UTM clicks. The zero index is the most recent (last) UTM click

OrderAffiliate

This object is read only. Changing the affiliate association should be with via the user interface.
Attributes
Name Data Type Description
affiliate_oid integer (int32) Affiliate ID
ledger_entries array of OrderAffiliateLedger Ledger entries associated with all the commissions earned on this order
sub_id string Sub identifier provided by the affiliate on the click that generated this order

OrderAffiliateLedger

This object is read only.
Attributes
Name Data Type Description
assigned_by_user string UltraCart user name that assigned this commission if manually assigned
item_id string Item ID that this ledger record is associated with
tier_number integer (int32) Tier number of this affiliate in the commission calculation
transaction_amount number Amount of the transaction
transaction_amount_paid number The amount that has been paid so far on the transaction
transaction_dts string (dateTime) The date/time that the affiliate ledger was generated for the transaction
transaction_memo string Details of the transaction suitable for display to the affiliate
transaction_percentage number The percentage earned on the transaction
transaction_state string The state of the transaction
Allowed Values
  • Pending
  • Posted
  • Approved
  • Paid
  • Rejected
  • Partially Paid

OrderAutoOrder

Attributes
Name Data Type Description
auto_order_code (read only) string Unique code assigned to this auto order
auto_order_oid (read only) integer (int32) Auto order object identifier
cancel_after_next_x_orders integer (int32) Cancel this auto order after X additional rebills
cancel_downgrade (read only) boolean True if the auto order was canceled because the customer purchased a downgrade item
cancel_reason string The reason this auto order was canceled by either merchant or customer
cancel_upgrade (read only) boolean True if the auto order was canceled because the customer purchased an upgrade item
canceled_by_user string The user that canceled the auto order
canceled_dts string (dateTime) The date/time that the auto order was canceled
completed (read only) boolean True if the auto order ran successfully to completion
credit_card_attempt integer (int32) The number of credit card attempts that have taken place
disabled_dts (read only) string (dateTime) The date/time the auto order was disabled due to failed rebills
enabled boolean True if this auto order is enabled
failure_reason (read only) string The reason this auto order failed during the last rebill attempt
items array of AutoOrderItem The items that are setup to rebill
next_attempt string (dateTime) The next time that the auto order will be attempted for processing
original_order_id (read only) string The original order id that this auto order is associated with.
override_affiliate_id integer (int32) Override the affiliate id given credit for rebills of this auto order
rebill_orders (read only) array of Order Rebill orders that have taken place on this auto order
rotating_transaction_gateway_code string The RTG code associated with this order for future rebills
status (read only) string The status of the auto order
Allowed Values
  • active
  • canceled
  • disabled

OrderBilling

Attributes
Name Data Type Description
address1 string(50) Address line 1
address2 string(50) Address line 2
cc_emails array of string CC emails. Multiple allowed, but total length of all emails can not exceed 100 characters.
cell_phone string(25) Cell phone
cell_phone_e164 (read only) string(25) Cell phone (E164 format)
city string(32) City
company string(50) Company
country_code string(2) ISO-3166 two letter country code
day_phone string(25) Day time phone
day_phone_e164 (read only) string(25) Day time phone (E164 format)
email string(100) Email
evening_phone string(25) Evening phone
evening_phone_e164 (read only) string(25) Evening phone (E164 format)
first_name string(30) First name
last_name string(30) Last name
postal_code string(20) Postal code
state_region string(32) State for United States otherwise region or province for other countries
title string(50) Title

OrderBuysafe

Attributes
Name Data Type Description
buysafe_bond_available (read only) boolean True if a buySAFE bond was available for purchase on this order
buysafe_bond_cost (read only) Currency Cost of the buySAFE bond
buysafe_bond_free (read only) boolean True if the buySAFE bond was free for this order
buysafe_bond_refunded (read only) Currency Amount of the buySAFE bond that was refunded
buysafe_bond_wanted boolean True if the buySAFE bond was wanted by the customer
buysafe_shopping_cart_id (read only) string Shopping cart ID associated with the buySAFE bond

OrderByTokenQuery

Attributes
Name Data Type Description
order_token string Order Token

OrderChannelPartner

This object is read-only except for inserts.
Attributes
Name Data Type Description
auto_approve_purchase_order boolean If true, any purchase order submitted is automatically approved
channel_partner_code string The code of the channel partner
channel_partner_data string Additional data provided by the channel partner, read-only
channel_partner_oid integer (int32) Channel partner object identifier, read-only and available on existing channel orders only.
channel_partner_order_id string(50) The order ID assigned by the channel partner for this order.
ignore_invalid_shipping_method boolean Set to true to ignore invalid shipping method being specified. Only applicable on inserting orders.
no_realtime_payment_processing boolean Indicates this order should be placed in Account Receivable for later payment processing
skip_payment_processing boolean Indicates this order was already paid for via a channel purchase and no payment collection should be attempted
store_completed boolean Instructs UltraCart to skip shipping department and mark this order as fully complete. This flag defaults to true. Set this flag to false to shipped product for this order.
store_if_payment_declines boolean If true, any failed payment will place the order in Accounts Receivable rather than rejecting it.
treat_warnings_as_errors boolean Any warnings are raised as errors and halt the import of the order

OrderCheckout

Attributes
Name Data Type Description
browser (read only) Browser Parsed user agent string into components
comments string Comments from the customer. Rarely used on the single page checkout.
custom_field1 string(50) Custom field 1
custom_field10 string(200) Custom field 10
custom_field2 string(50) Custom field 2
custom_field3 string(50) Custom field 3
custom_field4 string(50) Custom field 4
custom_field5 string(75) Custom field 5
custom_field6 string(50) Custom field 6
custom_field7 string(50) Custom field 7
custom_field8 string(200) Custom field 8
custom_field9 string(200) Custom field 9
customer_ip_address (read only) string IP address of the customer when placing the order
screen_branding_theme_code string(10) Screen branding theme code associated with the order (legacy checkout)
screen_size (read only) string Screen size small, medium or large
storefront_host_name string StoreFront host name associated with the order
upsell_path_code (read only) string Upsell path code assigned during the checkout that the customer went through

OrderCoupon

Attributes
Name Data Type Description
accounting_code (read only) string QuickBooks accounting code for this coupon
automatically_applied (read only) boolean Whether or not the coupon was automatically applied to the order
base_coupon_code string(20) Coupon code configured by the merchant. Will differ if the customer used a one time coupon code generated off this base coupon
coupon_code string(20) Coupon code entered by the customer
hdie_from_customer (read only) boolean True if this coupon is hide from the customer

OrderCurrentStageHistory

Attributes
Name Data Type Description
after_stage string New stage that the order is in.
Allowed Values
  • Accounts Receivable
  • Pending Clearance
  • Fraud Review
  • Rejected
  • Shipping Department
  • Completed Order
  • Quote Request
  • Quote Sent
  • Least Cost Routing
  • Unknown
  • Pre-ordered
  • Advanced Order Routing
  • Hold
before_stage string Previous stage that the order was in.
Allowed Values
  • Accounts Receivable
  • Pending Clearance
  • Fraud Review
  • Rejected
  • Shipping Department
  • Completed Order
  • Quote Request
  • Quote Sent
  • Least Cost Routing
  • Unknown
  • Pre-ordered
  • Advanced Order Routing
  • Hold
transition_dts (read only) string (dateTime) Date/time that the stage transitioned

OrderDigitalItem

Attributes
Name Data Type Description
file_size (read only) integer (int64) File size
last_download (read only) string (dateTime) Last download
last_download_ip_address (read only) string IP address that performed the last download
original_filename (read only) string Original file name
product_code (read only) string Item id associated with this item
product_description (read only) string Item description associated with this item
remaining_downloads integer (int32) Remaining number of downloads
url (read only) string URL that the customer can click to download the specific digital item

OrderDigitalOrder

Attributes
Name Data Type Description
creation_dts (read only) string (dateTime) Date/time that the digital order was created
expiration_dts string (dateTime) Expiration date/time of the digital order
items array of OrderDigitalItem Digital items associated with the digital order
url (read only) string URL where the customer can go to and download their digital order content
url_id (read only) string URL ID is a unique code that is part of the URLs

OrderEdi

Attributes
Name Data Type Description
bill_to_edi_code string Billing address identification code from the EDI order. Typically DUNS or DUNS+4
edi_department string Department number associated with this EDI order
edi_internal_vendor_number string(50) Internal vendor number associated with this EDI order
ship_to_edi_code string Shipping address identification code from the EDI order. Typically DUNS or DUNS+4

OrderEdiDocument

Attributes
Name Data Type Description
direction string Direction the document flowed
Allowed Values
  • inbound
  • outbound
doc_dts string (dateTime) Date/time the document was created/received
document string
document_type_description string
document_type_number integer (int32)
external_id string
functional_acknowledgement string
functional_acknowledgement_dts string
functional_acknowledgement_pending boolean
group_control_number integer (int32)
internal_id string
merchant_id string
order_id string
test_mode boolean

OrderEdiDocumentsResponse

Attributes
Name Data Type Description
ediDocuments array of OrderEdiDocument edi_documents
error Error Error object if unsuccessful
metadata ResponseMetadata Meta-data about the response such as payload or paging information
success boolean Indicates if API call was successful
warning Warning Warning object if a non-fatal issue or side-effect occurs

OrderFormat

Attributes
Name Data Type Description
context string The context to generate the order view for.
Allowed Values
  • unknown
  • receipt
  • shipment
  • refund
  • quote-request
  • quote
dont_link_email_to_search boolean True to not link the email address to the order search
email_as_link boolean True to make the email address a clickable mailto link
filter_distribution_center_oid integer (int32) Specify a distribution center oid to filter the items displayed to that particular distribution center.
filter_to_items_in_container_oid integer (int32) The container oid to filter items to.
format string The desired format.
Allowed Values
  • text
  • div
  • table
  • email
hide_bill_to_address boolean True to ide the bill to address
hide_price_information boolean True to hide price information
link_file_attachments boolean True to link file attachments for download
show_contact_info boolean True to show contact information
show_in_merchant_currency boolean True to show the order in the merchant currency
show_internal_information boolean True to show internal information about the order
show_merchant_notes boolean True to show merchant notes
show_non_sensitive_payment_info boolean True to show non-sensitive payment information
show_payment_info boolean True to show payment information
translate boolean True to translate the order into the native language of the customer

OrderFormatResponse

Attributes
Name Data Type Description
css_links array of string The URLs to any stylesheets that need to be included to properly view the markup.
formatted_result string The formatted result of the order. This will be HTML or text depending upon the requested format.

OrderFraudScore

The fraud score for the order. This entire object is read only and the details are provided to help you make a more educated decision on whether the order should be approved or rejected if the score is above your threshold.
Attributes
Name Data Type Description
anonymous_proxy boolean True if the IP address is a known anonymous proxy server
bin_match string Whether the BIN (first six digits) matched the country
Allowed Values
  • NA
  • No
  • NotFound
  • Yes
carder_email boolean True if the email address belongs to a known credit card fraudster
country_code string Country code
country_match boolean Country code matches BIN country
customer_phone_in_billing_location string Whether the customer's phone number is located in the area of the billing address
distance_km integer (int32) Distance in kilometers between the IP address and the BIN
free_email boolean True if the email address is for a free service like gmail.com
high_risk_country boolean True if the customer is in a high risk country known for internet fraud
ip_city string City associated with the IP address
ip_isp string ISP that owns the IP address
ip_latitude string Approximate latitude associated with the IP address
ip_longitude string Approximate longitude associated with the IP address
ip_org string Organization that owns the IP address
ip_region string State/region associated with the IP address
proxy_score number Likelihood of the IP address being a proxy server
score number Overall score. This is the score that is compared to see if the order is rejected or held for review by the fraud filter rules.
ship_forwarder boolean True if the address is a known ship forwarding company
spam_score number Likelihood of the email address being associated with a spammer
transparent_proxy boolean True if the IP address that placed the order is a transparent proxy server

OrderGift

Attributes
Name Data Type Description
gift boolean True if the order is a gift
gift_charge Currency Charge associated with making this order a gift
gift_charge_accounting_code (read only) string QuickBooks code for the gift charge
gift_charge_refunded Currency Amount refunded of the gift charge (read only except refund operation)
gift_email string(100) Email address of the gift recipient
gift_message string(10000) Message to the gift recipient
gift_wrap_accounting_code (read only) string QuickBooks code for the gift wrap charge
gift_wrap_cost Currency Cost of the gift wrap the customer selected
gift_wrap_refunded Currency Amount refunded of the gift wrap (read only except refund operation)
gift_wrap_title string(30) Title of the gift wrap that the customer wants used

OrderGiftCertificate

Attributes
Name Data Type Description
gift_certificate_amount (read only) Currency Gift certificate amount applied to the order
gift_certificate_code (read only) string Gift certificate code used on the order
gift_certificate_oid (read only) integer (int32) Gift certificate object identifier

OrderInternal

Attributes
Name Data Type Description
exported_to_accounting boolean True if the order has been exported to QuickBooks. If QuickBooks is not configured, then this will already be true
merchant_notes string Merchant notes. Full notes in non-transactional mode. Just used to write a new merchant note when transaction merchant notes enabled.
placed_by_user (read only) string If placed via the BEOE, this is the user that placed the order
refund_by_user (read only) string User that issued the refund
sales_rep_code string(10) Sales rep code associated with the order
transactional_merchant_notes (read only) array of OrderTransactionalMerchantNote Transactional merchant notes

OrderInvoiceResponse

Attributes
Name Data Type Description
error Error Error object if unsuccessful
metadata ResponseMetadata Meta-data about the response such as payload or paging information
pdfBase64 string pdf_base64
success boolean Indicates if API call was successful
warning Warning Warning object if a non-fatal issue or side-effect occurs

OrderItem

Attributes
Name Data Type Description
accounting_code (read only) string QuickBooks code
activation_codes array of string Activation codes assigned to this item
actual_cogs Currency Actual COGS of the item used by the cost analysis report
arbitrary_unit_cost Currency Arbitrary unit cost, used only during inserts for overriding the unit cost of an item
auto_order_last_rebill_dts string (dateTime) Date/time of the last rebill, used only during order insert to help project future rebills
auto_order_schedule string Auto order schedule, used only during inserts supplying the recurring schedule
barcode (read only) string Barcode
barcode_gtin12 (read only) string(12) Barcode - GTIN 12
barcode_gtin14 (read only) string(14) Barcode - GTIN 14
barcode_upc11 (read only) string(11) Barcode - UPC 11
barcode_upc12 (read only) string(12) Barcode - UPC 12
channel_partner_item_id string(30) Channel partner item id if this order came through a channel partner and the channel partner item id was mapped to an internal item id
cogs (read only) number Cost of goods sold
component_unit_value (read only) number Value of the kit component item
cost Currency Cost
country_code_of_origin (read only) string(2) Country of origin (ISO-3166 two letter code)
customs_description (read only) string Customs description
description string(2000) Description
discount (read only) Currency Discount
discount_quantity (read only) number Discount quantity
discount_shipping_weight (read only) Weight Discount shipping weight
distribution_center_code string Distribution center code responsible for shipping this item
edi OrderItemEdi EDI related item information
exclude_coupon boolean True if this item is excluded from coupons
free_shipping boolean True if the item receives free shipping
hazmat boolean Hazardous materials indicator
height Distance Height
item_index integer (int32) Index of the item on the order (one based index)
item_reference_oid (read only) integer (int32) Item reference object identifier used to linked to auto order item record
kit boolean True if this item is a kit
kit_component boolean True if this item is a kit component
length Distance Length
manufacturer_sku (read only) string Manufacturer SKU
max_days_time_in_transit integer (int32) Maximum days that the item can be in transit before spoilage (perishable products)
merchant_item_id string(20) Item ID
mix_and_match_group_name string Mix and match group name
mix_and_match_group_oid integer (int32) Mix and match group object identifier
no_shipping_discount boolean True if this item is excluded from shipping discounts
options array of OrderItemOption Options
packed_by_user (read only) string Packed by user
parent_item_index integer (int32) If this item is a kit component, this is the item index of the parent item (kit)
parent_merchant_item_id string(20) If this item is a kit component, this is the item id of the parent item (kit)
perishable_class string(50) Perishable class of the item
pricing_tier_name string Pricing tier that granted the particular price for this item if the customer profile had pricing tiers assigned
properties array of OrderItemProperty Properties
quantity number Quantity
quantity_refunded number Quantity refunded on this item (read only except refund operation)
quickbooks_class string(31) QuickBooks class
refund_reason string Refund reason code. This can only be written during a refund operation otherwise this field is read only.
return_reason string Return reason code. This can only be written during a refund operation otherwise this field is read only.
ship_separately boolean True if this item ships in a separate box
shipped_by_user (read only) string Shipped by user
shipped_dts string (dateTime) Date/time that this item was marked shipped
shipping_status string Shipping status for this item. This is the replacement for the old order level shipping status.
special_product_type string Special product type (USPS Media Mail)
Allowed Values
  • Book or Software
  • Music
  • Editorial
tags array of OrderItemTag Tags
tax_free boolean True if the item is tax free
tax_product_type string Type of product for tax purposes (self or UltraCart Managed taxes)
Allowed Values
  • digital
  • physical
  • service
taxable_cost Currency The taxable cost of the item. Typically the same as the cost
total_cost_with_discount (read only) Currency Total cost with discount
total_refunded Currency Total refunded on this item (read only except refund operation)
transmitted_to_distribution_center_dts string (dateTime) Date/time that this item was transmitted to the distribution center
unit_cost_with_discount (read only) Currency Unit cost with discount
upsell boolean True if this item was added to the order as part of an upsell
weight Weight Weight
width Distance Width

OrderItemEdi

This object is read only.
Attributes
Name Data Type Description
identifications (read only) array of OrderItemEdiIdentification Identification information receives on the EDI purchase order
lots (read only) array of OrderItemEdiLot Lot information

OrderItemEdiIdentification

This object is read only.
Attributes
Name Data Type Description
identification string Identification value
quantity integer (int32) Quantity associated with this identifier

OrderItemEdiLot

This object is read only.
Attributes
Name Data Type Description
lot_expiration string (dateTime) Log expiration
lot_number string Lot number
lot_quantity integer (int32) Lot quantity

OrderItemOption

Attributes
Name Data Type Description
additional_dimension_application string How the additional dimensions are applied to the item.
Allowed Values
  • none
  • set item to
  • add item
cost_change Currency The amount that this option changes the cost
file_attachment (read only) OrderItemOptionFileAttachment File attachment if option_type is file and attachment has not expired.
height Distance If additional_dimension_application != none
Height
hidden boolean True if this option is hidden from display on the order
label string(50) Label
length Distance If additional_dimension_application != none
Length
one_time_fee boolean True if the cost associated with this option is a one time fee or multiplied by the quantity of the item
value string(1024) Value
weight_change Weight The amount that this option changes the weight
width Distance If additional_dimension_application != none
Width

OrderItemOptionFileAttachment

This object is read only
Attributes
Name Data Type Description
expiration_dts string (dateTime) Expiration date/time
file_name string File name
mime_type string Mime type
size integer (int32) Size

OrderItemProperty

Attributes
Name Data Type Description
display boolean True if this property is displayed to the customer
expiration_dts string (dateTime) The date/time that the property expires and is deleted
name string(100) Name
value string(3800) Value

OrderItemTag

Attributes
Name Data Type Description
tag_value string(100) Tag Value

OrderLinkedShipment

This object is read only.
Attributes
Name Data Type Description
has_linked_shipment boolean True if this order has child linked shipments
linked_shipment boolean True if this order is linked to another parent order
linked_shipment_channel_partner_order_ids array of string If has_linked_shipment=true
The child linked shipment channel partner order ids
linked_shipment_order_ids array of string If has_linked_shipment=true
The child linked shipment order ids
linked_shipment_to_order_id string If linked_shipment=true
The parent order id that this one is linked to

OrderMarketing

Attributes
Name Data Type Description
advertising_source string(50) Advertising source
cell_phone_opt_in boolean True if the customer has opted into SMS marketing
mailing_list boolean True if the customer has opted into mailing list subscription
referral_code string(30) Referral code

OrderPackingSlipResponse

Attributes
Name Data Type Description
error Error Error object if unsuccessful
metadata ResponseMetadata Meta-data about the response such as payload or paging information
pdfBase64 string pdf_base64
success boolean Indicates if API call was successful
warning Warning Warning object if a non-fatal issue or side-effect occurs

OrderPayment

Attributes
Name Data Type Description
check OrderPaymentCheck If payment_method=Check
Check payment information
credit_card OrderPaymentCreditCard If payment_method=Credit Card
Credit card payment information
echeck OrderPaymentECheck If payment_method=eCheck
E-Check payment information
health_benefit_card OrderPaymentHealthBenefitCard Health benefit card
hold_for_fraud_review (read only) boolean True if order has been held for fraud review
insurance OrderPaymentInsurance If payment_method=Insurance
Insurance information
payment_dts string (dateTime) Date/time that the payment was successfully processed, for new orders, this field is only considered if channel_partner.skip_payment_processing is true
payment_method string Payment method
Allowed Values
  • Affirm
  • Amazon
  • Amazon Pay
  • Amazon SC
  • Cash
  • Check
  • COD
  • Credit Card
  • eBay
  • eCheck
  • Google Shopping
  • Insurance
  • Link
  • LoanHero
  • Money Order
  • PayPal
  • Purchase Order
  • Quote Request
  • Unknown
  • Wire Transfer
  • Walmart
  • Shop.com
  • Sezzle
  • Venmo
  • Apple Pay
  • Google Pay
  • Health Benefit Card
payment_method_accounting_code (read only) string Payment method QuickBooks code
payment_method_deposit_to_account (read only) string Payment method QuickBooks deposit account
payment_status (read only) string Payment status
Allowed Values
  • Unprocessed
  • Authorized
  • Capture Failed
  • Processed
  • Declined
  • Voided
  • Refunded
  • Skipped
paypal (read only) OrderPaymentPayPal PayPal details if the payment was vaulted.
purchase_order OrderPaymentPurchaseOrder If payment_method=Purchase Order
Purchase order information
rotating_transaction_gateway_code (read only) string Rotating transaction gateway code used to process this order
surcharge (read only) Currency Surcharge amount calculated from surcharge_transaction_fee and surcharge_transaction_percentage
surcharge_accounting_code (read only) string Surcharge accounting code
surcharge_transaction_fee number Surcharge transaction fee
surcharge_transaction_percentage number Surcharge transaction percentage
test_order (read only) boolean True if this is a test order
transactions (read only) array of OrderPaymentTransaction Transactions associated with processing this payment

OrderPaymentCheck

Attributes
Name Data Type Description
check_number string Check number

OrderPaymentCreditCard

Attributes
Name Data Type Description
card_auth_ticket (read only) string Card authorization ticket
card_authorization_amount (read only) number Card authorization amount
card_authorization_dts (read only) string (dateTime) Card authorization date/time
card_authorization_reference_number (read only) string Card authorization reference number
card_expiration_month integer (int32) Card expiration month (1-12)
card_expiration_year integer (int32) Card expiration year (Four digit year)
card_number (read only) string Card number (masked to last 4)
card_number_token string Card number token from hosted fields used to update the card number
card_number_truncated (read only) boolean True if the card has been truncated
card_type string Card type
Allowed Values
  • AMEX
  • Diners Club
  • Discover
  • JCB
  • MasterCard
  • VISA
card_verification_number_token string Card verification number token from hosted fields, only for import/insert of new orders, completely ignored for updates, and always null/empty for queries
dual_vaulted (read only) OrderPaymentCreditCardDualVaulted Details on the dual vaulted card that is also stored at the payment processor for future reuse

OrderPaymentCreditCardDualVaulted

Attributes
Name Data Type Description
gateway_name string
properties array of OrderPaymentCreditCardDualVaultedProperty
rotating_transaction_gateway_code string

OrderPaymentCreditCardDualVaultedProperty

Attributes
Name Data Type Description
name string
value string

OrderPaymentECheck

Attributes
Name Data Type Description
bank_aba_code string(9) Bank routing code
bank_account_name string(50) Bank account name
bank_account_number string(50) Bank account number (masked to last 4)
bank_account_type string Bank account type
Allowed Values
  • Checking
  • Savings
bank_name string(50) Bank name
bank_owner_type string Bank owner type
Allowed Values
  • Personal
  • Business
customer_tax_id string(9) Customer tax id (masked to last 4)
drivers_license_dob string(10) Driver license date of birth
drivers_license_number string(50) Driver license number (masked to last 4)
drivers_license_state string(2) Driver license state

OrderPaymentHealthBenefitCard

Attributes
Name Data Type Description
health_benefit_card_expiration_month integer (int32) Health benefit card expiration month (1-12)
health_benefit_card_expiration_year integer (int32) Health benefit card expiration year (Four digit year)
health_benefit_card_number (read only) string Health benefit card number (masked to last 4)
health_benefit_card_number_token string Health benefit card number token from hosted fields used to update the health benefit card number
health_benefit_card_number_truncated (read only) boolean True if the health benefit card has been truncated
health_benefit_card_verification_number_token string Health benefit card verification number token from hosted fields, only for import/insert of new orders, completely ignored for updates, and always null/empty for queries

OrderPaymentInsurance

Attributes
Name Data Type Description
application_id string application id
claim_id string claim id
insurance_type string insurance type
refund_claim_id string refund claim id

OrderPaymentPayPal

Attributes
Name Data Type Description
customer_id (read only) string PayPal Customer ID
vault_id (read only) string PayPal Vault ID

OrderPaymentPurchaseOrder

Attributes
Name Data Type Description
purchase_order_number string Purchase order number

OrderPaymentTransaction

This object is read only.
Attributes
Name Data Type Description
details array of OrderPaymentTransactionDetail Details
successful boolean True if the transaction was successful
transaction_gateway string Transaction gateway
transaction_id integer (int32) Transaction ID
transaction_timestamp string (dateTime) Transaction date/time

OrderPaymentTransactionDetail

This object is read only.
Attributes
Name Data Type Description
name string Name
type string Type
value string Value

OrderPointOfSale

Attributes
Name Data Type Description
location (read only) PointOfSaleLocation The location that the point of sale transaction took place at.
reader (read only) PointOfSaleReader The card reader that the point of sale transaction took place at if a credit card was used.
register (read only) PointOfSaleRegister The register that the point of sale transaction took place at.

OrderProcessPaymentRequest

Attributes
Name Data Type Description
amount number Specific amount to bill (optional). If not specified the total of the order is billed.
card_verification_number_token string Card verification number token from hosted fields used during credit card transaction processing (optional)

OrderProcessPaymentResponse

Attributes
Name Data Type Description
error Error Error object if unsuccessful
metadata ResponseMetadata Meta-data about the response such as payload or paging information
payment_transaction (read only) OrderPaymentTransaction Transaction details (for credit card transaction)
success boolean Indicates if API call was successful
warning Warning Warning object if a non-fatal issue or side-effect occurs

OrderProperty

Attributes
Name Data Type Description
display boolean True if this property is displayed to the customer
expiration_dts string (dateTime) The date/time that the property expires and is deleted
name string(100) Name
value string(1500) Value

OrderQuery

Attributes
Name Data Type Description
cc_email string(100) CC Email
channel_partner_code string The code of the channel partner
channel_partner_order_id string The order ID assigned by the channel partner for this order
city string(32) City
company string(50) Company
country_code string(2) ISO-3166 two letter country code
creation_date_begin string (dateTime) Date/time that the order was created
creation_date_end string (dateTime) Date/time that the order was created
current_stage string Current stage that the order is in.
Allowed Values
  • Accounts Receivable
  • Pending Clearance
  • Fraud Review
  • Rejected
  • Shipping Department
  • Completed Order
  • Quote Request
  • Quote Sent
  • Least Cost Routing
  • Unknown
custom_field_1 string Custom field 1
custom_field_10 string Custom field 10
custom_field_2 string Custom field 2
custom_field_3 string Custom field 3
custom_field_4 string Custom field 4
custom_field_5 string Custom field 5
custom_field_6 string Custom field 6
custom_field_7 string Custom field 7
custom_field_8 string Custom field 8
custom_field_9 string Custom field 9
customer_profile_oid integer (int32) The customer profile to find associated orders for
email string(100) Email
first_name string(30) First name
item_id string Item ID
last_name string(30) Last name
order_id string Order ID
payment_date_begin string (dateTime) Date/time that the order was successfully processed
payment_date_end string (dateTime) Date/time that the order was successfully processed
payment_method string Payment method
Allowed Values
  • Affirm
  • Amazon
  • Amazon SC
  • Cash
  • Check
  • COD
  • Credit Card
  • eCheck
  • LoanHero
  • Money Order
  • PayPal
  • Purchase Order
  • Quote Request
  • Unknown
  • Wire Transfer
  • Venmo
  • Apple Pay
  • Google Pay
phone string(25) Phone
postal_code string(20) Postal code
purchase_order_number string Purchase order number
query_target string Query Target
Allowed Values
  • origin
  • cache
refund_date_begin string (dateTime) Date/time that the order was refunded
refund_date_end string (dateTime) Date/time that the order was refunded
rma string(30) RMA number
screen_branding_theme_code string(10) Screen branding theme code associated with the order (legacy checkout)
shipment_date_begin string (dateTime) Date/time that the order was shipped
shipment_date_end string (dateTime) Date/time that the order was shipped
shipped_on_date_begin string (dateTime) Date/time that the order should ship on
shipped_on_date_end string (dateTime) Date/time that the order should ship on
state_region string(32) State for United States otherwise region or province for other countries
storefront_host_name string StoreFront host name associated with the order
total number Total

OrderQueryBatch

Attributes
Name Data Type Description
order_ids array of string Order IDs
query_target string Query Target
Allowed Values
  • origin
  • cache

OrderQuote

This object is read only.
Attributes
Name Data Type Description
quote_expiration_dts string (dateTime) Expiration of quote at date/time
quoted_by string Quoted by user
quoted_dts string (dateTime) Quoted on date/time

OrderReason

Attributes
Name Data Type Description
default_reason boolean Default reason
description string Reason description. This is the friendly description of the reason that should be displayed to the user.
value string Reason value. This is what should be submitted with a refund operation.

OrderRefundableResponse

Attributes
Name Data Type Description
error Error Error object if unsuccessful
item_level_refund_reason_required boolean True if the item level refund reason is required
item_level_refund_reasons array of OrderReason Reason codes available at the item level.
item_level_return_reasons array of OrderReason Return codes available at the item level.
manual_because_multiple_charges boolean If true, this refund will have to be manually done because of additional charges with the virtual terminal were made
metadata ResponseMetadata Meta-data about the response such as payload or paging information
order_level_refund_reason_required boolean True if the order level refund reason is required
order_level_refund_reasons array of OrderReason Reason codes available at the order level.
order_level_reject_reason_required boolean True if the order level reject reason is required
order_level_reject_reasons array of OrderReason Reject codes available at the order level.
refundable boolean Whether the order is refundable or not. Null should be interpreted as false.
success boolean Indicates if API call was successful
warning Warning Warning object if a non-fatal issue or side-effect occurs

OrderReplacement

Attributes
Name Data Type Description
additional_merchant_notes_new_order string Additional merchant notes to append to the new order
additional_merchant_notes_original_order string Additional merchant notes to append to the original order
custom_field1 string(50) Custom field 1
custom_field2 string(50) Custom field 2
custom_field3 string(50) Custom field 3
custom_field4 string(50) Custom field 4
custom_field5 string(75) Custom field 5
custom_field6 string(50) Custom field 6
custom_field7 string(50) Custom field 7
free boolean Set to true if this replacement shipment should be free for the customer.
immediate_charge boolean Set to true if you want to immediately charge the payment on this order, otherwise it will go to Accounts Receivable.
items array of OrderReplacementItem Items to include in the replacement order
original_order_id string Original order id
shipping_method string Shipping method to use. If not specified or invalid then least cost shipping will take place.
skip_payment boolean Set to true if you want to skip the payment as if it was successful.

OrderReplacementItem

Attributes
Name Data Type Description
arbitrary_unit_cost number Cost to charge the customer if specified. If not specified then the default item cost is used.
merchant_item_id string(20) Item ID
quantity number Quantity

OrderReplacementResponse

Attributes
Name Data Type Description
chargeSuccessful boolean
errorMessage string
feedback string
free boolean
orderId string
successful boolean

OrderResponse

Attributes
Name Data Type Description
error Error Error object if unsuccessful
metadata ResponseMetadata Meta-data about the response such as payload or paging information
order Order Order
success boolean Indicates if API call was successful
warning Warning Warning object if a non-fatal issue or side-effect occurs

OrderSalesforce

This object is read only
Attributes
Name Data Type Description
salesforce_opportunity_id string Salesforce.com opportunity id

OrderShipping

Attributes
Name Data Type Description
address1 string(50) Address line 1
address2 string(50) Address line 2
city string(32) City
company string(50) Company
country_code string(2) ISO-3166 two letter country code
day_phone string(25) Day time phone
day_phone_e164 (read only) string(25) Day time phone (E164 format)
delivery_date string (dateTime) Date the customer is requesting delivery on. Typically used for perishable product delivery.
evening_phone string(25) Evening phone
evening_phone_e164 (read only) string(25) Evening phone (E164 format)
first_name string(30) First name
last_name string(30) Last name
least_cost_route boolean If true, instructs UltraCart to apply the cheapest shipping method to this order. Used only for channel partner order inserts.
least_cost_route_shipping_methods array of string List of shipping methods to consider if least_code_route is true. Used only for channel parter order inserts.
lift_gate boolean Lift gate requested (LTL shipping methods only)
pickup_dts (read only) string (dateTime) Date/time the order should be picked up locally.
postal_code string(20) Postal code
rma string(30) RMA number
ship_on_date string (dateTime) Date the customer is requesting that the order ship on. Typically used for perishable product delivery.
ship_to_residential boolean True if the shipping address is residential. Effects the methods that are available to the customer as well as the price of the shipping method.
shipping_3rd_party_account_number string(20) Shipping 3rd party account number
shipping_date (read only) string (dateTime) Date/time the order shipped on. This date is set once the first shipment is sent to the customer.
shipping_department_status string(30) Shipping department status
shipping_method string Shipping method
shipping_method_accounting_code (read only) string Shipping method accounting code
special_instructions string Special instructions from the customer regarding shipping
state_region string(32) State
title string(50) Title
tracking_number_details (read only) array of OrderTrackingNumberDetails Tracking number details
tracking_numbers array of string Tracking numbers
weight (read only) Weight Total weight of the items on the order

OrdersResponse

Attributes
Name Data Type Description
error Error Error object if unsuccessful
metadata ResponseMetadata Meta-data about the response such as payload or paging information
orders array of Order orders
success boolean Indicates if API call was successful
warning Warning Warning object if a non-fatal issue or side-effect occurs

OrderSummary

Attributes
Name Data Type Description
actual_fulfillment (read only) Currency Actual amount of the fulfillment cost
actual_other_cost (read only) Currency Actual other cost
actual_payment_processing (read only) Currency Actual amount of the payment processing cost
actual_profit (read only) Currency Actual profit
actual_profit_analyzed (read only) boolean Actual profit has been analyzed
actual_profit_review (read only) boolean Actual profit needs review
actual_shipping (read only) Currency Actual amount of the shipping cost
arbitrary_shipping_handling_total Currency Arbitrary shipping handling total, this is meaningless for updating an order. For inserting a new order, this will override any internal shipping and handling totals and should only be used for orders completed outside the system. This will probably only ever be needed when submitting arbitrary taxes AND shipping is taxed.
health_benefit_card_amount (read only) Currency Health benefit card amount used
health_benefit_card_refunded (read only) Currency Health benefit card refunded
internal_gift_certificate_amount (read only) Currency Internal gift certificate amount used (store credit)
internal_gift_certificate_refunded (read only) Currency Internal gift certificate refunded (store credit)
other_refunded (read only) Currency Other refunded
shipping_handling_refunded Currency Shipping/handling refunded (read only except refund operation)
shipping_handling_total Currency Shipping/handling total
shipping_handling_total_discount (read only) Currency Shipping/handling total discount
subtotal (read only) Currency Subtotal
subtotal_discount (read only) Currency Subtotal discount
subtotal_discount_refunded Currency Subtotal discount refunded (read only except refund operation)
subtotal_refunded (read only) Currency Subtotal refunded
tax Currency Tax, may be updated to reflect any changes made to the tax fields, but cannot be used when inserting an order. For inserting, use the arbitrary fields instead.
tax_refunded Currency Tax refunded (read only except refund operation)
taxable_subtotal (read only) Currency Taxable subtotal
taxable_subtotal_discount (read only) Currency Taxable subtotal discount
total (read only) Currency Total
total_refunded (read only) Currency Total refunded

OrderTag

Attributes
Name Data Type Description
tag_value string(100) Tag Value

OrderTaxes

Attributes
Name Data Type Description
arbitrary_tax number Arbitrary Tax, this is meaningless for updating an order. For inserting a new order, this will override any internal tax calculations and should only be used for orders completed outside the system.
arbitrary_tax_rate number Arbitrary tax rate, this is meaningless for updating an order. For inserting a new order, this will override any internal tax calculations and should only be used for orders completed outside the system.
arbitrary_taxable_subtotal number Arbitrary taxable subtotal, this is meaningless for updating an order. For inserting a new order, this will override any internal tax calculations and should only be used for orders completed outside the system.
tax_city_accounting_code (read only) string QuickBooks tax city code
tax_country_accounting_code (read only) string QuickBooks tax country code
tax_county string(32) County used for tax calculation purposes (only in the United States)
tax_county_accounting_code (read only) string QuickBooks tax county code
tax_gift_charge (read only) boolean True if gift charge is taxed
tax_postal_code_accounting_code (read only) string QuickBooks tax postal code code
tax_rate number Tax rate, this is meaningless for updating an order. For inserting a new order, if you need to override internal tax calculations, use the arbitrary fields.
tax_rate_city (read only) number Tax rate at the city level
tax_rate_country (read only) number Tax rate at the country level
tax_rate_county (read only) number Tax rate at the county level
tax_rate_postal_code (read only) number Tax rate at the postal code level
tax_rate_state (read only) number Tax rate at the state level
tax_shipping (read only) boolean True if shipping is taxed
tax_state_accounting_code (read only) string QuickBooks tax state code

OrderTokenResponse

Attributes
Name Data Type Description
error Error Error object if unsuccessful
metadata ResponseMetadata Meta-data about the response such as payload or paging information
order_token string An order token that securely represents an order id
success boolean Indicates if API call was successful
warning Warning Warning object if a non-fatal issue or side-effect occurs

OrderTrackingNumberDetail

Attributes
Name Data Type Description
city string
event_dts (read only) string (dateTime) ISO 8601 timestamp that the event occurred
event_local_date string
event_local_time string
event_timezone_id (read only) string Timezone the event occurred in. Use this in conjunction with event_dts to format a local date/time.
state string
subtag string
subtag_message string
tag string
tag_description string
tag_icon string
zip string

OrderTrackingNumberDetails

Attributes
Name Data Type Description
actual_delivery_date string
actual_delivery_date_formatted string
details array of OrderTrackingNumberDetail
easypost_tracker_id string
expected_delivery_date string
expected_delivery_date_formatted string
map_url string
order_placed_date string
order_placed_date_formatted string
payment_processed_date string
payment_processed_date_formatted string
shipped_date string
shipped_date_formatted string
shipping_method string
status string
status_description string
tracking_number string
tracking_url string

OrderTransactionalMerchantNote

Attributes
Name Data Type Description
ip_address string IP Address
note string note
note_dts (read only) string (dateTime) Timestamp when the note was added
user string User that wrote the merchant note

OrderUtm

Attributes
Name Data Type Description
attribution_first_click_subtotal number
attribution_first_click_total number
attribution_last_click_subtotal number
attribution_last_click_total number
attribution_linear_subtotal number
attribution_linear_total number
attribution_position_based_subtotal number
attribution_position_based_total number
click_dts (read only) string (dateTime) Date/time that the click happened
facebook_ad_id string
fbclid string
gbraid string
glcid string
itm_campaign string
itm_content string
itm_id string
itm_medium string
itm_source string
itm_term string
msclkid string
short_code string
short_code_backup boolean
ttclid string
uc_message_id string
utm_campaign string
utm_content string
utm_id string
utm_medium string
utm_source string
utm_term string
vmcid string
wbraid string

OrderValidationRequest

Attributes
Name Data Type Description
checks array of string Checks to perform
Allowed Values
  • All
  • Billing Address Provided
  • Billing Phone Numbers Provided
  • Billing State Abbreviation Valid
  • Billing Validate City State Zip
  • Email provided if required
  • Gift Message Length
  • Items Present
  • Referral Code Provided
  • Shipping Address Provided
  • Shipping Method Provided
  • Shipping State Abbreviation Valid
  • Shipping Validate City State Zip
order Order Order

OrderValidationResponse

Attributes
Name Data Type Description
errors array of string Errors to display to the merchant if they failed any of the validations checked
messages array of string Informational messages
order_was_updated boolean If true, this order was updated during the validation call. This may happen during address standardization fixes.

PointOfSaleLocation

Attributes
Name Data Type Description
adddress2 string Address line 2
address1 string Address line 1
city string City
country string Country
distribution_center_code string The distribution center code where inventory is reduced from for this sale.
external_id string(100) External Id useful for syncing with a remote filesystem, this may be an MD5 hash or whatever suits your needs.
merchant_id string Merchant ID that owns this location
pos_location_oid integer (int32) Object identifier of the point of sale location.
postal_code string Postal code
state_province string State/province

PointOfSaleReader

Attributes
Name Data Type Description
device_type string The device type of the reader.
label string The label of the reader.
merchant_id string The merchant id that owns this point of sale reader.
payment_provider string The payment provider for the card reader.
Allowed Values
  • stripe
pos_reader_id integer (int32) Object identifier of the point of sale reader.
pos_register_oid integer (int32) Object identifier of the point of sale register this reader is assigned to.
serial_number string The serial number of the reader.
stripe_account_id string If the payment provider is Stripe, this is the Stripe account id
stripe_reader_id string If the payment provide is Stripe, this is the Stripe terminal reader id

PointOfSaleRegister

Attributes
Name Data Type Description
merchant_id string The merchant id that owns this point of sale register.
name string Name of the register.
pos_location_oid integer (int32) Object identifier of the point of sale location where this register is located.
pos_register_oid integer (int32) Object identifier of the point of sale register.

Property

Attributes
Name Data Type Description
name string
value string

ResponseMetadata

Attributes
Name Data Type Description
payload_name string Payload name
result_set ResultSet Result set

ResultSet

Attributes
Name Data Type Description
count integer (int32) Number of results in this set
limit integer (int32) Maximum number of results that can be returned in a set
more boolean True if there are more results to query
next_offset integer (int32) The next offset that you should query to retrieve more results
offset integer (int32) Offset of this result set (zero based)
total_records integer (int32) The total number of records in the result set. May be null if the number is not known and the client should continue iterating as long as more is true.

Warning

Attributes
Name Data Type Description
more_info string Additional information often a link to additional documentation
warning_message string A technical message meant to be read by a developer

Weight

Attributes
Name Data Type Description
uom string Unit of measure
Allowed Values
  • KG
  • G
  • LB
  • OZ
value number Weight

400
Status Code 400: bad request input such as invalid json

Headers
Name Data Type Description
UC-REST-ERROR string Contains human readable error message
Response
Name Data Type
body ErrorResponse

401
Status Code 401: invalid credentials supplied

Headers
Name Data Type Description
UC-REST-ERROR string Contains human readable error message
Response
Name Data Type
body ErrorResponse

410
Status Code 410: Your authorized application has been disabled by UltraCart

Headers
Name Data Type Description
UC-REST-ERROR string Contains human readable error message
Response
Name Data Type
body ErrorResponse

429
Status Code 429: you have exceeded the allowed API call rate limit for your application.

Headers
Name Data Type Description
UC-REST-ERROR string Contains human readable error message
Response
Name Data Type
body ErrorResponse

500
Status Code 500: any server side error. the body will contain a generic server error message

Headers
Name Data Type Description
UC-REST-ERROR string Contains human readable error message
Response
Name Data Type
body ErrorResponse