csharp
java
javascript
php
python
ruby
typescript

channel_partner

/channel_partner

Cancel channel partner order by channel partner order id

Permissions:
  • channel_partner_write

Produces: application/json
delete
/channel_partner/cancel/by_channel_partner_order_id/{order_id}

Cancel channel partner order by channel partner order id

SDK Function Name: cancelOrderByChannelPartnerOrderId

Parameters
Parameter Description Location Data Type Required
order_id The channel partner order id to delete. path string required
Responses
Status Code Reason Response Model
200
Successful response ChannelPartnerCancelResponse
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.Reflection;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;

namespace SdkSample.channel_partner
{
    public class CancelOrderByChannelPartnerOrderId
    {
        /*
        cancelOrderByChannelPartnerOrderId takes a channel partner order id, which is the external order id, and attempts
        to 'cancel' the order.  UltraCart doesn't have a cancel order state, so this needs some explanation of what happens.

        Here is the logic of the cancel process:
        If the Order stage is [this] then do [that]:
            'Completed Order'       -> Error: "Order has already been completed."
            'Rejected'              -> Error: "Order has already been rejected."
            'Accounts Receivable'   -> Success: order is rejected.
            'Preordered'            -> Success: order is rejected.
            'Quote Sent'            -> Success: order is rejected.
            'Quote Requested'       -> Success: order is rejected.

        The remaining stages are Fraud Review and Shipping Department.  Orders in these stages have already completed payment.
        From this point, complex logic determines if the order has already shipped, or is queued to ship in a way that cannot be canceled.
        Here is the logic for those stages, but the gist of it all is this:  If you receive any of the errors below, the order has progressed past a point where it can be canceled.
        SHIPPING LOGIC:
        Iterate through each item and consider it's shipping status:
            Item has already been transmitted to fulfillment center (contains a transmitted dts) -> Error: "The order has already had an item that has been transmitted to the distribution center."
            Does item DC (distribution center) have a transmission mechanism configured?
                YES -> Does the transmission have schedules? If NO -> Error: "The distribution center does not have any schedules so it would be an immediate transmission."
                NO -> Error: "Cant tell if we can cancel because the DC doesnt have a transport configured."

        If the above logic completes without errors, the following conditions must be met:
        Order has DC activity records.  If NO -> Error: "There is no activity in the DC queue when there should be."
        There must be at least 5 minutes before the next DC transmission. If NO -> Error: "Activity record is not at least 5 minutes away so we need to bail."

        At this point, the order will be canceled with the following activity:
        1) Distribution Center activity is cleared
        2) The order is refunded.  If the order is less than 24 hours old, a void is attempted instead.


        Other Possible Errors:
        System errors -> "Internal error.  Please contact UltraCart Support."
        Order does not exist -> "Invalid order ID specified."
        During refunding, original transaction could not be found -> "Unable to find original transaction on the order."
        During refunding, original transaction was found, but transaction id could not be found -> "Unable to locate original transaction reference number."
        During refunding, PayPal was used by no longer configured -> "PayPal is no longer configured on your account to refund against."
        Gateway does not support refunds -> [GatewayName] does not support refunds at this time.
        */
        public static void Execute()
        {
            Console.WriteLine("--- " + MethodBase.GetCurrentMethod()?.DeclaringType?.Name + " ---");
            
            try
            {
                // Create channel partner API instance using API key
                ChannelPartnerApi channelPartnerApi = new ChannelPartnerApi(Constants.ChannelPartnerApiKey);
                
                string channelPartnerOrderId = "BLAH-BLAH-123";
                var cancelResult = channelPartnerApi.CancelOrderByChannelPartnerOrderId(channelPartnerOrderId);
                
                if (!cancelResult.Success)
                {
                    foreach (string error in cancelResult.CancelErrors)
                    {
                        Console.WriteLine(error);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex); // Dumps all exception information
            }
        }
    }
}
package channel_partner;

import com.ultracart.admin.v2.ChannelPartnerApi;
import com.ultracart.admin.v2.models.ChannelPartnerCancelResponse;

import java.util.List;

public class CancelOrderByChannelPartnerOrderId {
    /*
    cancelOrderByChannelPartnerOrderId takes a channel partner order id, which is the external order id, and attempts
    to 'cancel' the order.  UltraCart doesn't have a cancel order state, so this needs some explanation of what happens.

    Here is the logic of the cancel process:
    If the Order stage is [this] then do [that]:
        'Completed Order'       -> Error: "Order has already been completed."
        'Rejected'              -> Error: "Order has already been rejected."
        'Accounts Receivable'   -> Success: order is rejected.
        'Preordered'            -> Success: order is rejected.
        'Quote Sent'            -> Success: order is rejected.
        'Quote Requested'       -> Success: order is rejected.

    The remaining stages are Fraud Review and Shipping Department.  Orders in these stages have already completed payment.
    From this point, complex logic determines if the order has already shipped, or is queued to ship in a way that cannot be canceled.
    Here is the logic for those stages, but the gist of it all is this:  If you receive any of the errors below, the order has progressed past a point where it can be canceled.
    SHIPPING LOGIC:
    Iterate through each item and consider it's shipping status:
        Item has already been transmitted to fulfillment center (contains a transmitted dts) -> Error: "The order has already had an item that has been transmitted to the distribution center."
        Does item DC (distribution center) have a transmission mechanism configured?
            YES -> Does the transmission have schedules? If NO -> Error: "The distribution center does not have any schedules so it would be an immediate transmission."
            NO -> Error: "Cant tell if we can cancel because the DC doesnt have a transport configured."

    If the above logic completes without errors, the following conditions must be met:
    Order has DC activity records.  If NO -> Error: "There is no activity in the DC queue when there should be."
    There must be at least 5 minutes before the next DC transmission. If NO -> Error: "Activity record is not at least 5 minutes away so we need to bail."

    At this point, the order will be canceled with the following activity:
    1) Distribution Center activity is cleared
    2) The order is refunded.  If the order is less than 24 hours old, a void is attempted instead.


    Other Possible Errors:
    System errors -> "Internal error.  Please contact UltraCart Support."
    Order does not exist -> "Invalid order ID specified."
    During refunding, original transaction could not be found -> "Unable to find original transaction on the order."
    During refunding, original transaction was found, but transaction id could not be found -> "Unable to locate original transaction reference number."
    During refunding, PayPal was used by no longer configured -> "PayPal is no longer configured on your account to refund against."
    Gateway does not support refunds -> [GatewayName] does not support refunds at this time.
    */
    public static void execute() {
        System.out.println("--- CancelOrderByChannelPartnerOrderId ---");

        try {
            // Create channel partner API instance using API key
            ChannelPartnerApi channelPartnerApi = new ChannelPartnerApi(common.Constants.CHANNEL_PARTNER_API_KEY);

            String channelPartnerOrderId = "BLAH-BLAH-123";
            ChannelPartnerCancelResponse cancelResult = channelPartnerApi.cancelOrderByChannelPartnerOrderId(channelPartnerOrderId);

            if (!cancelResult.getSuccess()) {
                List<String> errors = cancelResult.getCancelErrors();
                for (String error : errors) {
                    System.out.println(error);
                }
            }
        }
        catch (Exception ex) {
            System.out.println(ex); // Dumps all exception information
        }
    }
}
import { channelPartnerApi } from '../api.js';

export class CancelOrderByChannelPartnerOrderId {
    /*
    cancelOrderByChannelPartnerOrderId takes a channel partner order id, which is the external order id, and attempts
    to 'cancel' the order.  UltraCart doesn't have a cancel order state, so this needs some explanation of what happens.

    Here is the logic of the cancel process:
    If the Order stage is [this] then do [that]:
        'Completed Order'       -> Error: "Order has already been completed."
        'Rejected'              -> Error: "Order has already been rejected."
        'Accounts Receivable'   -> Success: order is rejected.
        'Preordered'            -> Success: order is rejected.
        'Quote Sent'            -> Success: order is rejected.
        'Quote Requested'       -> Success: order is rejected.

    The remaining stages are Fraud Review and Shipping Department.  Orders in these stages have already completed payment.
    From this point, complex logic determines if the order has already shipped, or is queued to ship in a way that cannot be canceled.
    Here is the logic for those stages, but the gist of it all is this:  If you receive any of the errors below, the order has progressed past a point where it can be canceled.
    SHIPPING LOGIC:
    Iterate through each item and consider its shipping status:
        Item has already been transmitted to fulfillment center (contains a transmitted dts) -> Error: "The order has already had an item that has been transmitted to the distribution center."
        Does item DC (distribution center) have a transmission mechanism configured?
            YES -> Does the transmission have schedules? If NO -> Error: "The distribution center does not have any schedules so it would be an immediate transmission."
            NO -> Error: "Can't tell if we can cancel because the DC doesn't have a transport configured."

    If the above logic completes without errors, the following conditions must be met:
    Order has DC activity records.  If NO -> Error: "There is no activity in the DC queue when there should be."
    There must be at least 5 minutes before the next DC transmission. If NO -> Error: "Activity record is not at least 5 minutes away so we need to bail."

    At this point, the order will be canceled with the following activity:
    1) Distribution Center activity is cleared
    2) The order is refunded.  If the order is less than 24 hours old, a void is attempted instead.

    Other Possible Errors:
    System errors -> "Internal error.  Please contact UltraCart Support."
    Order does not exist -> "Invalid order ID specified."
    During refunding, original transaction could not be found -> "Unable to find original transaction on the order."
    During refunding, original transaction was found, but transaction id could not be found -> "Unable to locate original transaction reference number."
    During refunding, PayPal was used but no longer configured -> "PayPal is no longer configured on your account to refund against."
    Gateway does not support refunds -> [GatewayName] does not support refunds at this time.
    */
    static async execute() {
        console.log(`--- ${this.name} ---`);

        try {
            // Channel partner order ID to cancel
            const channelPartnerOrderId = "BLAH-BLAH-123";

            // Attempt to cancel the order using a Promise wrapper
            const cancelResult = await new Promise((resolve, reject) => {
                channelPartnerApi.cancelOrderByChannelPartnerOrderId(
                    channelPartnerOrderId,
                    function (error, data) {
                        if (error) {
                            reject(error);
                        } else {
                            resolve(data);
                        }
                    }
                );
            });

            // Check if cancellation was not successful
            if (!cancelResult.success) {
                cancelResult.cancel_errors?.forEach((error) => {
                    console.log(error);
                });
            }
        } catch (ex) {
            console.error(ex);
        }
    }
}

<?php

ini_set('display_errors', 1);

/*

cancelOrderByChannelPartnerOrderId takes a channel partner order id, which is the external order id, and attempts
to 'cancel' the order.  UltraCart doesn't have a cancel order state, so this needs some explanation of what happens.

Here is the logic of the cancel process:
If the Order stage is [this] then do [that]:
    'Completed Order'       -> Error: "Order has already been completed."
    'Rejected'              -> Error: "Order has already been rejected."
    'Accounts Receivable'   -> Success: order is rejected.
    'Preordered'            -> Success: order is rejected.
    'Quote Sent'            -> Success: order is rejected.
    'Quote Requested'       -> Success: order is rejected.

The remaining stages are Fraud Review and Shipping Department.  Orders in these stages have already completed payment.
From this point, complex logic determines if the order has already shipped, or is queued to ship in a way that cannot be canceled.
Here is the logic for those stages, but the gist of it all is this:  If you receive any of the errors below, the order has progressed past a point where it can be canceled.
SHIPPING LOGIC:
Iterate through each item and consider it's shipping status:
    Item has already been transmitted to fulfillment center (contains a transmitted dts) -> Error: "The order has already had an item that has been transmitted to the distribution center."
    Does item DC (distribution center) have a transmission mechanism configured?
        YES -> Does the transmission have schedules? If NO -> Error: "The distribution center does not have any schedules so it would be an immediate transmission."
        NO -> Error: "Cant tell if we can cancel because the DC doesnt have a transport configured."

If the above logic completes without errors, the following conditions must be met:
Order has DC activity records.  If NO -> Error: "There is no activity in the DC queue when there should be."
There must be at least 5 minutes before the next DC transmission. If NO -> Error: "Activity record is not at least 5 minutes away so we need to bail."

At this point, the order will be canceled with the following activity:
1) Distribution Center activity is cleared
2) The order is refunded.  If the order is less than 24 hours old, a void is attempted instead.


Other Possible Errors:
System errors -> "Internal error.  Please contact UltraCart Support."
Order does not exist -> "Invalid order ID specified."
During refunding, original transaction could not be found -> "Unable to find original transaction on the order."
During refunding, original transaction was found, but transaction id could not be found -> "Unable to locate original transaction reference number."
During refunding, PayPal was used by no longer configured -> "PayPal is no longer configured on your account to refund against."
Gateway does not support refunds -> [GatewayName] does not support refunds at this time.

 */


use ultracart\v2\api\ChannelPartnerApi;
use ultracart\v2\ApiException;

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

$channel_partner_api = ChannelPartnerApi::usingApiKey(Constants::CHANNEL_PARTNER_API_KEY);

$channel_partner_order_id = 'BLAH-BLAH-123';
try {
    $cancel_result = $channel_partner_api->cancelOrderByChannelPartnerOrderId($channel_partner_order_id);
    if(!$cancel_result->getSuccess()){
        $errors = $cancel_result->getCancelErrors();
        foreach ($errors as $error){
            echo $error . "\n";
        }
    }

} catch (ApiException $e) {
    var_dump($e);  // Dumps all exception information
}


"""
cancelOrderByChannelPartnerOrderId takes a channel partner order id, which is the external order id, and attempts
to 'cancel' the order. UltraCart doesn't have a cancel order state, so this needs some explanation of what happens.

Here is the logic of the cancel process:
If the Order stage is [this] then do [that]:
    'Completed Order'       -> Error: "Order has already been completed."
    'Rejected'             -> Error: "Order has already been rejected."
    'Accounts Receivable'  -> Success: order is rejected.
    'Preordered'          -> Success: order is rejected.
    'Quote Sent'          -> Success: order is rejected.
    'Quote Requested'     -> Success: order is rejected.

The remaining stages are Fraud Review and Shipping Department. Orders in these stages have already completed payment.
From this point, complex logic determines if the order has already shipped, or is queued to ship in a way that cannot be canceled.
Here is the logic for those stages, but the gist of it all is this: If you receive any of the errors below, the order has progressed past a point where it can be canceled.

SHIPPING LOGIC:
Iterate through each item and consider it's shipping status:
    Item has already been transmitted to fulfillment center (contains a transmitted dts) -> Error: "The order has already had an item that has been transmitted to the distribution center."
    Does item DC (distribution center) have a transmission mechanism configured?
        YES -> Does the transmission have schedules? If NO -> Error: "The distribution center does not have any schedules so it would be an immediate transmission."
        NO -> Error: "Cant tell if we can cancel because the DC doesnt have a transport configured."

If the above logic completes without errors, the following conditions must be met:
Order has DC activity records. If NO -> Error: "There is no activity in the DC queue when there should be."
There must be at least 5 minutes before the next DC transmission. If NO -> Error: "Activity record is not at least 5 minutes away so we need to bail."

At this point, the order will be canceled with the following activity:
1) Distribution Center activity is cleared
2) The order is refunded. If the order is less than 24 hours old, a void is attempted instead.

Other Possible Errors:
System errors -> "Internal error. Please contact UltraCart Support."
Order does not exist -> "Invalid order ID specified."
During refunding, original transaction could not be found -> "Unable to find original transaction on the order."
During refunding, original transaction was found, but transaction id could not be found -> "Unable to locate original transaction reference number."
During refunding, PayPal was used by no longer configured -> "PayPal is no longer configured on your account to refund against."
Gateway does not support refunds -> [GatewayName] does not support refunds at this time.
"""

from ultracart.apis import ChannelPartnerApi
from ultracart.exceptions import ApiException
from samples import channel_partner_api_client

channel_partner_api = ChannelPartnerApi(channel_partner_api_client())

channel_partner_order_id = 'BLAH-BLAH-123'

try:
    cancel_result = channel_partner_api.cancel_order_by_channel_partner_order_id(channel_partner_order_id)
    if not cancel_result.success:
        for error in cancel_result.cancel_errors:
            print(error)

except ApiException as e:
    print(e)  # Prints the exception information
require 'ultracart_api'
require_relative '../constants'

# cancelOrderByChannelPartnerOrderId takes a channel partner order id, which is the external order id, and attempts
# to 'cancel' the order.  UltraCart doesn't have a cancel order state, so this needs some explanation of what happens.
#
# Here is the logic of the cancel process:
# If the Order stage is [this] then do [that]:
#     'Completed Order'       -> Error: "Order has already been completed."
#     'Rejected'              -> Error: "Order has already been rejected."
#     'Accounts Receivable'   -> Success: order is rejected.
#     'Preordered'            -> Success: order is rejected.
#     'Quote Sent'            -> Success: order is rejected.
#     'Quote Requested'       -> Success: order is rejected.
#
# The remaining stages are Fraud Review and Shipping Department.  Orders in these stages have already completed payment.
# From this point, complex logic determines if the order has already shipped, or is queued to ship in a way that cannot be canceled.
# Here is the logic for those stages, but the gist of it all is this:  If you receive any of the errors below, the order has progressed past a point where it can be canceled.
# SHIPPING LOGIC:
# Iterate through each item and consider it's shipping status:
#     Item has already been transmitted to fulfillment center (contains a transmitted dts) -> Error: "The order has already had an item that has been transmitted to the distribution center."
#     Does item DC (distribution center) have a transmission mechanism configured?
#         YES -> Does the transmission have schedules? If NO -> Error: "The distribution center does not have any schedules so it would be an immediate transmission."
#         NO -> Error: "Cant tell if we can cancel because the DC doesnt have a transport configured."
#
# If the above logic completes without errors, the following conditions must be met:
# Order has DC activity records.  If NO -> Error: "There is no activity in the DC queue when there should be."
# There must be at least 5 minutes before the next DC transmission. If NO -> Error: "Activity record is not at least 5 minutes away so we need to bail."
#
# At this point, the order will be canceled with the following activity:
# 1) Distribution Center activity is cleared
# 2) The order is refunded.  If the order is less than 24 hours old, a void is attempted instead.
#
#
# Other Possible Errors:
# System errors -> "Internal error.  Please contact UltraCart Support."
# Order does not exist -> "Invalid order ID specified."
# During refunding, original transaction could not be found -> "Unable to find original transaction on the order."
# During refunding, original transaction was found, but transaction id could not be found -> "Unable to locate original transaction reference number."
# During refunding, PayPal was used by no longer configured -> "PayPal is no longer configured on your account to refund against."
# Gateway does not support refunds -> [GatewayName] does not support refunds at this time.

channel_partner_api = UltracartClient::ChannelPartnerApi.new_using_api_key(Constants::CHANNEL_PARTNER_API_KEY)

channel_partner_order_id = 'BLAH-BLAH-123'
begin
  cancel_result = channel_partner_api.cancel_order_by_channel_partner_order_id(channel_partner_order_id)
  unless cancel_result.success
    cancel_result.cancel_errors.each do |error|
      puts error
    end
  end
rescue UltracartClient::ApiError => e
  puts e.inspect  # Dumps all exception information
end
import {channelPartnerApi} from '../api';
import {ChannelPartnerCancelResponse} from "ultracart_rest_api_v2_typescript";

export class CancelOrderByChannelPartnerOrderId {
    /*
    cancelOrderByChannelPartnerOrderId takes a channel partner order id, which is the external order id, and attempts
    to 'cancel' the order.  UltraCart doesn't have a cancel order state, so this needs some explanation of what happens.

    Here is the logic of the cancel process:
    If the Order stage is [this] then do [that]:
        'Completed Order'       -> Error: "Order has already been completed."
        'Rejected'              -> Error: "Order has already been rejected."
        'Accounts Receivable'   -> Success: order is rejected.
        'Preordered'            -> Success: order is rejected.
        'Quote Sent'            -> Success: order is rejected.
        'Quote Requested'       -> Success: order is rejected.

    The remaining stages are Fraud Review and Shipping Department.  Orders in these stages have already completed payment.
    From this point, complex logic determines if the order has already shipped, or is queued to ship in a way that cannot be canceled.
    Here is the logic for those stages, but the gist of it all is this:  If you receive any of the errors below, the order has progressed past a point where it can be canceled.
    SHIPPING LOGIC:
    Iterate through each item and consider it's shipping status:
        Item has already been transmitted to fulfillment center (contains a transmitted dts) -> Error: "The order has already had an item that has been transmitted to the distribution center."
        Does item DC (distribution center) have a transmission mechanism configured?
            YES -> Does the transmission have schedules? If NO -> Error: "The distribution center does not have any schedules so it would be an immediate transmission."
            NO -> Error: "Cant tell if we can cancel because the DC doesnt have a transport configured."

    If the above logic completes without errors, the following conditions must be met:
    Order has DC activity records.  If NO -> Error: "There is no activity in the DC queue when there should be."
    There must be at least 5 minutes before the next DC transmission. If NO -> Error: "Activity record is not at least 5 minutes away so we need to bail."

    At this point, the order will be canceled with the following activity:
    1) Distribution Center activity is cleared
    2) The order is refunded.  If the order is less than 24 hours old, a void is attempted instead.


    Other Possible Errors:
    System errors -> "Internal error.  Please contact UltraCart Support."
    Order does not exist -> "Invalid order ID specified."
    During refunding, original transaction could not be found -> "Unable to find original transaction on the order."
    During refunding, original transaction was found, but transaction id could not be found -> "Unable to locate original transaction reference number."
    During refunding, PayPal was used by no longer configured -> "PayPal is no longer configured on your account to refund against."
    Gateway does not support refunds -> [GatewayName] does not support refunds at this time.
    */
    public static async Execute(): Promise<void> {
        console.log(`--- ${this.name} ---`);

        try {
            // Channel partner order ID to cancel
            const channelPartnerOrderId: string = "BLAH-BLAH-123";

            // Attempt to cancel the order
            const cancelResult: ChannelPartnerCancelResponse = await channelPartnerApi.cancelOrderByChannelPartnerOrderId({orderId: channelPartnerOrderId});

            // Check if cancellation was not successful
            if (!cancelResult.success) {
                // Log each cancellation error
                cancelResult.cancel_errors?.forEach((error: string) => {
                    console.log(error);
                });
            }
        } catch (ex) {
            // Log the entire exception
            console.error(ex);
        }
    }
}

Cancel channel partner order by UltraCart order id

Permissions:
  • channel_partner_write

Produces: application/json
delete
/channel_partner/cancel/by_ultracart_order_id/{order_id}

Cancel channel partner order by UltraCart order id

SDK Function Name: cancelOrderByUltraCartOrderId

Parameters
Parameter Description Location Data Type Required
order_id The UltraCart order id to delete. path string required
Responses
Status Code Reason Response Model
200
Successful response ChannelPartnerCancelResponse
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.Reflection;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;

namespace SdkSample.channel_partner
{
    public class CancelOrderByUltraCartOrderId
    {
        /*
        cancelOrderByUltraCartOrderId takes an UltraCart order id and attempts to 'cancel' the order.
        UltraCart doesn't have a cancel order state, so this needs some explanation of what happens.

        Here is the logic of the cancel process:
        If the Order stage is [this] then do [that]:
            'Completed Order'       -> Error: "Order has already been completed."
            'Rejected'              -> Error: "Order has already been rejected."
            'Accounts Receivable'   -> Success: order is rejected.
            'Preordered'            -> Success: order is rejected.
            'Quote Sent'            -> Success: order is rejected.
            'Quote Requested'       -> Success: order is rejected.

        The remaining stages are Fraud Review and Shipping Department.  Orders in these stages have already completed payment.
        From this point, complex logic determines if the order has already shipped, or is queued to ship in a way that cannot be canceled.
        Here is the logic for those stages, but the gist of it all is this:  If you receive any of the errors below, the order has progressed past a point where it can be canceled.
        SHIPPING LOGIC:
        Iterate through each item and consider it's shipping status:
            Item has already been transmitted to fulfillment center (contains a transmitted dts) -> Error: "The order has already had an item that has been transmitted to the distribution center."
            Does item DC (distribution center) have a transmission mechanism configured?
                YES -> Does the transmission have schedules? If NO -> Error: "The distribution center does not have any schedules so it would be an immediate transmission."
                NO -> Error: "Cant tell if we can cancel because the DC doesnt have a transport configured."

        If the above logic completes without errors, the following conditions must be met:
        Order has DC activity records.  If NO -> Error: "There is no activity in the DC queue when there should be."
        There must be at least 5 minutes before the next DC transmission. If NO -> Error: "Activity record is not at least 5 minutes away so we need to bail."

        At this point, the order will be canceled with the following activity:
        1) Distribution Center activity is cleared
        2) The order is refunded.  If the order is less than 24 hours old, a void is attempted instead.


        Other Possible Errors:
        System errors -> "Internal error.  Please contact UltraCart Support."
        Order does not exist -> "Invalid order ID specified."
        During refunding, original transaction could not be found -> "Unable to find original transaction on the order."
        During refunding, original transaction was found, but transaction id could not be found -> "Unable to locate original transaction reference number."
        During refunding, PayPal was used by no longer configured -> "PayPal is no longer configured on your account to refund against."
        Gateway does not support refunds -> [GatewayName] does not support refunds at this time.
        */
        public static void Execute()
        {
            Console.WriteLine("--- " + MethodBase.GetCurrentMethod()?.DeclaringType?.Name + " ---");
            
            try
            {
                // Create channel partner API instance using API key
                ChannelPartnerApi channelPartnerApi = new ChannelPartnerApi(Constants.ChannelPartnerApiKey);
                
                string ultracartOrderId = "DEMO-12345678980";
                var cancelResult = channelPartnerApi.CancelOrderByUltraCartOrderId(ultracartOrderId);
                
                if (!cancelResult.Success)
                {
                    foreach (string error in cancelResult.CancelErrors)
                    {
                        Console.WriteLine(error);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);  // Dumps all exception information
            }
        }
    }
}
package channel_partner;

import com.ultracart.admin.v2.ChannelPartnerApi;
import com.ultracart.admin.v2.models.ChannelPartnerCancelResponse;

import java.util.List;

public class CancelOrderByUltraCartOrderId {
    /*
    cancelOrderByUltraCartOrderId takes an UltraCart order id and attempts to 'cancel' the order.
    UltraCart doesn't have a cancel order state, so this needs some explanation of what happens.

    Here is the logic of the cancel process:
    If the Order stage is [this] then do [that]:
        'Completed Order'       -> Error: "Order has already been completed."
        'Rejected'              -> Error: "Order has already been rejected."
        'Accounts Receivable'   -> Success: order is rejected.
        'Preordered'            -> Success: order is rejected.
        'Quote Sent'            -> Success: order is rejected.
        'Quote Requested'       -> Success: order is rejected.

    The remaining stages are Fraud Review and Shipping Department.  Orders in these stages have already completed payment.
    From this point, complex logic determines if the order has already shipped, or is queued to ship in a way that cannot be canceled.
    Here is the logic for those stages, but the gist of it all is this:  If you receive any of the errors below, the order has progressed past a point where it can be canceled.
    SHIPPING LOGIC:
    Iterate through each item and consider it's shipping status:
        Item has already been transmitted to fulfillment center (contains a transmitted dts) -> Error: "The order has already had an item that has been transmitted to the distribution center."
        Does item DC (distribution center) have a transmission mechanism configured?
            YES -> Does the transmission have schedules? If NO -> Error: "The distribution center does not have any schedules so it would be an immediate transmission."
            NO -> Error: "Cant tell if we can cancel because the DC doesnt have a transport configured."

    If the above logic completes without errors, the following conditions must be met:
    Order has DC activity records.  If NO -> Error: "There is no activity in the DC queue when there should be."
    There must be at least 5 minutes before the next DC transmission. If NO -> Error: "Activity record is not at least 5 minutes away so we need to bail."

    At this point, the order will be canceled with the following activity:
    1) Distribution Center activity is cleared
    2) The order is refunded.  If the order is less than 24 hours old, a void is attempted instead.


    Other Possible Errors:
    System errors -> "Internal error.  Please contact UltraCart Support."
    Order does not exist -> "Invalid order ID specified."
    During refunding, original transaction could not be found -> "Unable to find original transaction on the order."
    During refunding, original transaction was found, but transaction id could not be found -> "Unable to locate original transaction reference number."
    During refunding, PayPal was used by no longer configured -> "PayPal is no longer configured on your account to refund against."
    Gateway does not support refunds -> [GatewayName] does not support refunds at this time.
    */
    public static void execute() {
        System.out.println("--- CancelOrderByUltraCartOrderId ---");

        try {
            // Create channel partner API instance using API key
            ChannelPartnerApi channelPartnerApi = new ChannelPartnerApi(common.Constants.CHANNEL_PARTNER_API_KEY);

            String ultracartOrderId = "DEMO-12345678980";
            ChannelPartnerCancelResponse cancelResult = channelPartnerApi.cancelOrderByUltraCartOrderId(ultracartOrderId);

            if (!cancelResult.getSuccess()) {
                List<String> errors = cancelResult.getCancelErrors();
                for (String error : errors) {
                    System.out.println(error);
                }
            }
        }
        catch (Exception ex) {
            System.out.println(ex);  // Dumps all exception information
        }
    }
}
import { channelPartnerApi } from '../api.js';

/**
 * cancelOrderByUltraCartOrderId takes an UltraCart order id and attempts to 'cancel' the order.
 * UltraCart doesn't have a cancel order state, so this needs some explanation of what happens.
 *
 * Here is the logic of the cancel process:
 * If the Order stage is [this] then do [that]:
 *     'Completed Order'       -> Error: "Order has already been completed."
 *     'Rejected'              -> Error: "Order has already been rejected."
 *     'Accounts Receivable'   -> Success: order is rejected.
 *     'Preordered'            -> Success: order is rejected.
 *     'Quote Sent'            -> Success: order is rejected.
 *     'Quote Requested'       -> Success: order is rejected.
 *
 * The remaining stages are Fraud Review and Shipping Department.  Orders in these stages have already completed payment.
 * From this point, complex logic determines if the order has already shipped, or is queued to ship in a way that cannot be canceled.
 * Here is the logic for those stages, but the gist of it all is this:  If you receive any of the errors below, the order has progressed past a point where it can be canceled.
 * SHIPPING LOGIC:
 * Iterate through each item and consider its shipping status:
 *     Item has already been transmitted to fulfillment center (contains a transmitted dts) -> Error: "The order has already had an item that has been transmitted to the distribution center."
 *     Does item DC (distribution center) have a transmission mechanism configured?
 *         YES -> Does the transmission have schedules? If NO -> Error: "The distribution center does not have any schedules so it would be an immediate transmission."
 *         NO -> Error: "Can't tell if we can cancel because the DC doesn't have a transport configured."
 *
 * If the above logic completes without errors, the following conditions must be met:
 * Order has DC activity records.  If NO -> Error: "There is no activity in the DC queue when there should be."
 * There must be at least 5 minutes before the next DC transmission. If NO -> Error: "Activity record is not at least 5 minutes away so we need to bail."
 *
 * At this point, the order will be canceled with the following activity:
 * 1) Distribution Center activity is cleared
 * 2) The order is refunded.  If the order is less than 24 hours old, a void is attempted instead.
 *
 * Other Possible Errors:
 * System errors -> "Internal error.  Please contact UltraCart Support."
 * Order does not exist -> "Invalid order ID specified."
 * During refunding, original transaction could not be found -> "Unable to find original transaction on the order."
 * During refunding, original transaction was found, but transaction id could not be found -> "Unable to locate original transaction reference number."
 * During refunding, PayPal was used but no longer configured -> "PayPal is no longer configured on your account to refund against."
 * Gateway does not support refunds -> [GatewayName] does not support refunds at this time.
 */
export class CancelOrderByUltraCartOrderId {
    /**
     * Execute method to cancel an order by its UltraCart order ID
     */
    static async execute() {
        console.log(`--- ${this.name} ---`);

        try {
            // UltraCart order ID to cancel
            const ultracartOrderId = "DEMO-12345678980";

            // Attempt to cancel the order using a Promise wrapper
            const cancelResult = await new Promise((resolve, reject) => {
                channelPartnerApi.cancelOrderByUltraCartOrderId(
                    ultracartOrderId,
                    function (error, data) {
                        if (error) {
                            reject(error);
                        } else {
                            resolve(data);
                        }
                    }
                );
            });

            // Check if cancellation was unsuccessful
            if (!cancelResult.success) {
                cancelResult.cancel_errors?.forEach(error => {
                    console.log(error);
                });
            }
        } catch (ex) {
            // Log any exceptions that occur during the process
            console.error(ex);
        }
    }
}

<?php

ini_set('display_errors', 1);

/*

cancelOrderByUltraCartOrderId takes an UltraCart order id and attempts to 'cancel' the order.
UltraCart doesn't have a cancel order state, so this needs some explanation of what happens.

Here is the logic of the cancel process:
If the Order stage is [this] then do [that]:
    'Completed Order'       -> Error: "Order has already been completed."
    'Rejected'              -> Error: "Order has already been rejected."
    'Accounts Receivable'   -> Success: order is rejected.
    'Preordered'            -> Success: order is rejected.
    'Quote Sent'            -> Success: order is rejected.
    'Quote Requested'       -> Success: order is rejected.

The remaining stages are Fraud Review and Shipping Department.  Orders in these stages have already completed payment.
From this point, complex logic determines if the order has already shipped, or is queued to ship in a way that cannot be canceled.
Here is the logic for those stages, but the gist of it all is this:  If you receive any of the errors below, the order has progressed past a point where it can be canceled.
SHIPPING LOGIC:
Iterate through each item and consider it's shipping status:
    Item has already been transmitted to fulfillment center (contains a transmitted dts) -> Error: "The order has already had an item that has been transmitted to the distribution center."
    Does item DC (distribution center) have a transmission mechanism configured?
        YES -> Does the transmission have schedules? If NO -> Error: "The distribution center does not have any schedules so it would be an immediate transmission."
        NO -> Error: "Cant tell if we can cancel because the DC doesnt have a transport configured."

If the above logic completes without errors, the following conditions must be met:
Order has DC activity records.  If NO -> Error: "There is no activity in the DC queue when there should be."
There must be at least 5 minutes before the next DC transmission. If NO -> Error: "Activity record is not at least 5 minutes away so we need to bail."

At this point, the order will be canceled with the following activity:
1) Distribution Center activity is cleared
2) The order is refunded.  If the order is less than 24 hours old, a void is attempted instead.


Other Possible Errors:
System errors -> "Internal error.  Please contact UltraCart Support."
Order does not exist -> "Invalid order ID specified."
During refunding, original transaction could not be found -> "Unable to find original transaction on the order."
During refunding, original transaction was found, but transaction id could not be found -> "Unable to locate original transaction reference number."
During refunding, PayPal was used by no longer configured -> "PayPal is no longer configured on your account to refund against."
Gateway does not support refunds -> [GatewayName] does not support refunds at this time.

 */


use ultracart\v2\api\ChannelPartnerApi;
use ultracart\v2\ApiException;

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

$channel_partner_api = ChannelPartnerApi::usingApiKey(Constants::CHANNEL_PARTNER_API_KEY);

$ultracart_order_id = 'DEMO-12345678980';
try {
    $cancel_result = $channel_partner_api->cancelOrderByUltraCartOrderId($ultracart_order_id);
    if(!$cancel_result->getSuccess()){
        $errors = $cancel_result->getCancelErrors();
        foreach ($errors as $error){
            echo $error . "\n";
        }
    }

} catch (ApiException $e) {
    var_dump($e);  // Dumps all exception information
}


"""
Deletes a ChannelPartnerShiptoPreference. These preferences are used by EDI channel partners to automatically
apply return policies and add additional free items to EDI orders based on the EDI code that is present.

Success will return a status code 204 (No content)

Possible Errors:
Attempting to interact with a channel partner other than the one tied to your API Key:
    "Invalid channel_partner_oid specified. Your REST API key may only interact with channel_partner_oid: 12345"
Supply a bad preference oid: "Invalid channel_partner_ship_to_preference_oid specified."
"""

from ultracart.apis import ChannelPartnerApi
from samples import channel_partner_api_client

channel_partner_api = ChannelPartnerApi(channel_partner_api_client())

# you will usually get this by calling get_channel_partner_ship_to_preferences()
channel_partner_shipto_preference_oid = 67890
channel_partner_oid = 12345

channel_partner_api.delete_channel_partner_ship_to_preference(channel_partner_oid, channel_partner_shipto_preference_oid)
require 'ultracart_api'
require_relative '../constants'

# cancelOrderByUltraCartOrderId takes an UltraCart order id and attempts to 'cancel' the order.
# UltraCart doesn't have a cancel order state, so this needs some explanation of what happens.
#
# Here is the logic of the cancel process:
# If the Order stage is [this] then do [that]:
#     'Completed Order'       -> Error: "Order has already been completed."
#     'Rejected'              -> Error: "Order has already been rejected."
#     'Accounts Receivable'   -> Success: order is rejected.
#     'Preordered'            -> Success: order is rejected.
#     'Quote Sent'            -> Success: order is rejected.
#     'Quote Requested'       -> Success: order is rejected.
#
# The remaining stages are Fraud Review and Shipping Department.  Orders in these stages have already completed payment.
# From this point, complex logic determines if the order has already shipped, or is queued to ship in a way that cannot be canceled.
# Here is the logic for those stages, but the gist of it all is this:  If you receive any of the errors below, the order has progressed past a point where it can be canceled.
# SHIPPING LOGIC:
# Iterate through each item and consider it's shipping status:
#     Item has already been transmitted to fulfillment center (contains a transmitted dts) -> Error: "The order has already had an item that has been transmitted to the distribution center."
#     Does item DC (distribution center) have a transmission mechanism configured?
#         YES -> Does the transmission have schedules? If NO -> Error: "The distribution center does not have any schedules so it would be an immediate transmission."
#         NO -> Error: "Cant tell if we can cancel because the DC doesnt have a transport configured."
#
# If the above logic completes without errors, the following conditions must be met:
# Order has DC activity records.  If NO -> Error: "There is no activity in the DC queue when there should be."
# There must be at least 5 minutes before the next DC transmission. If NO -> Error: "Activity record is not at least 5 minutes away so we need to bail."
#
# At this point, the order will be canceled with the following activity:
# 1) Distribution Center activity is cleared
# 2) The order is refunded.  If the order is less than 24 hours old, a void is attempted instead.
#
#
# Other Possible Errors:
# System errors -> "Internal error.  Please contact UltraCart Support."
# Order does not exist -> "Invalid order ID specified."
# During refunding, original transaction could not be found -> "Unable to find original transaction on the order."
# During refunding, original transaction was found, but transaction id could not be found -> "Unable to locate original transaction reference number."
# During refunding, PayPal was used by no longer configured -> "PayPal is no longer configured on your account to refund against."
# Gateway does not support refunds -> [GatewayName] does not support refunds at this time.

channel_partner_api = UltracartClient::ChannelPartnerApi.new_using_api_key(Constants::CHANNEL_PARTNER_API_KEY)

ultracart_order_id = 'DEMO-12345678980'
begin
  cancel_result = channel_partner_api.cancel_order_by_ultra_cart_order_id(ultracart_order_id)
  unless cancel_result.success
    cancel_result.cancel_errors.each do |error|
      puts error
    end
  end
rescue UltracartClient::ApiError => e
  puts e.inspect  # Dumps all exception information
end
import {channelPartnerApi} from '../api';

/**
 * cancelOrderByUltraCartOrderId takes an UltraCart order id and attempts to 'cancel' the order.
 * UltraCart doesn't have a cancel order state, so this needs some explanation of what happens.
 *
 * Here is the logic of the cancel process:
 * If the Order stage is [this] then do [that]:
 *     'Completed Order'       -> Error: "Order has already been completed."
 *     'Rejected'              -> Error: "Order has already been rejected."
 *     'Accounts Receivable'   -> Success: order is rejected.
 *     'Preordered'            -> Success: order is rejected.
 *     'Quote Sent'            -> Success: order is rejected.
 *     'Quote Requested'       -> Success: order is rejected.
 *
 * The remaining stages are Fraud Review and Shipping Department.  Orders in these stages have already completed payment.
 * From this point, complex logic determines if the order has already shipped, or is queued to ship in a way that cannot be canceled.
 * Here is the logic for those stages, but the gist of it all is this:  If you receive any of the errors below, the order has progressed past a point where it can be canceled.
 * SHIPPING LOGIC:
 * Iterate through each item and consider it's shipping status:
 *     Item has already been transmitted to fulfillment center (contains a transmitted dts) -> Error: "The order has already had an item that has been transmitted to the distribution center."
 *     Does item DC (distribution center) have a transmission mechanism configured?
 *         YES -> Does the transmission have schedules? If NO -> Error: "The distribution center does not have any schedules so it would be an immediate transmission."
 *         NO -> Error: "Cant tell if we can cancel because the DC doesnt have a transport configured."
 *
 * If the above logic completes without errors, the following conditions must be met:
 * Order has DC activity records.  If NO -> Error: "There is no activity in the DC queue when there should be."
 * There must be at least 5 minutes before the next DC transmission. If NO -> Error: "Activity record is not at least 5 minutes away so we need to bail."
 *
 * At this point, the order will be canceled with the following activity:
 * 1) Distribution Center activity is cleared
 * 2) The order is refunded.  If the order is less than 24 hours old, a void is attempted instead.
 *
 * Other Possible Errors:
 * System errors -> "Internal error.  Please contact UltraCart Support."
 * Order does not exist -> "Invalid order ID specified."
 * During refunding, original transaction could not be found -> "Unable to find original transaction on the order."
 * During refunding, original transaction was found, but transaction id could not be found -> "Unable to locate original transaction reference number."
 * During refunding, PayPal was used by no longer configured -> "PayPal is no longer configured on your account to refund against."
 * Gateway does not support refunds -> [GatewayName] does not support refunds at this time.
 */
export class CancelOrderByUltraCartOrderId {
    /**
     * Execute method to cancel an order by its UltraCart order ID
     */
    public static async execute(): Promise<void> {
        console.log(`--- ${this.name} ---`);

        try {
            // UltraCart order ID to cancel
            const ultracartOrderId = "DEMO-12345678980";

            // Attempt to cancel the order
            const cancelResult = await channelPartnerApi.cancelOrderByUltraCartOrderId({orderId: ultracartOrderId});

            // Check if cancellation was unsuccessful
            if (!cancelResult.success) {
                // Log each cancellation error
                cancelResult.cancel_errors?.forEach(error => {
                    console.log(error);
                });
            }
        } catch (ex) {
            // Log any exceptions that occur during the process
            console.error(ex);
        }
    }
}

Retrieve the channel partners configured on the account.

Permissions:
  • channel_partner_read

Produces: application/json
get
/channel_partner/channel_partners

Retrieve the channel partners configured on the account.

SDK Function Name: getChannelPartners

Responses
Status Code Reason Response Model
200
Successful response ChannelPartnersResponse
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.Reflection;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;

namespace SdkSample.channel_partner
{
    public class GetChannelPartners
    {
        /*
            Retrieves a list of all channel partners configured for this merchant.  If the API KEY used is tied to a specific
            Channel Partner, then the results will contain only that Channel Partner.
         */
        public static void Execute()
        {
            Console.WriteLine("--- " + MethodBase.GetCurrentMethod()?.DeclaringType?.Name + " ---");
            
            try
            {
                // Create channel partner API instance using API key
                ChannelPartnerApi channelPartnerApi = new ChannelPartnerApi(Constants.ChannelPartnerApiKey);
                var apiResponse = channelPartnerApi.GetChannelPartners();
                
                if (apiResponse.Error != null)
                {
                    Console.Error.WriteLine(apiResponse.Error.DeveloperMessage);
                    Console.Error.WriteLine(apiResponse.Error.UserMessage);
                    Environment.Exit(1);
                }
                
                var channelPartners = apiResponse.ChannelPartners;
                
                foreach (var channelPartner in channelPartners)
                {
                    Console.WriteLine(channelPartner);
                }
                
                Console.WriteLine($"Retrieved {channelPartners.Count} channel partners");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
                Console.WriteLine(ex.StackTrace);
            }
        }
    }
}
package channel_partner;

import com.ultracart.admin.v2.ChannelPartnerApi;
import com.ultracart.admin.v2.models.ChannelPartner;
import com.ultracart.admin.v2.models.ChannelPartnersResponse;

import java.util.List;

public class GetChannelPartners {
  /*
      Retrieves a list of all channel partners configured for this merchant.  If the API KEY used is tied to a specific
      Channel Partner, then the results will contain only that Channel Partner.
   */
  public static void execute() {
    System.out.println("--- GetChannelPartners ---");

    try {
      // Create channel partner API instance using API key
      ChannelPartnerApi channelPartnerApi = new ChannelPartnerApi(common.Constants.CHANNEL_PARTNER_API_KEY);
      ChannelPartnersResponse apiResponse = channelPartnerApi.getChannelPartners();

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

      List<ChannelPartner> channelPartners = apiResponse.getChannelPartners();

      for (ChannelPartner channelPartner : channelPartners) {
        System.out.println(channelPartner);
      }

      System.out.println("Retrieved " + channelPartners.size() + " channel partners");
    } catch (Exception ex) {
      System.out.println("Error: " + ex.getMessage());
      ex.printStackTrace();
    }
  }
}
import { channelPartnerApi } from '../api.js';

/**
 * Retrieves a list of all channel partners configured for this merchant.
 * If the API KEY used is tied to a specific Channel Partner, then the results
 * will contain only that Channel Partner.
 */
export class GetChannelPartners {
    /**
     * Execute method to retrieve channel partners
     */
    static async execute() {
        console.log(`--- ${this.name} ---`);

        try {
            // Retrieve channel partners
            const apiResponse = await new Promise((resolve, reject) => {
                channelPartnerApi.getChannelPartners(function (error, data, response) {
                    if (error) {
                        reject(error);
                    } else {
                        resolve(data);
                    }
                });
            });

            // Check for any errors in the API response
            if (apiResponse.error) {
                console.error(apiResponse.error.developer_message);
                console.error(apiResponse.error.user_message);
                process.exit(1);
            }

            // Extract channel partners
            const channelPartners = apiResponse.channelPartners || [];

            // Log each channel partner
            channelPartners.forEach(channelPartner => {
                console.log(channelPartner);
            });

            // Log total number of channel partners
            console.log(`Retrieved ${channelPartners.length} channel partners`);

        } catch (ex) {
            // Log details of the error
            if (ex instanceof Error) {
                console.error(`Error: ${ex.message}`);
                console.error(ex.stack);
            } else {
                console.error("An unknown error occurred");
            }
        }
    }
}

<?php

ini_set('display_errors', 1);

/*
    Retrieves a list of all channel partners configured for this merchant.  If the API KEY used is tied to a specific
    Channel Partner, then the results will contain only that Channel Partner.
 */


use ultracart\v2\api\ChannelPartnerApi;

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


$channel_partner_api = ChannelPartnerApi::usingApiKey(Constants::CHANNEL_PARTNER_API_KEY);
$api_response = $channel_partner_api->getChannelPartners();


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

$channel_partners = $api_response->getChannelPartners();

echo '<html lang="en"><body><pre>';
foreach ($channel_partners as $channel_partner) {
    var_dump($channel_partner);
}
echo '</pre></body></html>';

from ultracart.apis import ChannelPartnerApi
from samples import channel_partner_api_client

"""
Retrieves a list of all channel partners configured for this merchant. If the API KEY used is tied to a specific
Channel Partner, then the results will contain only that Channel Partner.
"""

channel_partner_api = ChannelPartnerApi(channel_partner_api_client())
api_response = channel_partner_api.get_channel_partners()

if api_response.error is not None:
    print(api_response.error.developer_message)
    print(api_response.error.user_message)
    exit()

channel_partners = api_response.channel_partners

for channel_partner in channel_partners:
    print(channel_partner)
# Retrieves a list of all channel partners configured for this merchant.  If the API KEY used is tied to a specific
# Channel Partner, then the results will contain only that Channel Partner.

require 'ultracart_api'
require_relative '../constants'

channel_partner_api = UltracartClient::ChannelPartnerApi.new_using_api_key(Constants::CHANNEL_PARTNER_API_KEY)
api_response = channel_partner_api.get_channel_partners

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

channel_partners = api_response.channel_partners

channel_partners.each do |channel_partner|
  p channel_partner
end
import {
    ChannelPartner,
    ChannelPartnersResponse
} from 'ultracart_rest_api_v2_typescript';
import { channelPartnerApi } from '../api';

/**
 * Retrieves a list of all channel partners configured for this merchant.
 * If the API KEY used is tied to a specific Channel Partner, then the results
 * will contain only that Channel Partner.
 */
export class GetChannelPartners {
    /**
     * Execute method to retrieve channel partners
     */
    public static async execute(): Promise<void> {
        console.log(`--- ${this.name} ---`);

        try {
            // Retrieve channel partners
            const apiResponse: ChannelPartnersResponse = await channelPartnerApi.getChannelPartners();

            // Check for any errors in the API response
            if (apiResponse.error) {
                console.error(apiResponse.error.developer_message);
                console.error(apiResponse.error.user_message);
                process.exit(1);
            }

            // Extract channel partners
            const channelPartners: ChannelPartner[] = apiResponse.channelPartners || [];

            // Log each channel partner
            channelPartners.forEach(channelPartner => {
                console.log(channelPartner);
            });

            // Log total number of channel partners
            console.log(`Retrieved ${channelPartners.length} channel partners`);
        } catch (ex: unknown) {
            // Type the error as unknown and log details
            if (ex instanceof Error) {
                console.error(`Error: ${ex.message}`);
                console.error(ex.stack);
            } else {
                console.error("An unknown error occurred");
            }
        }
    }
}

Retrieve reject and refund reason codes.

Permissions:
  • channel_partner_read

Produces: application/json
get
/channel_partner/channel_partners/{channel_partner_oid}/reason_codes

Retrieve reject and refund reason codes.

SDK Function Name: getChannelPartnerReasonCodes

Parameters
Parameter Description Location Data Type Required
channel_partner_oid path integer (int32) optional
Responses
Status Code Reason Response Model
200
Successful response ChanelPartnerReasonCodesResponse
400
Bad Request 400
401
Unauthorized 401
410
Authorized Application Disabled 410
429
Too Many Requests 429
500
Server Side 500

Retrieve the ship to preferences associated with the channel partner.

Permissions:
  • channel_partner_read

Produces: application/json
get
/channel_partner/channel_partners/{channel_partner_oid}/ship_to_preferences

Retrieve the ship to preferences associated with the channel partner.

SDK Function Name: getChannelPartnerShipToPreferences

Parameters
Parameter Description Location Data Type Required
channel_partner_oid path integer (int32) optional
Responses
Status Code Reason Response Model
200
Successful response ChannelPartnerShipToPreferencesResponse
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.Reflection;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;

namespace SdkSample.channel_partner
{
    public class GetChannelPartnerShipToPreferences
    {
        /*
         Retrieves all shipto preferences for a channel partner.
         These preferences are used by EDI channel partners to automatically
         apply return policies and add additional free items to EDI orders based on the EDI code that is present.

         Possible Errors:
         Attempting to interact with a channel partner other than the one tied to your API Key:
            "Invalid channel_partner_oid specified.  Your REST API key may only interact with channel_partner_oid: 12345"
         Supplying a bad channel partner oid: "Invalid channel_partner_oid specified."
        */
        public static void Execute()
        {
            Console.WriteLine("--- " + MethodBase.GetCurrentMethod()?.DeclaringType?.Name + " ---");
            
            try
            {
                // Create channel partner API instance using API key
                ChannelPartnerApi channelPartnerApi = new ChannelPartnerApi(Constants.ChannelPartnerApiKey);
                
                int channelPartnerOid = 12345;
                var apiResponse = channelPartnerApi.GetChannelPartnerShipToPreferences(channelPartnerOid);
                
                if (apiResponse.Error != null)
                {
                    Console.Error.WriteLine(apiResponse.Error.DeveloperMessage);
                    Console.Error.WriteLine(apiResponse.Error.UserMessage);
                    Environment.Exit(1);
                }
                
                var preferences = apiResponse.ShipToPreferences;
                
                foreach (var preference in preferences)
                {
                    Console.WriteLine(preference);
                }
                
                Console.WriteLine($"Retrieved {preferences.Count} ship to preferences");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
                Console.WriteLine(ex.StackTrace);
            }
        }
    }
}
package channel_partner;

import com.ultracart.admin.v2.ChannelPartnerApi;
import com.ultracart.admin.v2.models.ChannelPartnerShipToPreference;
import com.ultracart.admin.v2.models.ChannelPartnerShipToPreferencesResponse;

import java.util.List;

public class GetChannelPartnerShipToPreferences {
  /*
   Retrieves all shipto preferences for a channel partner.
   These preferences are used by EDI channel partners to automatically
   apply return policies and add additional free items to EDI orders based on the EDI code that is present.

   Possible Errors:
   Attempting to interact with a channel partner other than the one tied to your API Key:
      "Invalid channel_partner_oid specified.  Your REST API key may only interact with channel_partner_oid: 12345"
   Supplying a bad channel partner oid: "Invalid channel_partner_oid specified."
  */
  public static void execute() {
    System.out.println("--- GetChannelPartnerShipToPreferences ---");

    try {
      // Create channel partner API instance using API key
      ChannelPartnerApi channelPartnerApi = new ChannelPartnerApi(common.Constants.CHANNEL_PARTNER_API_KEY);

      int channelPartnerOid = 12345;
      ChannelPartnerShipToPreferencesResponse apiResponse = channelPartnerApi.getChannelPartnerShipToPreferences(channelPartnerOid);

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

      List<ChannelPartnerShipToPreference> preferences = apiResponse.getShipToPreferences();

      for (ChannelPartnerShipToPreference preference : preferences) {
        System.out.println(preference);
      }

      System.out.println("Retrieved " + preferences.size() + " ship to preferences");
    } catch (Exception ex) {
      System.out.println("Error: " + ex.getMessage());
      ex.printStackTrace();
    }
  }
}
import {channelPartnerApi} from '../api.js';

/**
 * Retrieves all shipto preferences for a channel partner.
 * These preferences are used by EDI channel partners to automatically
 * apply return policies and add additional free items to EDI orders based on the EDI code that is present.
 *
 * Possible Errors:
 * Attempting to interact with a channel partner other than the one tied to your API Key:
 *    "Invalid channel_partner_oid specified.  Your REST API key may only interact with channel_partner_oid: 12345"
 * Supplying a bad channel partner oid: "Invalid channel_partner_oid specified."
 */
export async function execute() {
    console.log(`--- ${execute.name} ---`);

    try {
        // Channel partner OID
        const channelPartnerOid = 12345;

        // Retrieve channel partner shipto preferences
        const apiResponse = await new Promise((resolve, reject) => {
            channelPartnerApi.getChannelPartnerShipToPreferences(channelPartnerOid, function (error, data) {
                if (error) {
                    reject(error);
                } else {
                    resolve(data);
                }
            });
        });

        // Check for errors in the API response
        if (apiResponse.error) {
            const error = apiResponse.error;
            console.error(error.developer_message);
            console.error(error.user_message);
            process.exit(1);
        }

        // Extract preferences
        const preferences = apiResponse.shipToPreferences;

        // Safely iterate and log preferences
        if (preferences) {
            preferences.forEach(preference => {
                console.log(preference);
            });

            console.log(`Retrieved ${preferences.length} ship to preferences`);
        } else {
            console.log('No ship to preferences found');
        }
    } catch (ex) {
        // Handle any unexpected errors
        const error = ex instanceof Error ? ex : new Error('Unknown error');
        console.error(`Error: ${error.message}`);
        console.error(error.stack);
    }
}

// Optional: If you want to run this directly
if (require.main === module) {
    execute().catch(console.error);
}

<?php

ini_set('display_errors', 1);

/*
 Retrieves all shipto preferences for a channel partner.
 These preferences are used by EDI channel partners to automatically
 apply return policies and add additional free items to EDI orders based on the EDI code that is present.

 Possible Errors:
 Attempting to interact with a channel partner other than the one tied to your API Key:
    "Invalid channel_partner_oid specified.  Your REST API key may only interact with channel_partner_oid: 12345"
 Supplying a bad channel partner oid: "Invalid channel_partner_oid specified."

 */


use ultracart\v2\api\ChannelPartnerApi;

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


$channel_partner_api = ChannelPartnerApi::usingApiKey(Constants::CHANNEL_PARTNER_API_KEY);
$channel_partner_oid = 12345;
$api_response = $channel_partner_api->getChannelPartnerShipToPreferences($channel_partner_oid);


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

$preferences = $api_response->getShipToPreferences();

echo '<html lang="en"><body><pre>';
foreach ($preferences as $preference) {
    var_dump($preference);
}
echo '</pre></body></html>';

from ultracart.apis import ChannelPartnerApi
from samples import channel_partner_api_client

"""
Retrieves all shipto preferences for a channel partner.
These preferences are used by EDI channel partners to automatically
apply return policies and add additional free items to EDI orders based on the EDI code that is present.

Possible Errors:
Attempting to interact with a channel partner other than the one tied to your API Key:
    "Invalid channel_partner_oid specified.  Your REST API key may only interact with channel_partner_oid: 12345"
Supplying a bad channel partner oid: "Invalid channel_partner_oid specified."
"""

channel_partner_api = ChannelPartnerApi(channel_partner_api_client())
channel_partner_oid = 12345
api_response = channel_partner_api.get_channel_partner_ship_to_preferences(channel_partner_oid)

if api_response.error is not None:
    print(api_response.error.developer_message)
    print(api_response.error.user_message)
    exit()

preferences = api_response.ship_to_preferences

for preference in preferences:
    print(preference)
require 'ultracart_api'
require_relative '../constants'

# Retrieves all shipto preferences for a channel partner.
# These preferences are used by EDI channel partners to automatically
# apply return policies and add additional free items to EDI orders based on the EDI code that is present.
#
# Possible Errors:
# Attempting to interact with a channel partner other than the one tied to your API Key:
#    "Invalid channel_partner_oid specified.  Your REST API key may only interact with channel_partner_oid: 12345"
# Supplying a bad channel partner oid: "Invalid channel_partner_oid specified."

channel_partner_api = UltracartClient::ChannelPartnerApi.new_using_api_key(Constants::CHANNEL_PARTNER_API_KEY)
channel_partner_oid = 12345
api_response = channel_partner_api.get_channel_partner_ship_to_preferences(channel_partner_oid)

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

preferences = api_response.ship_to_preferences

preferences.each do |preference|
  p preference
end
import {
    ChannelPartnerShipToPreference, ModelError
} from 'ultracart_rest_api_v2_typescript';
import { channelPartnerApi } from '../api';

/**
 * Retrieves all shipto preferences for a channel partner.
 * These preferences are used by EDI channel partners to automatically
 * apply return policies and add additional free items to EDI orders based on the EDI code that is present.
 *
 * Possible Errors:
 * Attempting to interact with a channel partner other than the one tied to your API Key:
 *    "Invalid channel_partner_oid specified.  Your REST API key may only interact with channel_partner_oid: 12345"
 * Supplying a bad channel partner oid: "Invalid channel_partner_oid specified."
 */
export async function execute(): Promise<void> {
    console.log(`--- ${execute.name} ---`);

    try {
        // Channel partner OID
        const channelPartnerOid: number = 12345;

        // Retrieve channel partner shipto preferences
        const apiResponse = await channelPartnerApi.getChannelPartnerShipToPreferences({channelPartnerOid});

        // Check for errors in the API response
        if (apiResponse.error) {
            const error: ModelError = apiResponse.error;
            console.error(error.developer_message);
            console.error(error.user_message);
            process.exit(1);
        }

        // Extract preferences
        const preferences: ChannelPartnerShipToPreference[] | undefined = apiResponse.shipToPreferences;

        // Safely iterate and log preferences
        if (preferences) {
            preferences.forEach(preference => {
                console.log(preference);
            });

            console.log(`Retrieved ${preferences.length} ship to preferences`);
        } else {
            console.log('No ship to preferences found');
        }
    }
    catch (ex: unknown) {
        // Handle any unexpected errors
        const error = ex as Error;
        console.error(`Error: ${error.message}`);
        console.error(error.stack);
    }
}

// Optional: If you want to run this directly
if (require.main === module) {
    execute().catch(console.error);
}

Insert a ship to preference record for the channel partner.

Permissions:
  • channel_partner_write

Produces: application/json
post
/channel_partner/channel_partners/{channel_partner_oid}/ship_to_preferences

Insert a ship to preference record for the channel partner.

SDK Function Name: insertChannelPartnerShipToPreference

Parameters
Parameter Description Location Data Type Required
channel_partner_oid path integer (int32) optional
ship_to_preference Ship to preference to create body ChannelPartnerShipToPreference required
Responses
Status Code Reason Response Model
200
Successful response ChannelPartnerShipToPreferenceResponse
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.Reflection;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;

namespace SdkSample.channel_partner
{
    public class InsertChannelPartnerShipToPreference
    {
        /*
         Inserts a channel partner shipto preference for a channel partner.
         These preferences are used by EDI channel partners to automatically
         apply return policies and add additional free items to EDI orders based on the EDI code that is present.

         Possible Errors:
         Attempting to interact with a channel partner other than the one tied to your API Key:
            "Invalid channel_partner_oid specified.  Your REST API key may only interact with channel_partner_oid: 12345"
         Supplying a bad channel partner oid: "Invalid channel_partner_oid specified."
        */
        public static void Execute()
        {
            Console.WriteLine("--- " + MethodBase.GetCurrentMethod()?.DeclaringType?.Name + " ---");
            
            try
            {
                // Create channel partner API instance using API key
                ChannelPartnerApi channelPartnerApi = new ChannelPartnerApi(Constants.ChannelPartnerApiKey);
                
                int channelPartnerOid = 12345;
                
                ChannelPartnerShipToPreference preference = new ChannelPartnerShipToPreference();
                preference.ChannelPartnerOid = channelPartnerOid;
                preference.ShipToEdiCode = "EDI_CODE_HERE";
                preference.ReturnPolicy = "This is some return policy text that will be printed on the packing slip.";
                preference.AdditionalKitComponentItemIds = new List<string> { "ITEM_ID1", "ITEM_ID2", "ITEM_ID3" };
                preference.Description = "This is a merchant friendly description to help me remember what the above setting are.";
                
                var apiResponse = channelPartnerApi.InsertChannelPartnerShipToPreference(channelPartnerOid, preference);
                
                if (apiResponse.Error != null)
                {
                    Console.Error.WriteLine(apiResponse.Error.DeveloperMessage);
                    Console.Error.WriteLine(apiResponse.Error.UserMessage);
                    Environment.Exit(1);
                }
                
                var insertedPreference = apiResponse.ShipToPreference;
                
                // This should equal what you submitted.
                Console.WriteLine(insertedPreference);
                Console.WriteLine("Ship to preference inserted successfully");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
                Console.WriteLine(ex.StackTrace);
            }
        }
    }
}
package channel_partner;

import com.ultracart.admin.v2.ChannelPartnerApi;
import com.ultracart.admin.v2.models.ChannelPartnerShipToPreference;
import com.ultracart.admin.v2.models.ChannelPartnerShipToPreferenceResponse;

import java.util.ArrayList;

public class InsertChannelPartnerShipToPreference {
    /*
     Inserts a channel partner shipto preference for a channel partner.
     These preferences are used by EDI channel partners to automatically
     apply return policies and add additional free items to EDI orders based on the EDI code that is present.

     Possible Errors:
     Attempting to interact with a channel partner other than the one tied to your API Key:
        "Invalid channel_partner_oid specified.  Your REST API key may only interact with channel_partner_oid: 12345"
     Supplying a bad channel partner oid: "Invalid channel_partner_oid specified."
    */
    public static void execute() {
        System.out.println("--- InsertChannelPartnerShipToPreference ---");

        try {
            // Create channel partner API instance using API key
            ChannelPartnerApi channelPartnerApi = new ChannelPartnerApi(common.Constants.CHANNEL_PARTNER_API_KEY);

            int channelPartnerOid = 12345;

            ChannelPartnerShipToPreference preference = new ChannelPartnerShipToPreference();
            preference.setChannelPartnerOid(channelPartnerOid);
            preference.setShipToEdiCode("EDI_CODE_HERE");
            preference.setReturnPolicy("This is some return policy text that will be printed on the packing slip.");

            ArrayList<String> additionalKitComponentItemIds = new ArrayList<String>();
            additionalKitComponentItemIds.add("ITEM_ID1");
            additionalKitComponentItemIds.add("ITEM_ID2");
            additionalKitComponentItemIds.add("ITEM_ID3");
            preference.setAdditionalKitComponentItemIds(additionalKitComponentItemIds);

            preference.setDescription("This is a merchant friendly description to help me remember what the above setting are.");

            ChannelPartnerShipToPreferenceResponse apiResponse = channelPartnerApi.insertChannelPartnerShipToPreference(channelPartnerOid, preference);

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

            ChannelPartnerShipToPreference insertedPreference = apiResponse.getShipToPreference();

            // This should equal what you submitted.
            System.out.println(insertedPreference);
            System.out.println("Ship to preference inserted successfully");
        }
        catch (Exception ex) {
            System.out.println("Error: " + ex.getMessage());
            ex.printStackTrace();
        }
    }
}
import {channelPartnerApi} from '../api.js';

/**
 * Inserts a channel partner shipto preference for a channel partner.
 * These preferences are used by EDI channel partners to automatically
 * apply return policies and add additional free items to EDI orders based on the EDI code that is present.
 *
 * Possible Errors:
 * Attempting to interact with a channel partner other than the one tied to your API Key:
 *    "Invalid channel_partner_oid specified.  Your REST API key may only interact with channel_partner_oid: 12345"
 * Supplying a bad channel partner oid: "Invalid channel_partner_oid specified."
 */
export async function execute() {
    console.log(`--- ${execute.name} ---`);

    try {
        // Channel partner OID
        const channelPartnerOid = 12345;

        // Create ship to preference
        const preference = {
            channel_partner_oid: channelPartnerOid,
            ship_to_edi_code: "EDI_CODE_HERE",
            return_policy: "This is some return policy text that will be printed on the packing slip.",
            additional_kit_component_item_ids: ["ITEM_ID1", "ITEM_ID2", "ITEM_ID3"],
            description: "This is a merchant friendly description to help me remember what the above setting are."
        };

        // Insert the ship to preference
        const apiResponse = await new Promise((resolve, reject) => {
            channelPartnerApi.insertChannelPartnerShipToPreference(
                channelPartnerOid, preference,
                function (error, data) {
                    if (error) {
                        reject(error);
                    } else {
                        resolve(data);
                    }
                }
            );
        });

        // Check for errors in the API response
        if (apiResponse.error) {
            const error = apiResponse.error;
            console.error(error.developer_message);
            console.error(error.user_message);
            process.exit(1);
        }

        // Extract and log the inserted preference
        const insertedPreference = apiResponse.ship_to_preference;

        // This should equal what you submitted.
        console.log(insertedPreference);
        console.log("Ship to preference inserted successfully");
    } catch (ex) {
        // Handle any unexpected errors
        const error = ex instanceof Error ? ex : new Error('Unknown error');
        console.error(`Error: ${error.message}`);
        console.error(error.stack);
    }
}

// Optional: If you want to run this directly
if (require.main === module) {
    execute().catch(console.error);
}

<?php

ini_set('display_errors', 1);

/*
 Inserts a channel partner shipto preference for a channel partner.
 These preferences are used by EDI channel partners to automatically
 apply return policies and add additional free items to EDI orders based on the EDI code that is present.

 Possible Errors:
 Attempting to interact with a channel partner other than the one tied to your API Key:
    "Invalid channel_partner_oid specified.  Your REST API key may only interact with channel_partner_oid: 12345"
 Supplying a bad channel partner oid: "Invalid channel_partner_oid specified."

 */


use ultracart\v2\api\ChannelPartnerApi;
use ultracart\v2\models\ChannelPartnerShipToPreference;

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


$channel_partner_api = ChannelPartnerApi::usingApiKey(Constants::CHANNEL_PARTNER_API_KEY);
$channel_partner_oid = 12345;

$preference = new ChannelPartnerShipToPreference();
$preference->setChannelPartnerOid($channel_partner_oid);
$preference->setShipToEdiCode('EDI_CODE_HERE');
$preference->setReturnPolicy("This is some return policy text that will be printed on the packing slip.");
$preference->setAdditionalKitComponentItemIds(['ITEM_ID1', 'ITEM_ID2', 'ITEM_ID3']);
$preference->setDescription("This is a merchant friendly description to help me remember what the above setting are.");

$api_response = $channel_partner_api->insertChannelPartnerShipToPreference($channel_partner_oid, $preference);


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

$inserted_preference = $api_response->getShipToPreference();

echo '<html lang="en"><body><pre>';
// This should equal what you submitted.
var_dump($inserted_preference);
echo '</pre></body></html>';

from ultracart.apis import ChannelPartnerApi
from ultracart.models import ChannelPartnerShipToPreference
from samples import channel_partner_api_client

# Initialize API
channel_partner_api = ChannelPartnerApi(channel_partner_api_client())
channel_partner_oid = 12345

# Create preference object
preference = ChannelPartnerShipToPreference()
preference.channel_partner_oid = channel_partner_oid
preference.ship_to_edi_code = 'EDI_CODE_HERE'
preference.return_policy = "This is some return policy text that will be printed on the packing slip."
preference.additional_kit_component_item_ids = ['ITEM_ID1', 'ITEM_ID2', 'ITEM_ID3']
preference.description = "This is a merchant friendly description to help me remember what the above setting are."

# Insert the preference
api_response = channel_partner_api.insert_channel_partner_ship_to_preference(channel_partner_oid, preference)

if api_response.error is not None:
    print(api_response.error.developer_message)
    print(api_response.error.user_message)
    exit()

inserted_preference = api_response.ship_to_preference
print(inserted_preference)
# Inserts a channel partner shipto preference for a channel partner.
# These preferences are used by EDI channel partners to automatically
# apply return policies and add additional free items to EDI orders based on the EDI code that is present.
#
# Possible Errors:
# Attempting to interact with a channel partner other than the one tied to your API Key:
#    "Invalid channel_partner_oid specified.  Your REST API key may only interact with channel_partner_oid: 12345"
# Supplying a bad channel partner oid: "Invalid channel_partner_oid specified."

require 'ultracart_api'
require_relative '../constants'

channel_partner_api = UltracartClient::ChannelPartnerApi.new_using_api_key(Constants::CHANNEL_PARTNER_API_KEY)
channel_partner_oid = 12345

preference = UltracartClient::ChannelPartnerShipToPreference.new
preference.channel_partner_oid = channel_partner_oid
preference.ship_to_edi_code = 'EDI_CODE_HERE'
preference.return_policy = "This is some return policy text that will be printed on the packing slip."
preference.additional_kit_component_item_ids = ['ITEM_ID1', 'ITEM_ID2', 'ITEM_ID3']
preference.description = "This is a merchant friendly description to help me remember what the above setting are."

api_response = channel_partner_api.insert_channel_partner_ship_to_preference(channel_partner_oid, preference)

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

inserted_preference = api_response.ship_to_preference

# This should equal what you submitted.
p inserted_preference
import {
    ChannelPartnerShipToPreference, ModelError
} from 'ultracart_rest_api_v2_typescript';
import {channelPartnerApi} from '../api';

/**
 * Inserts a channel partner shipto preference for a channel partner.
 * These preferences are used by EDI channel partners to automatically
 * apply return policies and add additional free items to EDI orders based on the EDI code that is present.
 *
 * Possible Errors:
 * Attempting to interact with a channel partner other than the one tied to your API Key:
 *    "Invalid channel_partner_oid specified.  Your REST API key may only interact with channel_partner_oid: 12345"
 * Supplying a bad channel partner oid: "Invalid channel_partner_oid specified."
 */
export async function execute(): Promise<void> {
    console.log(`--- ${execute.name} ---`);

    try {
        // Channel partner OID
        const channelPartnerOid: number = 12345;

        // Create ship to preference
        const preference: ChannelPartnerShipToPreference = {
            channel_partner_oid: channelPartnerOid,
            ship_to_edi_code: "EDI_CODE_HERE",
            return_policy: "This is some return policy text that will be printed on the packing slip.",
            additional_kit_component_item_ids: ["ITEM_ID1", "ITEM_ID2", "ITEM_ID3"],
            description: "This is a merchant friendly description to help me remember what the above setting are."
        };

        // Insert the ship to preference
        const apiResponse = await channelPartnerApi.insertChannelPartnerShipToPreference({
            channelPartnerOid,
            shipToPreference: preference
        });

        // Check for errors in the API response
        if (apiResponse.error) {
            const error: ModelError = apiResponse.error;
            console.error(error.developer_message);
            console.error(error.user_message);
            process.exit(1);
        }

        // Extract and log the inserted preference
        const insertedPreference = apiResponse.ship_to_preference;

        // This should equal what you submitted.
        console.log(insertedPreference);
        console.log("Ship to preference inserted successfully");
    } catch (ex: unknown) {
        // Handle any unexpected errors
        const error = ex as Error;
        console.error(`Error: ${error.message}`);
        console.error(error.stack);
    }
}

// Optional: If you want to run this directly
if (require.main === module) {
    execute().catch(console.error);
}

Delete a ship to preference record for the channel partner.

Permissions:
  • channel_partner_write

Produces: application/json
delete
/channel_partner/channel_partners/{channel_partner_oid}/ship_to_preferences/{channel_partner_ship_to_preference_oid}

Delete a ship to preference record for the channel partner.

SDK Function Name: deleteChannelPartnerShipToPreference

Parameters
Parameter Description Location Data Type Required
channel_partner_oid path integer (int32) optional
channel_partner_ship_to_preference_oid path integer (int32) optional
Responses
Status Code Reason Response Model
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.Reflection;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;

namespace SdkSample.channel_partner
{
    public class DeleteChannelPartnerShipToPreference
    {
        /*
         Deletes a ChannelPartnerShiptoPreference.  These preferences are used by EDI channel partners to automatically
         apply return policies and add additional free items to EDI orders based on the EDI code that is present.

         Success will return a status code 204 (No content)

         Possible Errors:
         Attempting to interact with a channel partner other than the one tied to your API Key:
            "Invalid channel_partner_oid specified.  Your REST API key may only interact with channel_partner_oid: 12345"
         Supply a bad preference oid: "Invalid channel_partner_ship_to_preference_oid specified."
        */
        public static void Execute()
        {
            Console.WriteLine("--- " + MethodBase.GetCurrentMethod()?.DeclaringType?.Name + " ---");
            
            try
            {
                // Create channel partner API instance using API key
                ChannelPartnerApi channelPartnerApi = new ChannelPartnerApi(Constants.ChannelPartnerApiKey);
                
                int channelPartnerShiptoPreferenceOid = 67890; // you will usually get this by calling getChannelPartnerShipToPreferences()
                int channelPartnerOid = 12345;
                
                channelPartnerApi.DeleteChannelPartnerShipToPreference(channelPartnerOid, channelPartnerShiptoPreferenceOid);
                Console.WriteLine("Channel partner ship to preference deleted successfully");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
                Console.WriteLine(ex.StackTrace);
            }
        }
    }
}
package channel_partner;

import com.ultracart.admin.v2.ChannelPartnerApi;

public class DeleteChannelPartnerShipToPreference {
  /*
   Deletes a ChannelPartnerShiptoPreference.  These preferences are used by EDI channel partners to automatically
   apply return policies and add additional free items to EDI orders based on the EDI code that is present.

   Success will return a status code 204 (No content)

   Possible Errors:
   Attempting to interact with a channel partner other than the one tied to your API Key:
      "Invalid channel_partner_oid specified.  Your REST API key may only interact with channel_partner_oid: 12345"
   Supply a bad preference oid: "Invalid channel_partner_ship_to_preference_oid specified."
  */
  public static void execute() {
    System.out.println("--- DeleteChannelPartnerShipToPreference ---");

    try {
      // Create channel partner API instance using API key
      ChannelPartnerApi channelPartnerApi = new ChannelPartnerApi(common.Constants.CHANNEL_PARTNER_API_KEY);

      int channelPartnerShiptoPreferenceOid = 67890; // you will usually get this by calling getChannelPartnerShipToPreferences()
      int channelPartnerOid = 12345;

      channelPartnerApi.deleteChannelPartnerShipToPreference(channelPartnerOid, channelPartnerShiptoPreferenceOid);
      System.out.println("Channel partner ship to preference deleted successfully");
    } catch (Exception ex) {
      System.out.println("Error: " + ex.getMessage());
      ex.printStackTrace();
    }
  }
}
import {channelPartnerApi} from '../api.js';

/**
 * Deletes a ChannelPartnerShiptoPreference. These preferences are used by EDI channel partners to automatically
 * apply return policies and add additional free items to EDI orders based on the EDI code that is present.
 *
 * Success will return a status code 204 (No content)
 *
 * Possible Errors:
 * Attempting to interact with a channel partner other than the one tied to your API Key:
 *    "Invalid channel_partner_oid specified.  Your REST API key may only interact with channel_partner_oid: 12345"
 * Supply a bad preference oid: "Invalid channel_partner_ship_to_preference_oid specified."
 */
export class DeleteChannelPartnerShipToPreference {
    /**
     * Execute method to delete a channel partner ship to preference
     */
    static async execute() {
        console.log(`--- ${this.name} ---`);

        try {
            // Channel partner ship to preference OID to delete (usually obtained from getChannelPartnerShipToPreferences())
            const channelPartnerShiptoPreferenceOid = 67890;
            const channelPartnerOid = 12345;

            // Delete the channel partner ship to preference using a Promise wrapper
            await new Promise((resolve, reject) => {
                channelPartnerApi.deleteChannelPartnerShipToPreference(
                    channelPartnerOid, channelPartnerShipToPreferenceOid,
                    function (error, data, response) {
                        if (error) {
                            reject(error);
                        } else {
                            resolve(data, response);
                        }
                    }
                );
            });

            console.log("Channel partner ship to preference deleted successfully");
        } catch (ex) {
            // Log the error details
            if (ex instanceof Error) {
                console.error(`Error: ${ex.message}`);
                console.error(ex.stack);
            } else {
                console.error("An unknown error occurred");
            }
        }
    }
}

<?php

ini_set('display_errors', 1);

/*
 Deletes a ChannelPartnerShiptoPreference.  These preferences are used by EDI channel partners to automatically
 apply return policies and add additional free items to EDI orders based on the EDI code that is present.

 Success will return a status code 204 (No content)

 Possible Errors:
 Attempting to interact with a channel partner other than the one tied to your API Key:
    "Invalid channel_partner_oid specified.  Your REST API key may only interact with channel_partner_oid: 12345"
 Supply a bad preference oid: "Invalid channel_partner_ship_to_preference_oid specified."

 */


use ultracart\v2\api\ChannelPartnerApi;

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


$channel_partner_api = ChannelPartnerApi::usingApiKey(Constants::CHANNEL_PARTNER_API_KEY);
$channel_partner_shipto_preference_oid = 67890; // you will usually get this by calling getChannelPartnerShipToPreferences()
$channel_partner_oid = 12345;

$channel_partner_api->deleteChannelPartnerShipToPreference($channel_partner_oid, $channel_partner_shipto_preference_oid);

"""
This is a helper function for call centers to calculate the shipping cost on an order. In a typical flow, the call center
will collect all the shipping information and items being purchased into a ChannelPartnerOrder object.
They will then call this method, passing in the order object. The response will contain the shipping estimates
that the call center can present to the customer. Once the customer selects a particulate estimate,
they can then plug that cost into their call center application and complete the order.

Possible Errors:
Using an API key that is not tied to a channel partner: "This API Key does not have permission to interact with channel partner orders. Please review your Channel Partner configuration."
Order has invalid channel partner code: "Invalid channel partner code"
Order has no items: "null order.items passed." or "order.items array contains a null entry."
Order has no channel partner order id: "order.channelPartnerOrderId must be specified."
Order channel partner order id is a duplicate: "order.channelPartnerOrderId [XYZ] already used."
Channel Partner is inactive: "partner is inactive."
"""

from ultracart.apis import ChannelPartnerApi
from ultracart.models import ChannelPartnerOrder, ChannelPartnerOrderItem, ChannelPartnerOrderItemOption
from samples import channel_partner_api_client
from datetime import datetime, timedelta

channel_partner_api = ChannelPartnerApi(channel_partner_api_client())

order = ChannelPartnerOrder()
order.channel_partner_order_id = "widget-1245-abc-1"
order.coupons = ["10OFF"]
# Delivery date will impact shipping estimates if there is a delivery deadline.
# order.delivery_date = (datetime.now() + timedelta(days=14)).isoformat()

item = ChannelPartnerOrderItem()
# item.arbitrary_unit_cost = 9.99
# item.auto_order_last_rebill_dts = (datetime.now() - timedelta(days=30)).isoformat()
# item.auto_order_schedule = "Weekly"
item.merchant_item_id = "shirt"

size_option = ChannelPartnerOrderItemOption()
size_option.name = "Size"
size_option.value = "Small"

color_option = ChannelPartnerOrderItemOption()
color_option.name = "Color"
color_option.value = "Orange"

item.options = [size_option, color_option]
item.quantity = 1
item.upsell = False

order.items = [item]

# order.ship_on_date = (datetime.now() + timedelta(days=7)).isoformat()
order.ship_to_residential = True
order.shipto_address1 = "55 Main Street"
order.shipto_address2 = "Suite 202"
order.shipto_city = "Duluth"
order.shipto_company = "Widgets Inc"
order.shipto_country_code = "US"
order.shipto_day_phone = "6785552323"
order.shipto_evening_phone = "7703334444"
order.shipto_first_name = "Sally"
order.shipto_last_name = "McGonkyDee"
order.shipto_postal_code = "30097"
order.shipto_state_region = "GA"
order.shipto_title = "Director"

api_response = channel_partner_api.estimate_shipping_for_channel_partner_order(order)
estimates = api_response.estimates

# TODO: Apply one estimate shipping method (name) and cost to your channel partner order.

for estimate in estimates:
    print(estimate)

require 'ultracart_api'
require_relative '../constants'

# Deletes a ChannelPartnerShiptoPreference.  These preferences are used by EDI channel partners to automatically
# apply return policies and add additional free items to EDI orders based on the EDI code that is present.
#
# Success will return a status code 204 (No content)
#
# Possible Errors:
# Attempting to interact with a channel partner other than the one tied to your API Key:
#     "Invalid channel_partner_oid specified.  Your REST API key may only interact with channel_partner_oid: 12345"
# Supply a bad preference oid: "Invalid channel_partner_ship_to_preference_oid specified."

channel_partner_api = UltracartClient::ChannelPartnerApi.new_using_api_key(Constants::CHANNEL_PARTNER_API_KEY)

# you will usually get this by calling get_channel_partner_ship_to_preferences()
channel_partner_shipto_preference_oid = 67890
channel_partner_oid = 12345

channel_partner_api.delete_channel_partner_ship_to_preference(channel_partner_oid, channel_partner_shipto_preference_oid)
import {channelPartnerApi} from '../api';

/**
 * Deletes a ChannelPartnerShiptoPreference.  These preferences are used by EDI channel partners to automatically
 * apply return policies and add additional free items to EDI orders based on the EDI code that is present.
 *
 * Success will return a status code 204 (No content)
 *
 * Possible Errors:
 * Attempting to interact with a channel partner other than the one tied to your API Key:
 *    "Invalid channel_partner_oid specified.  Your REST API key may only interact with channel_partner_oid: 12345"
 * Supply a bad preference oid: "Invalid channel_partner_ship_to_preference_oid specified."
 */
export class DeleteChannelPartnerShipToPreference {
    /**
     * Execute method to delete a channel partner ship to preference
     */
    public static async execute(): Promise<void> {
        console.log(`--- ${this.name} ---`);

        try {
            // Channel partner ship to preference OID to delete (usually obtained from getChannelPartnerShipToPreferences())
            const channelPartnerShiptoPreferenceOid: number = 67890;
            const channelPartnerOid: number = 12345;

            // Delete the channel partner ship to preference
            await channelPartnerApi.deleteChannelPartnerShipToPreference({
                channelPartnerOid,
                channelPartnerShipToPreferenceOid: channelPartnerShiptoPreferenceOid
            });

            console.log("Channel partner ship to preference deleted successfully");
        } catch (ex: unknown) {
            // Type the error as unknown and log details
            if (ex instanceof Error) {
                console.error(`Error: ${ex.message}`);
                console.error(ex.stack);
            } else {
                console.error("An unknown error occurred");
            }
        }
    }
}

Retrieve the ship to preference associated with the channel partner and the specific id.

Permissions:
  • channel_partner_read

Produces: application/json
get
/channel_partner/channel_partners/{channel_partner_oid}/ship_to_preferences/{channel_partner_ship_to_preference_oid}

Retrieve the ship to preference associated with the channel partner and the specific id.

SDK Function Name: getChannelPartnerShipToPreference

Parameters
Parameter Description Location Data Type Required
channel_partner_oid path integer (int32) optional
channel_partner_ship_to_preference_oid path integer (int32) optional
Responses
Status Code Reason Response Model
200
Successful response ChannelPartnerShipToPreferenceResponse
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.Reflection;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;

namespace SdkSample.channel_partner
{
    public class GetChannelPartnerShipToPreference
    {
        /*
         Retrieves a shipto preference for a channel partner.
         These preferences are used by EDI channel partners to automatically
         apply return policies and add additional free items to EDI orders based on the EDI code that is present.

         Possible Errors:
         Attempting to interact with a channel partner other than the one tied to your API Key:
            "Invalid channel_partner_oid specified.  Your REST API key may only interact with channel_partner_oid: 12345"
         Supplying a bad channel partner oid: "Invalid channel_partner_oid specified."
         Supplying a bad channel partner shipto preference oid: "Invalid channel_partner_ship_to_preference_oid specified."
        */
        public static void Execute()
        {
            Console.WriteLine("--- " + MethodBase.GetCurrentMethod()?.DeclaringType?.Name + " ---");
            
            try
            {
                // Create channel partner API instance using API key
                ChannelPartnerApi channelPartnerApi = new ChannelPartnerApi(Constants.ChannelPartnerApiKey);
                
                int channelPartnerOid = 12345;
                int channelPartnerShiptoPreferenceOid = 67890;
                
                var apiResponse = channelPartnerApi.GetChannelPartnerShipToPreference(channelPartnerOid, channelPartnerShiptoPreferenceOid);
                
                if (apiResponse.Error != null)
                {
                    Console.Error.WriteLine(apiResponse.Error.DeveloperMessage);
                    Console.Error.WriteLine(apiResponse.Error.UserMessage);
                    Environment.Exit(1);
                }
                
                var preference = apiResponse.ShipToPreference;
                Console.WriteLine(preference);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
                Console.WriteLine(ex.StackTrace);
            }
        }
    }
}
package channel_partner;

import com.ultracart.admin.v2.ChannelPartnerApi;
import com.ultracart.admin.v2.models.ChannelPartnerShipToPreference;
import com.ultracart.admin.v2.models.ChannelPartnerShipToPreferenceResponse;

public class GetChannelPartnerShipToPreference {
    /*
     Retrieves a shipto preference for a channel partner.
     These preferences are used by EDI channel partners to automatically
     apply return policies and add additional free items to EDI orders based on the EDI code that is present.

     Possible Errors:
     Attempting to interact with a channel partner other than the one tied to your API Key:
        "Invalid channel_partner_oid specified.  Your REST API key may only interact with channel_partner_oid: 12345"
     Supplying a bad channel partner oid: "Invalid channel_partner_oid specified."
     Supplying a bad channel partner shipto preference oid: "Invalid channel_partner_ship_to_preference_oid specified."
    */
    public static void execute() {
        System.out.println("--- GetChannelPartnerShipToPreference ---");

        try {
            // Create channel partner API instance using API key
            ChannelPartnerApi channelPartnerApi = new ChannelPartnerApi(common.Constants.CHANNEL_PARTNER_API_KEY);

            int channelPartnerOid = 12345;
            int channelPartnerShiptoPreferenceOid = 67890;

            ChannelPartnerShipToPreferenceResponse apiResponse = channelPartnerApi.getChannelPartnerShipToPreference(channelPartnerOid, channelPartnerShiptoPreferenceOid);

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

            ChannelPartnerShipToPreference preference = apiResponse.getShipToPreference();
            System.out.println(preference);
        }
        catch (Exception ex) {
            System.out.println("Error: " + ex.getMessage());
            ex.printStackTrace();
        }
    }
}
import { channelPartnerApi } from '../api.js';

/**
 * Retrieves a shipto preference for a channel partner.
 * These preferences are used by EDI channel partners to automatically
 * apply return policies and add additional free items to EDI orders based on the EDI code that is present.
 *
 * Possible Errors:
 * Attempting to interact with a channel partner other than the one tied to your API Key:
 *    "Invalid channel_partner_oid specified.  Your REST API key may only interact with channel_partner_oid: 12345"
 * Supplying a bad channel partner oid: "Invalid channel_partner_oid specified."
 * Supplying a bad channel partner shipto preference oid: "Invalid channel_partner_ship_to_preference_oid specified."
 */
export async function execute() {
    console.log(`--- ${execute.name} ---`);

    try {
        // Channel partner OID and shipto preference OID
        const channelPartnerOid = 12345;
        const channelPartnerShiptoPreferenceOid = 67890;

        // Retrieve channel partner shipto preference
        const apiResponse = await new Promise((resolve, reject) => {
            channelPartnerApi.getChannelPartnerShipToPreference(
                channelPartnerOid,
                channelPartnerShipToPreferenceOid
            , function (error, data) {
                if (error) {
                    reject(error);
                } else {
                    resolve(data);
                }
            });
        });

        // Check for errors in the API response
        if (apiResponse.error) {
            const error = apiResponse.error;
            console.error(error.developer_message);
            console.error(error.user_message);
            process.exit(1);
        }

        // Extract and log the preference
        const preference = apiResponse.ship_to_preference;
        console.log(preference);

    } catch (ex) {
        // Handle any unexpected errors
        const error = ex instanceof Error ? ex : new Error('Unknown error');
        console.error(`Error: ${error.message}`);
        console.error(error.stack);
    }
}

// Optional: If you want to run this directly
if (require.main === module) {
    execute().catch(console.error);
}

<?php

ini_set('display_errors', 1);

/*
 Retrieves a shipto preference for a channel partner.
 These preferences are used by EDI channel partners to automatically
 apply return policies and add additional free items to EDI orders based on the EDI code that is present.

 Possible Errors:
 Attempting to interact with a channel partner other than the one tied to your API Key:
    "Invalid channel_partner_oid specified.  Your REST API key may only interact with channel_partner_oid: 12345"
 Supplying a bad channel partner oid: "Invalid channel_partner_oid specified."
 Supplying a bad channel partner shipto preference oid: "Invalid channel_partner_ship_to_preference_oid specified."

 */


use ultracart\v2\api\ChannelPartnerApi;

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


$channel_partner_api = ChannelPartnerApi::usingApiKey(Constants::CHANNEL_PARTNER_API_KEY);
$channel_partner_oid = 12345;
$channel_partner_shipto_preference_oid = 67890;
$api_response = $channel_partner_api->getChannelPartnerShipToPreference($channel_partner_oid, $channel_partner_shipto_preference_oid);


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

$preference = $api_response->getShipToPreference();

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

from ultracart.apis import ChannelPartnerApi
from samples import channel_partner_api_client

"""
Retrieves a shipto preference for a channel partner.
These preferences are used by EDI channel partners to automatically
apply return policies and add additional free items to EDI orders based on the EDI code that is present.

Possible Errors:
Attempting to interact with a channel partner other than the one tied to your API Key:
    "Invalid channel_partner_oid specified.  Your REST API key may only interact with channel_partner_oid: 12345"
Supplying a bad channel partner oid: "Invalid channel_partner_oid specified."
Supplying a bad channel partner shipto preference oid: "Invalid channel_partner_ship_to_preference_oid specified."
"""

channel_partner_api = ChannelPartnerApi(channel_partner_api_client())
channel_partner_oid = 12345
channel_partner_shipto_preference_oid = 67890
api_response = channel_partner_api.get_channel_partner_ship_to_preference(channel_partner_oid, channel_partner_shipto_preference_oid)

if api_response.error is not None:
    print(api_response.error.developer_message)
    print(api_response.error.user_message)
    exit()

preference = api_response.ship_to_preference

print(preference)
require 'ultracart_api'
require_relative '../constants'

# Retrieves a shipto preference for a channel partner.
# These preferences are used by EDI channel partners to automatically
# apply return policies and add additional free items to EDI orders based on the EDI code that is present.
#
# Possible Errors:
# Attempting to interact with a channel partner other than the one tied to your API Key:
#    "Invalid channel_partner_oid specified.  Your REST API key may only interact with channel_partner_oid: 12345"
# Supplying a bad channel partner oid: "Invalid channel_partner_oid specified."
# Supplying a bad channel partner shipto preference oid: "Invalid channel_partner_ship_to_preference_oid specified."

channel_partner_api = UltracartClient::ChannelPartnerApi.new_using_api_key(Constants::CHANNEL_PARTNER_API_KEY)
channel_partner_oid = 12345
channel_partner_shipto_preference_oid = 67890
api_response = channel_partner_api.get_channel_partner_ship_to_preference(channel_partner_oid, channel_partner_shipto_preference_oid)

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

preference = api_response.ship_to_preference

p preference
import {ChannelPartnerShipToPreference, ModelError} from 'ultracart_rest_api_v2_typescript';
import { channelPartnerApi } from '../api';

/**
 * Retrieves a shipto preference for a channel partner.
 * These preferences are used by EDI channel partners to automatically
 * apply return policies and add additional free items to EDI orders based on the EDI code that is present.
 *
 * Possible Errors:
 * Attempting to interact with a channel partner other than the one tied to your API Key:
 *    "Invalid channel_partner_oid specified.  Your REST API key may only interact with channel_partner_oid: 12345"
 * Supplying a bad channel partner oid: "Invalid channel_partner_oid specified."
 * Supplying a bad channel partner shipto preference oid: "Invalid channel_partner_ship_to_preference_oid specified."
 */
export async function execute(): Promise<void> {
    console.log(`--- ${execute.name} ---`);

    try {
        // Channel partner OID and shipto preference OID
        const channelPartnerOid: number = 12345;
        const channelPartnerShiptoPreferenceOid: number = 67890;

        // Retrieve channel partner shipto preference
        const apiResponse = await channelPartnerApi.getChannelPartnerShipToPreference({
            channelPartnerOid,
            channelPartnerShipToPreferenceOid: channelPartnerShiptoPreferenceOid
        });

        // Check for errors in the API response
        if (apiResponse.error) {
            const error: ModelError = apiResponse.error;
            console.error(error.developer_message);
            console.error(error.user_message);
            process.exit(1);
        }

        // Extract and log the preference
        const preference: ChannelPartnerShipToPreference | undefined = apiResponse.ship_to_preference;
        console.log(preference);
    }
    catch (ex: unknown) {
        // Handle any unexpected errors
        const error = ex as Error;
        console.error(`Error: ${error.message}`);
        console.error(error.stack);
    }
}

// Optional: If you want to run this directly
if (require.main === module) {
    execute().catch(console.error);
}

Update a ship to preference record for the channel partner.

Permissions:
  • channel_partner_write

Produces: application/json
put
/channel_partner/channel_partners/{channel_partner_oid}/ship_to_preferences/{channel_partner_ship_to_preference_oid}

Update a ship to preference record for the channel partner.

SDK Function Name: updateChannelPartnerShipToPreference

Parameters
Parameter Description Location Data Type Required
channel_partner_oid path integer (int32) optional
channel_partner_ship_to_preference_oid path integer (int32) optional
ship_to_preference Ship to preference to create body ChannelPartnerShipToPreference required
Responses
Status Code Reason Response Model
200
Successful response ChannelPartnerShipToPreferenceResponse
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.channel_partner
{
    public class UpdateChannelPartnerShipToPreference
    {
        /// <summary>
        /// Updates a channel partner shipto preference for a channel partner.
        /// These preferences are used by EDI channel partners to automatically
        /// apply return policies and add additional free items to EDI orders based on the EDI code that is present.
        /// 
        /// Possible Errors:
        /// Attempting to interact with a channel partner other than the one tied to your API Key:
        ///    "Invalid channel_partner_oid specified.  Your REST API key may only interact with channel_partner_oid: 12345"
        /// Supplying a bad channel partner oid: "Invalid channel_partner_oid specified."
        /// </summary>
        public static void Execute()
        {
            ChannelPartnerApi channelPartnerApi = new ChannelPartnerApi(Constants.ChannelPartnerApiKey);
            int channelPartnerOid = 12345;
            int channelPartnerShipToPreferenceOid = 67890;

            ChannelPartnerShipToPreferenceResponse apiResponse = channelPartnerApi.GetChannelPartnerShipToPreference(
                channelPartnerOid, 
                channelPartnerShipToPreferenceOid);

            ChannelPartnerShipToPreference preference = apiResponse.ShipToPreference;
            
            // Update some fields.
            preference.ShipToEdiCode = "EDI_CODE_HERE";
            preference.ReturnPolicy = "This is some return policy text that will be printed on the packing slip.";
            preference.AdditionalKitComponentItemIds = new List<string> { "ITEM_ID1", "ITEM_ID2", "ITEM_ID3" };
            preference.Description = "This is a merchant friendly description to help me remember what the above setting are.";

            apiResponse = channelPartnerApi.UpdateChannelPartnerShipToPreference(
                channelPartnerOid, 
                channelPartnerShipToPreferenceOid, 
                preference);

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

            ChannelPartnerShipToPreference updatedPreference = apiResponse.ShipToPreference;

            // This should equal what you submitted.
            Console.WriteLine(JsonConvert.SerializeObject(updatedPreference, Formatting.Indented));
        }
    }
}
package channel_partner;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ultracart.admin.v2.ChannelPartnerApi;
import com.ultracart.admin.v2.models.ChannelPartnerShipToPreference;
import com.ultracart.admin.v2.models.ChannelPartnerShipToPreferenceResponse;

import java.util.ArrayList;

public class UpdateChannelPartnerShipToPreference {
    /**
     * Updates a channel partner shipto preference for a channel partner.
     * These preferences are used by EDI channel partners to automatically
     * apply return policies and add additional free items to EDI orders based on the EDI code that is present.
     *
     * Possible Errors:
     * Attempting to interact with a channel partner other than the one tied to your API Key:
     *    "Invalid channel_partner_oid specified.  Your REST API key may only interact with channel_partner_oid: 12345"
     * Supplying a bad channel partner oid: "Invalid channel_partner_oid specified."
     */
    public static void execute() {
        try {
            ChannelPartnerApi channelPartnerApi = new ChannelPartnerApi(common.Constants.CHANNEL_PARTNER_API_KEY);
            int channelPartnerOid = 12345;
            int channelPartnerShipToPreferenceOid = 67890;

            ChannelPartnerShipToPreferenceResponse apiResponse = channelPartnerApi.getChannelPartnerShipToPreference(
                channelPartnerOid,
                channelPartnerShipToPreferenceOid);

            ChannelPartnerShipToPreference preference = apiResponse.getShipToPreference();

            // Update some fields.
            preference.setShipToEdiCode("EDI_CODE_HERE");
            preference.setReturnPolicy("This is some return policy text that will be printed on the packing slip.");

            ArrayList<String> additionalKitComponentItemIds = new ArrayList<String>();
            additionalKitComponentItemIds.add("ITEM_ID1");
            additionalKitComponentItemIds.add("ITEM_ID2");
            additionalKitComponentItemIds.add("ITEM_ID3");
            preference.setAdditionalKitComponentItemIds(additionalKitComponentItemIds);

            preference.setDescription("This is a merchant friendly description to help me remember what the above setting are.");

            apiResponse = channelPartnerApi.updateChannelPartnerShipToPreference(
                channelPartnerOid,
                channelPartnerShipToPreferenceOid,
                preference);

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

            ChannelPartnerShipToPreference updatedPreference = apiResponse.getShipToPreference();

            // This should equal what you submitted.
            ObjectMapper mapper = new ObjectMapper();
            System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(updatedPreference));
        }
        catch (Exception ex) {
            System.out.println("Error: " + ex.getMessage());
            ex.printStackTrace();
        }
    }
}
import {channelPartnerApi} from '../api.js';

/**
 * Updates a channel partner shipto preference for a channel partner.
 * These preferences are used by EDI channel partners to automatically
 * apply return policies and add additional free items to EDI orders based on the EDI code that is present.
 *
 * Possible Errors:
 * Attempting to interact with a channel partner other than the one tied to your API Key:
 *    "Invalid channel_partner_oid specified.  Your REST API key may only interact with channel_partner_oid: 12345"
 * Supplying a bad channel partner oid: "Invalid channel_partner_oid specified."
 */
export async function execute() {
    try {
        const channelPartnerOid = 12345;
        const channelPartnerShipToPreferenceOid = 67890;

        // Retrieve the existing preference
        const getResponse = await new Promise((resolve, reject) => {
            channelPartnerApi.getChannelPartnerShipToPreference(
                {channelPartnerOid, channelPartnerShipToPreferenceOid},
                function (error, data) {
                    if (error) {
                        reject(error);
                    } else {
                        resolve(data);
                    }
                }
            );
        });

        // Check for errors in retrieval
        if (getResponse.error) {
            const error = getResponse.error;
            console.error(error.developer_message);
            console.error(error.user_message);
            process.exit(1);
        }

        // Ensure preference exists
        if (!getResponse.ship_to_preference) {
            console.error("No ship to preference found");
            process.exit(1);
        }

        // Create a copy of the preference to update
        const preference = {
            ...getResponse.ship_to_preference,
            ship_to_edi_code: "EDI_CODE_HERE",
            return_policy: "This is some return policy text that will be printed on the packing slip.",
            additional_kit_component_item_ids: ["ITEM_ID1", "ITEM_ID2", "ITEM_ID3"],
            description: "This is a merchant friendly description to help me remember what the above setting are."
        };

        // Update the preference
        const updateResponse = await new Promise((resolve, reject) => {
            channelPartnerApi.updateChannelPartnerShipToPreference(
                channelPartnerOid,
                channelPartnerShipToPreferenceOid,
                preference,
                function (error, data) {
                    if (error) {
                        reject(error);
                    } else {
                        resolve(data);
                    }
                }
            );
        });

        // Check for errors in update
        if (updateResponse.error) {
            const error = updateResponse.error;
            console.error(error.developer_message);
            console.error(error.user_message);
            process.exit(1);
        }

        // Ensure updated preference exists
        const updatedPreference = updateResponse.ship_to_preference;

        // This should equal what you submitted.
        console.log(JSON.stringify(updatedPreference, null, 2));
    } catch (ex) {
        const error = ex instanceof Error ? ex : new Error('Unknown error');
        console.error(`Error: ${error.message}`);
        console.error(error.stack);
    }
}

// Optional: If you want to run this directly
if (require.main === module) {
    execute().catch(console.error);
}

<?php

ini_set('display_errors', 1);

/*
 Updates a channel partner shipto preference for a channel partner.
 These preferences are used by EDI channel partners to automatically
 apply return policies and add additional free items to EDI orders based on the EDI code that is present.

 Possible Errors:
 Attempting to interact with a channel partner other than the one tied to your API Key:
    "Invalid channel_partner_oid specified.  Your REST API key may only interact with channel_partner_oid: 12345"
 Supplying a bad channel partner oid: "Invalid channel_partner_oid specified."

 */


use ultracart\v2\api\ChannelPartnerApi;
use ultracart\v2\models\ChannelPartnerShipToPreference;

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


$channel_partner_api = ChannelPartnerApi::usingApiKey(Constants::CHANNEL_PARTNER_API_KEY);
$channel_partner_oid = 12345;
$channel_partner_ship_to_preference_oid = 67890;

$api_response = $channel_partner_api->getChannelPartnerShipToPreference($channel_partner_oid, $channel_partner_ship_to_preference_oid);

$preference = $api_response->getShipToPreference();
// Update some fields.
$preference->setShipToEdiCode('EDI_CODE_HERE');
$preference->setReturnPolicy("This is some return policy text that will be printed on the packing slip.");
$preference->setAdditionalKitComponentItemIds(['ITEM_ID1', 'ITEM_ID2', 'ITEM_ID3']);
$preference->setDescription("This is a merchant friendly description to help me remember what the above setting are.");

$api_response = $channel_partner_api->updateChannelPartnerShipToPreference($channel_partner_oid, $channel_partner_ship_to_preference_oid, $preference);

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

$updated_preference = $api_response->getShipToPreference();

echo '<html lang="en"><body><pre>';
// This should equal what you submitted.
var_dump($updated_preference);
echo '</pre></body></html>';

from ultracart.apis import ChannelPartnerApi
from samples import channel_partner_api_client

# Initialize API
channel_partner_api = ChannelPartnerApi(channel_partner_api_client())
channel_partner_oid = 12345
channel_partner_ship_to_preference_oid = 67890

# Get existing preference
api_response = channel_partner_api.get_channel_partner_ship_to_preference(channel_partner_oid, channel_partner_ship_to_preference_oid)

preference = api_response.ship_to_preference

# Update fields
preference.ship_to_edi_code = 'EDI_CODE_HERE'
preference.return_policy = "This is some return policy text that will be printed on the packing slip."
preference.additional_kit_component_item_ids = ['ITEM_ID1', 'ITEM_ID2', 'ITEM_ID3']
preference.description = "This is a merchant friendly description to help me remember what the above setting are."

# Update the preference
api_response = channel_partner_api.update_channel_partner_ship_to_preference(channel_partner_oid, channel_partner_ship_to_preference_oid, preference)

if api_response.error is not None:
    print(api_response.error.developer_message)
    print(api_response.error.user_message)
    exit()

updated_preference = api_response.ship_to_preference
print(updated_preference)
# Updates a channel partner shipto preference for a channel partner.
# These preferences are used by EDI channel partners to automatically
# apply return policies and add additional free items to EDI orders based on the EDI code that is present.
#
# Possible Errors:
# Attempting to interact with a channel partner other than the one tied to your API Key:
#    "Invalid channel_partner_oid specified.  Your REST API key may only interact with channel_partner_oid: 12345"
# Supplying a bad channel partner oid: "Invalid channel_partner_oid specified."

require 'ultracart_api'
require_relative '../constants'

channel_partner_api = UltracartClient::ChannelPartnerApi.new_using_api_key(Constants::CHANNEL_PARTNER_API_KEY)
channel_partner_oid = 12345
channel_partner_ship_to_preference_oid = 67890

api_response = channel_partner_api.get_channel_partner_ship_to_preference(channel_partner_oid, channel_partner_ship_to_preference_oid)

preference = api_response.ship_to_preference
# Update some fields.
preference.ship_to_edi_code = 'EDI_CODE_HERE'
preference.return_policy = "This is some return policy text that will be printed on the packing slip."
preference.additional_kit_component_item_ids = ['ITEM_ID1', 'ITEM_ID2', 'ITEM_ID3']
preference.description = "This is a merchant friendly description to help me remember what the above setting are."

api_response = channel_partner_api.update_channel_partner_ship_to_preference(channel_partner_oid, channel_partner_ship_to_preference_oid, preference)

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

updated_preference = api_response.ship_to_preference

# This should equal what you submitted.
p updated_preference
import {
    ChannelPartnerShipToPreference, ModelError
} from 'ultracart_rest_api_v2_typescript';
import {channelPartnerApi} from '../api';

/**
 * Updates a channel partner shipto preference for a channel partner.
 * These preferences are used by EDI channel partners to automatically
 * apply return policies and add additional free items to EDI orders based on the EDI code that is present.
 *
 * Possible Errors:
 * Attempting to interact with a channel partner other than the one tied to your API Key:
 *    "Invalid channel_partner_oid specified.  Your REST API key may only interact with channel_partner_oid: 12345"
 * Supplying a bad channel partner oid: "Invalid channel_partner_oid specified."
 */
export async function execute(): Promise<void> {
    try {
        const channelPartnerOid: number = 12345;
        const channelPartnerShipToPreferenceOid: number = 67890;

        // Retrieve the existing preference
        const getResponse = await channelPartnerApi.getChannelPartnerShipToPreference({
            channelPartnerOid,
            channelPartnerShipToPreferenceOid
        });

        // Check for errors in retrieval
        if (getResponse.error) {
            const error: ModelError = getResponse.error;
            console.error(error.developer_message);
            console.error(error.user_message);
            process.exit(1);
        }

        // Ensure preference exists
        if (!getResponse.ship_to_preference) {
            console.error("No ship to preference found");
            process.exit(1);
        }

        // Create a copy of the preference to update
        const preference: ChannelPartnerShipToPreference = {
            ...getResponse.ship_to_preference,
            ship_to_edi_code: "EDI_CODE_HERE",
            return_policy: "This is some return policy text that will be printed on the packing slip.",
            additional_kit_component_item_ids: ["ITEM_ID1", "ITEM_ID2", "ITEM_ID3"],
            description: "This is a merchant friendly description to help me remember what the above setting are."
        };

        // Update the preference
        const updateResponse = await channelPartnerApi.updateChannelPartnerShipToPreference({
            channelPartnerOid,
            channelPartnerShipToPreferenceOid,
            shipToPreference: preference
        });

        // Check for errors in update
        if (updateResponse.error) {
            const error: ModelError = updateResponse.error;
            console.error(error.developer_message);
            console.error(error.user_message);
            process.exit(1);
        }

        // Ensure updated preference exists
        const updatedPreference = updateResponse.ship_to_preference;

        // This should equal what you submitted.
        console.log(JSON.stringify(updatedPreference, null, 2));
    } catch (ex: unknown) {
        const error = ex as Error;
        console.error(`Error: ${error.message}`);
        console.error(error.stack);
    }
}

// Optional: If you want to run this directly
if (require.main === module) {
    execute().catch(console.error);
}

Estimate shipping for channel partner order

Permissions:
  • channel_partner_read

Consumes: application/json
Produces: application/json
post
/channel_partner/estimate_shipping

Estimate shipping for order from a channel partner.

SDK Function Name: estimateShippingForChannelPartnerOrder

Parameters
Parameter Description Location Data Type Required
channel_partner_order Order needing shipping estimate body ChannelPartnerOrder required
Responses
Status Code Reason Response Model
200
Successful response ChannelPartnerEstimateShippingResponse
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.Reflection;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;

namespace SdkSample.channel_partner
{
    public class EstimateShippingForChannelPartnerOrder
    {
        /*
         This is a helper function for call centers to calculate the shipping cost on an order.  In a typical flow, the call center
         will collect all the shipping information and items being purchased into a ChannelPartnerOrder object.
         They will then call this method, passing in the order object.  The response will contain the shipping estimates
         that the call center can present to the customer.  Once the customer selects a particulate estimate,
         they can then plug that cost into their call center application and complete the order.

         Possible Errors:
         Using an API key that is not tied to a channel partner: "This API Key does not have permission to interact with channel partner orders.  Please review your Channel Partner configuration."
         Order has invalid channel partner code: "Invalid channel partner code"
         Order has no items: "null order.items passed." or "order.items array contains a null entry."
         Order has no channel partner order id: "order.channelPartnerOrderId must be specified."
         Order channel partner order id is a duplicate:  "order.channelPartnerOrderId [XYZ] already used."
         Channel Partner is inactive: "partner is inactive."
        */
        public static void Execute()
        {
            Console.WriteLine("--- " + MethodBase.GetCurrentMethod()?.DeclaringType?.Name + " ---");
            
            try
            {
                // Create channel partner API instance using API key
                ChannelPartnerApi channelPartnerApi = new ChannelPartnerApi(Constants.ChannelPartnerApiKey);
                
                ChannelPartnerOrder order = new ChannelPartnerOrder()
                {
                    ChannelPartnerOrderId = "widget-1245-abc-1",
                    Coupons = new List<string>() { "10OFF" },
                    // DeliveryDate will impact shipping estimates if there is a delivery deadline.  
                    // DeliveryDate =
                    //    DateTime.Now.AddDays(14).ToString("s", System.Globalization.CultureInfo.InvariantCulture),
                    Items = new List<ChannelPartnerOrderItem>()
                    {
                        new ChannelPartnerOrderItem()
                        {
                            // ArbitraryUnitCost = 9.99m,
                            // AutoOrderLastRebillDts = DateTime.Now.AddDays(-30).ToString("s", System.Globalization.CultureInfo.InvariantCulture),
                            // AutoOrderSchedule = "Weekly",
                            MerchantItemId = "shirt",
                            Options = new List<ChannelPartnerOrderItemOption>()
                            {
                                new ChannelPartnerOrderItemOption()
                                {
                                    Name = "Size",
                                    Value = "Small"
                                },
                                new ChannelPartnerOrderItemOption()
                                {
                                    Name = "Color",
                                    Value = "Orange"
                                }
                            },
                            Quantity = 1,
                            Upsell = false,
                        }
                    },
                    // ShipOnDate = DateTime.Now.AddDays(7).ToString("s", System.Globalization.CultureInfo.InvariantCulture),
                    ShipToResidential = true,
                    ShiptoAddress1 = "55 Main Street",
                    ShiptoAddress2 = "Suite 202",
                    ShiptoCity = "Duluth",
                    ShiptoCompany = "Widgets Inc",
                    ShiptoCountryCode = "US",
                    ShiptoDayPhone = "6785552323",
                    ShiptoEveningPhone = "7703334444",
                    ShiptoFirstName = "Sally",
                    ShiptoLastName = "McGonkyDee",
                    ShiptoPostalCode = "30097",
                    ShiptoStateRegion = "GA",
                    ShiptoTitle = "Director"
                };
                
                var apiResponse = channelPartnerApi.EstimateShippingForChannelPartnerOrder(order);
                var estimates = apiResponse.Estimates;
                
                // TODO: Apply one estimate shipping method (name) and cost to your channel partner order.
                
                // Display shipping estimates
                foreach (var estimate in estimates)
                {
                    Console.WriteLine(estimate);
                }
                
                Console.WriteLine($"Retrieved {estimates.Count} shipping estimates");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
                Console.WriteLine(ex.StackTrace);
            }
        }
    }
}
package channel_partner;

import com.ultracart.admin.v2.ChannelPartnerApi;
import com.ultracart.admin.v2.models.*;

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

public class EstimateShippingForChannelPartnerOrder {
  /*
   This is a helper function for call centers to calculate the shipping cost on an order.  In a typical flow, the call center
   will collect all the shipping information and items being purchased into a ChannelPartnerOrder object.
   They will then call this method, passing in the order object.  The response will contain the shipping estimates
   that the call center can present to the customer.  Once the customer selects a particulate estimate,
   they can then plug that cost into their call center application and complete the order.

   Possible Errors:
   Using an API key that is not tied to a channel partner: "This API Key does not have permission to interact with channel partner orders.  Please review your Channel Partner configuration."
   Order has invalid channel partner code: "Invalid channel partner code"
   Order has no items: "null order.items passed." or "order.items array contains a null entry."
   Order has no channel partner order id: "order.channelPartnerOrderId must be specified."
   Order channel partner order id is a duplicate:  "order.channelPartnerOrderId [XYZ] already used."
   Channel Partner is inactive: "partner is inactive."
  */
  public static void execute() {
    System.out.println("--- EstimateShippingForChannelPartnerOrder ---");

    try {
      // Create channel partner API instance using API key
      ChannelPartnerApi channelPartnerApi = new ChannelPartnerApi(common.Constants.CHANNEL_PARTNER_API_KEY);

      ChannelPartnerOrder order = new ChannelPartnerOrder();
      order.setChannelPartnerOrderId("widget-1245-abc-1");

      ArrayList<String> coupons = new ArrayList<String>();
      coupons.add("10OFF");
      order.setCoupons(coupons);

      // DeliveryDate will impact shipping estimates if there is a delivery deadline.
      // order.setDeliveryDate(Instant.now().plus(14, java.time.temporal.ChronoUnit.DAYS).toString());

      ArrayList<ChannelPartnerOrderItem> items = new ArrayList<ChannelPartnerOrderItem>();
      ChannelPartnerOrderItem item = new ChannelPartnerOrderItem();
      // item.setArbitraryUnitCost(new java.math.BigDecimal("9.99"));
      // item.setAutoOrderLastRebillDts(Instant.now().minus(30, java.time.temporal.ChronoUnit.DAYS).toString());
      // item.setAutoOrderSchedule("Weekly");
      item.setMerchantItemId("shirt");

      ArrayList<ChannelPartnerOrderItemOption> options = new ArrayList<ChannelPartnerOrderItemOption>();
      ChannelPartnerOrderItemOption sizeOption = new ChannelPartnerOrderItemOption();
      sizeOption.setName("Size");
      sizeOption.setValue("Small");
      options.add(sizeOption);

      ChannelPartnerOrderItemOption colorOption = new ChannelPartnerOrderItemOption();
      colorOption.setName("Color");
      colorOption.setValue("Orange");
      options.add(colorOption);

      item.setOptions(options);
      item.setQuantity(BigDecimal.valueOf(1));
      item.setUpsell(false);
      items.add(item);
      order.setItems(items);

      // order.setShipOnDate(Instant.now().plus(7, java.time.temporal.ChronoUnit.DAYS).toString());
      order.setShipToResidential(true);
      order.setShiptoAddress1("55 Main Street");
      order.setShiptoAddress2("Suite 202");
      order.setShiptoCity("Duluth");
      order.setShiptoCompany("Widgets Inc");
      order.setShiptoCountryCode("US");
      order.setShiptoDayPhone("6785552323");
      order.setShiptoEveningPhone("7703334444");
      order.setShiptoFirstName("Sally");
      order.setShiptoLastName("McGonkyDee");
      order.setShiptoPostalCode("30097");
      order.setShiptoStateRegion("GA");
      order.setShiptoTitle("Director");

      ChannelPartnerEstimateShippingResponse apiResponse = channelPartnerApi.estimateShippingForChannelPartnerOrder(order);
      List<ChannelPartnerShippingEstimate> estimates = apiResponse.getEstimates();

      // TODO: Apply one estimate shipping method (name) and cost to your channel partner order.

      // Display shipping estimates
      for (ChannelPartnerShippingEstimate estimate : estimates) {
        System.out.println(estimate);
      }

      System.out.println("Retrieved " + estimates.size() + " shipping estimates");
    } catch (Exception ex) {
      System.out.println("Error: " + ex.getMessage());
      ex.printStackTrace();
    }
  }
}
import { channelPartnerApi } from '../api.js';

/**
 * This is a helper function for call centers to calculate the shipping cost on an order. In a typical flow, the call center
 * will collect all the shipping information and items being purchased into a ChannelPartnerOrder object.
 * They will then call this method, passing in the order object. The response will contain the shipping estimates
 * that the call center can present to the customer. Once the customer selects a particular estimate,
 * they can then plug that cost into their call center application and complete the order.
 *
 * Possible Errors:
 * Using an API key that is not tied to a channel partner: "This API Key does not have permission to interact with channel partner orders. Please review your Channel Partner configuration."
 * Order has invalid channel partner code: "Invalid channel partner code"
 * Order has no items: "null order.items passed." or "order.items array contains a null entry."
 * Order has no channel partner order id: "order.channelPartnerOrderId must be specified."
 * Order channel partner order id is a duplicate: "order.channelPartnerOrderId [XYZ] already used."
 * Channel Partner is inactive: "partner is inactive."
 */
export class EstimateShippingForChannelPartnerOrder {
    /**
     * Execute method to estimate shipping for a channel partner order
     */
    static async execute() {
        console.log(`--- ${this.name} ---`);

        try {
            // Prepare the channel partner order
            const order = {
                channel_partner_order_id: "widget-1245-abc-1",
                coupons: ["10OFF"],
                // Uncomment and modify as needed
                // deliveryDate: DateTime.now().plus({ days: 14 }).toISO(),
                items: [
                    {
                        // Commented out properties preserved from original code
                        // arbitraryUnitCost: 9.99,
                        // autoOrderLastRebillDts: DateTime.now().minus({ days: 30 }).toISO(),
                        // autoOrderSchedule: "Weekly",
                        merchant_item_id: "shirt",
                        options: [
                            {
                                name: "Size",
                                value: "Small"
                            },
                            {
                                name: "Color",
                                value: "Orange"
                            }
                        ],
                        quantity: 1,
                        upsell: false,
                    }
                ],
                // Uncomment and modify as needed
                // shipOnDate: DateTime.now().plus({ days: 7 }).toISO(),
                ship_to_residential: true,
                shipto_address1: "55 Main Street",
                shipto_address2: "Suite 202",
                shipto_city: "Duluth",
                shipto_company: "Widgets Inc",
                shipto_country_code: "US",
                shipto_day_phone: "6785552323",
                shipto_evening_phone: "7703334444",
                shipto_first_name: "Sally",
                shipto_last_name: "McGonkyDee",
                shipto_postal_code: "30097",
                shipto_state_region: "GA",
                shipto_title: "Director"
            };

            // Estimate shipping for the order using a Promise wrapper
            const apiResponse = await new Promise((resolve, reject) => {
                channelPartnerApi.estimateShippingForChannelPartnerOrder(
                    order,
                    function (error, data, response) {
                        if (error) {
                            reject(error);
                        } else {
                            resolve(data, response);
                        }
                    }
                );
            });

            const estimates = apiResponse.estimates;

            // TODO: Apply one estimate shipping method (name) and cost to your channel partner order.

            if (estimates !== undefined) {
                // Display shipping estimates
                estimates.forEach(estimate => {
                    console.log(estimate);
                });

                console.log(`Retrieved ${estimates.length} shipping estimates`);
            }
        } catch (ex) {
            // Log the error details
            if (ex instanceof Error) {
                console.error(`Error: ${ex.message}`);
                console.error(ex.stack);
            } else {
                console.error("An unknown error occurred");
            }
        }
    }
}

<?php

ini_set('display_errors', 1);

/*
 This is a helper function for call centers to calculate the shipping cost on an order.  In a typical flow, the call center
 will collect all the shipping information and items being purchased into a ChannelPartnerOrder object.
 They will then call this method, passing in the order object.  The response will contain the shipping estimates
 that the call center can present to the customer.  Once the customer selects a particulate estimate,
 they can then plug that cost into their call center application and complete the order.

 Possible Errors:
 Using an API key that is not tied to a channel partner: "This API Key does not have permission to interact with channel partner orders.  Please review your Channel Partner configuration."
 Order has invalid channel partner code: "Invalid channel partner code"
 Order has no items: "null order.items passed." or "order.items array contains a null entry."
 Order has no channel partner order id: "order.channelPartnerOrderId must be specified."
 Order channel partner order id is a duplicate:  "order.channelPartnerOrderId [XYZ] already used."
 Channel Partner is inactive: "partner is inactive."


 */


use ultracart\v2\api\ChannelPartnerApi;
use ultracart\v2\models\ChannelPartnerOrder;
use ultracart\v2\models\ChannelPartnerOrderItem;
use ultracart\v2\models\ChannelPartnerOrderItemOption;

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


$channel_partner_api = ChannelPartnerApi::usingApiKey(Constants::CHANNEL_PARTNER_API_KEY);

$order = new ChannelPartnerOrder();
$order->setChannelPartnerOrderId("widget-1245-abc-1");
$order->setCoupons(["10OFF"]);
// DeliveryDate will impact shipping estimates if there is a delivery deadline.
// $order->setDeliveryDate(date('c', strtotime('+14 days')));

$item = new ChannelPartnerOrderItem();
// $item->setArbitraryUnitCost(9.99);
// $item->setAutoOrderLastRebillDts(date('c', strtotime('-30 days')));
// $item->setAutoOrderSchedule("Weekly");
$item->setMerchantItemId("shirt");

$sizeOption = new ChannelPartnerOrderItemOption();
$sizeOption->setName("Size");
$sizeOption->setValue("Small");

$colorOption = new ChannelPartnerOrderItemOption();
$colorOption->setName("Color");
$colorOption->setValue("Orange");

$item->setOptions([$sizeOption, $colorOption]);
$item->setQuantity(1);
$item->setUpsell(false);

$order->setItems([$item]);

// $order->setShipOnDate(date('c', strtotime('+7 days')));
$order->setShipToResidential(true);
$order->setShiptoAddress1("55 Main Street");
$order->setShiptoAddress2("Suite 202");
$order->setShiptoCity("Duluth");
$order->setShiptoCompany("Widgets Inc");
$order->setShiptoCountryCode("US");
$order->setShiptoDayPhone("6785552323");
$order->setShiptoEveningPhone("7703334444");
$order->setShiptoFirstName("Sally");
$order->setShiptoLastName("McGonkyDee");
$order->setShiptoPostalCode("30097");
$order->setShiptoStateRegion("GA");
$order->setShiptoTitle("Director");


$api_response = $channel_partner_api->estimateShippingForChannelPartnerOrder($order);
$estimates = $api_response->getEstimates();

// TODO: Apply one estimate shipping method (name) and cost to your channel partner order.

echo '<html lang="en"><body><pre>';
foreach ($estimates as $estimate) {
    var_dump($estimate);
}
echo '</pre></body></html>';

from ultracart.apis import ChannelPartnerApi
from ultracart.models import ChannelPartnerOrder, ChannelPartnerOrderItem, ChannelPartnerOrderItemOption
from samples import channel_partner_api_client

channel_partner_api = ChannelPartnerApi(channel_partner_api_client())

order = ChannelPartnerOrder()
order.channel_partner_order_id = "widget-1245-abc-1"
order.coupons = ["10OFF"]
# DeliveryDate will impact shipping estimates if there is a delivery deadline.
# order.delivery_date = (datetime.now() + timedelta(days=14)).isoformat()

item = ChannelPartnerOrderItem()
# item.arbitrary_unit_cost = 9.99
# item.auto_order_last_rebill_dts = (datetime.now() - timedelta(days=30)).isoformat()
# item.auto_order_schedule = "Weekly"
item.merchant_item_id = "shirt"

size_option = ChannelPartnerOrderItemOption()
size_option.name = "Size"
size_option.value = "Small"

color_option = ChannelPartnerOrderItemOption()
color_option.name = "Color"
color_option.value = "Orange"

item.options = [size_option, color_option]
item.quantity = 1
item.upsell = False

order.items = [item]

# order.ship_on_date = (datetime.now() + timedelta(days=7)).isoformat()
order.ship_to_residential = True
order.shipto_address1 = "55 Main Street"
order.shipto_address2 = "Suite 202"
order.shipto_city = "Duluth"
order.shipto_company = "Widgets Inc"
order.shipto_country_code = "US"
order.shipto_day_phone = "6785552323"
order.shipto_evening_phone = "7703334444"
order.shipto_first_name = "Sally"
order.shipto_last_name = "McGonkyDee"
order.shipto_postal_code = "30097"
order.shipto_state_region = "GA"
order.shipto_title = "Director"

api_response = channel_partner_api.estimate_shipping_for_channel_partner_order(order)
estimates = api_response.estimates

# TODO: Apply one estimate shipping method (name) and cost to your channel partner order.

for estimate in estimates:
    print(estimate)
require 'ultracart_api'
require_relative '../constants'

# This is a helper function for call centers to calculate the shipping cost on an order.  In a typical flow, the call center
# will collect all the shipping information and items being purchased into a ChannelPartnerOrder object.
# They will then call this method, passing in the order object.  The response will contain the shipping estimates
# that the call center can present to the customer.  Once the customer selects a particulate estimate,
# they can then plug that cost into their call center application and complete the order.
#
# Possible Errors:
# Using an API key that is not tied to a channel partner: "This API Key does not have permission to interact with channel partner orders.  Please review your Channel Partner configuration."
# Order has invalid channel partner code: "Invalid channel partner code"
# Order has no items: "null order.items passed." or "order.items array contains a null entry."
# Order has no channel partner order id: "order.channelPartnerOrderId must be specified."
# Order channel partner order id is a duplicate:  "order.channelPartnerOrderId [XYZ] already used."
# Channel Partner is inactive: "partner is inactive."

channel_partner_api = UltracartClient::ChannelPartnerApi.new_using_api_key(Constants::CHANNEL_PARTNER_API_KEY)

order = UltracartClient::ChannelPartnerOrder.new
order.channel_partner_order_id = "widget-1245-abc-1"
order.coupons = ["10OFF"]
# DeliveryDate will impact shipping estimates if there is a delivery deadline.
# order.delivery_date = (Time.now + (14 * 24 * 60 * 60)).iso8601

item = UltracartClient::ChannelPartnerOrderItem.new
# item.arbitrary_unit_cost = 9.99
# item.auto_order_last_rebill_dts = (Time.now - (30 * 24 * 60 * 60)).iso8601
# item.auto_order_schedule = "Weekly"
item.merchant_item_id = "shirt"

size_option = UltracartClient::ChannelPartnerOrderItemOption.new
size_option.name = "Size"
size_option.value = "Small"

color_option = UltracartClient::ChannelPartnerOrderItemOption.new
color_option.name = "Color"
color_option.value = "Orange"

item.options = [size_option, color_option]
item.quantity = 1
item.upsell = false

order.items = [item]

# order.ship_on_date = (Time.now + (7 * 24 * 60 * 60)).iso8601
order.ship_to_residential = true
order.ship_to_address1 = "55 Main Street"
order.ship_to_address2 = "Suite 202"
order.ship_to_city = "Duluth"
order.ship_to_company = "Widgets Inc"
order.ship_to_country_code = "US"
order.ship_to_day_phone = "6785552323"
order.ship_to_evening_phone = "7703334444"
order.ship_to_first_name = "Sally"
order.ship_to_last_name = "McGonkyDee"
order.ship_to_postal_code = "30097"
order.ship_to_state_region = "GA"
order.ship_to_title = "Director"

api_response = channel_partner_api.estimate_shipping_for_channel_partner_order(order)
estimates = api_response.estimates

# TODO: Apply one estimate shipping method (name) and cost to your channel partner order.

estimates.each do |estimate|
  p estimate
end
import {
    ChannelPartnerOrder
} from 'ultracart_rest_api_v2_typescript';
import {channelPartnerApi} from '../api';

/**
 * This is a helper function for call centers to calculate the shipping cost on an order.  In a typical flow, the call center
 * will collect all the shipping information and items being purchased into a ChannelPartnerOrder object.
 * They will then call this method, passing in the order object.  The response will contain the shipping estimates
 * that the call center can present to the customer.  Once the customer selects a particulate estimate,
 * they can then plug that cost into their call center application and complete the order.
 *
 * Possible Errors:
 * Using an API key that is not tied to a channel partner: "This API Key does not have permission to interact with channel partner orders.  Please review your Channel Partner configuration."
 * Order has invalid channel partner code: "Invalid channel partner code"
 * Order has no items: "null order.items passed." or "order.items array contains a null entry."
 * Order has no channel partner order id: "order.channelPartnerOrderId must be specified."
 * Order channel partner order id is a duplicate:  "order.channelPartnerOrderId [XYZ] already used."
 * Channel Partner is inactive: "partner is inactive."
 */
export class EstimateShippingForChannelPartnerOrder {
    /**
     * Execute method to estimate shipping for a channel partner order
     */
    public static async execute(): Promise<void> {
        console.log(`--- ${this.name} ---`);

        try {
            // Prepare the channel partner order
            const order: ChannelPartnerOrder = {
                channel_partner_order_id: "widget-1245-abc-1",
                coupons: ["10OFF"],
                // Uncomment and modify as needed
                // deliveryDate: DateTime.now().plus({ days: 14 }).toISO(),
                items: [
                    {
                        // Commented out properties preserved from original code
                        // arbitraryUnitCost: 9.99,
                        // autoOrderLastRebillDts: DateTime.now().minus({ days: 30 }).toISO(),
                        // autoOrderSchedule: "Weekly",
                        merchant_item_id: "shirt",
                        options: [
                            {
                                name: "Size",
                                value: "Small"
                            },
                            {
                                name: "Color",
                                value: "Orange"
                            }
                        ],
                        quantity: 1,
                        upsell: false,
                    }
                ],
                // Uncomment and modify as needed
                // shipOnDate: DateTime.now().plus({ days: 7 }).toISO(),
                ship_to_residential: true,
                shipto_address1: "55 Main Street",
                shipto_address2: "Suite 202",
                shipto_city: "Duluth",
                shipto_company: "Widgets Inc",
                shipto_country_code: "US",
                shipto_day_phone: "6785552323",
                shipto_evening_phone: "7703334444",
                shipto_first_name: "Sally",
                shipto_last_name: "McGonkyDee",
                shipto_postal_code: "30097",
                shipto_state_region: "GA",
                shipto_title: "Director"
            };

            // Estimate shipping for the order
            const apiResponse = await channelPartnerApi.estimateShippingForChannelPartnerOrder({channelPartnerOrder: order});
            const estimates = apiResponse.estimates;

            // TODO: Apply one estimate shipping method (name) and cost to your channel partner order.

            if (estimates !== undefined) {
                // Display shipping estimates
                estimates.forEach(estimate => {
                    console.log(estimate);
                });

                console.log(`Retrieved ${estimates.length} shipping estimates`);
            }
        } catch (ex: unknown) {
            // Type the error as unknown and log details
            if (ex instanceof Error) {
                console.error(`Error: ${ex.message}`);
                console.error(ex.stack);
            } else {
                console.error("An unknown error occurred");
            }
        }
    }
}

Estimate tax for channel partner order

Permissions:
  • channel_partner_read

Consumes: application/json
Produces: application/json
post
/channel_partner/estimate_tax

Estimate tax for order from a channel partner.

SDK Function Name: estimateTaxForChannelPartnerOrder

Parameters
Parameter Description Location Data Type Required
channel_partner_order Order needing tax estimate body ChannelPartnerOrder required
Responses
Status Code Reason Response Model
200
Successful response ChannelPartnerEstimateTaxResponse
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.Reflection;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;

namespace SdkSample.channel_partner
{
    public class EstimateTaxForChannelPartnerOrder
    {
        /*
         This is a helper function for call centers to calculate the tax on an order.  In a typical flow, the call center
         will collect all the shipping information and items being purchased into a ChannelPartnerOrder object.
         They will then call this method, passing in the order object.  The response will contain the tax that should be
         collected.  They can then plug that tax into their call center application and complete the order.

         Possible Errors:
         Using an API key that is not tied to a channel partner: "This API Key does not have permission to interact with channel partner orders.  Please review your Channel Partner configuration."
         Order has invalid channel partner code: "Invalid channel partner code"
         Order has no items: "null order.items passed." or "order.items array contains a null entry."
         Order has no channel partner order id: "order.channelPartnerOrderId must be specified."
         Order channel partner order id is a duplicate:  "order.channelPartnerOrderId [XYZ] already used."
         Channel Partner is inactive: "partner is inactive."
        */
        public static void Execute()
        {
            Console.WriteLine("--- " + MethodBase.GetCurrentMethod()?.DeclaringType?.Name + " ---");
            
            try
            {
                // Create channel partner API instance using API key
                ChannelPartnerApi channelPartnerApi = new ChannelPartnerApi(Constants.ChannelPartnerApiKey);
                
                ChannelPartnerOrder order = new ChannelPartnerOrder()
                {
                    ChannelPartnerOrderId = "widget-1245-abc-1",
                    Coupons = new List<string>() { "10OFF" },
                    // DeliveryDate will impact shipping estimates if there is a delivery deadline.  
                    // DeliveryDate =
                    //    DateTime.Now.AddDays(14).ToString("s", System.Globalization.CultureInfo.InvariantCulture),
                    Items = new List<ChannelPartnerOrderItem>()
                    {
                        new ChannelPartnerOrderItem()
                        {
                            // ArbitraryUnitCost = 9.99m,
                            // AutoOrderLastRebillDts = DateTime.Now.AddDays(-30).ToString("s", System.Globalization.CultureInfo.InvariantCulture),
                            // AutoOrderSchedule = "Weekly",
                            MerchantItemId = "shirt",
                            Options = new List<ChannelPartnerOrderItemOption>()
                            {
                                new ChannelPartnerOrderItemOption()
                                {
                                    Name = "Size",
                                    Value = "Small"
                                },
                                new ChannelPartnerOrderItemOption()
                                {
                                    Name = "Color",
                                    Value = "Orange"
                                }
                            },
                            Quantity = 1,
                            Upsell = false,
                        }
                    },
                    // ShipOnDate = DateTime.Now.AddDays(7).ToString("s", System.Globalization.CultureInfo.InvariantCulture),
                    ShipToResidential = true,
                    ShiptoAddress1 = "55 Main Street",
                    ShiptoAddress2 = "Suite 202",
                    ShiptoCity = "Duluth",
                    ShiptoCompany = "Widgets Inc",
                    ShiptoCountryCode = "US",
                    ShiptoDayPhone = "6785552323",
                    ShiptoEveningPhone = "7703334444",
                    ShiptoFirstName = "Sally",
                    ShiptoLastName = "McGonkyDee",
                    ShiptoPostalCode = "30097",
                    ShiptoStateRegion = "GA",
                    ShiptoTitle = "Director"
                };
                
                var apiResponse = channelPartnerApi.EstimateTaxForChannelPartnerOrder(order);
                var arbitraryTax = apiResponse.ArbitraryTax;
                // TODO: Apply this tax to your channel partner order.
                
                Console.WriteLine($"Estimated tax: {arbitraryTax}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
                Console.WriteLine(ex.StackTrace);
            }
        }
    }
}
package channel_partner;

import com.ultracart.admin.v2.ChannelPartnerApi;
import com.ultracart.admin.v2.models.ChannelPartnerEstimateTaxResponse;
import com.ultracart.admin.v2.models.ChannelPartnerOrder;
import com.ultracart.admin.v2.models.ChannelPartnerOrderItem;
import com.ultracart.admin.v2.models.ChannelPartnerOrderItemOption;

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

public class EstimateTaxForChannelPartnerOrder {
  /*
   This is a helper function for call centers to calculate the tax on an order.  In a typical flow, the call center
   will collect all the shipping information and items being purchased into a ChannelPartnerOrder object.
   They will then call this method, passing in the order object.  The response will contain the tax that should be
   collected.  They can then plug that tax into their call center application and complete the order.

   Possible Errors:
   Using an API key that is not tied to a channel partner: "This API Key does not have permission to interact with channel partner orders.  Please review your Channel Partner configuration."
   Order has invalid channel partner code: "Invalid channel partner code"
   Order has no items: "null order.items passed." or "order.items array contains a null entry."
   Order has no channel partner order id: "order.channelPartnerOrderId must be specified."
   Order channel partner order id is a duplicate:  "order.channelPartnerOrderId [XYZ] already used."
   Channel Partner is inactive: "partner is inactive."
  */
  public static void execute() {
    System.out.println("--- EstimateTaxForChannelPartnerOrder ---");

    try {
      // Create channel partner API instance using API key
      ChannelPartnerApi channelPartnerApi = new ChannelPartnerApi(common.Constants.CHANNEL_PARTNER_API_KEY);

      ChannelPartnerOrder order = new ChannelPartnerOrder();
      order.setChannelPartnerOrderId("widget-1245-abc-1");

      ArrayList<String> coupons = new ArrayList<String>();
      coupons.add("10OFF");
      order.setCoupons(coupons);

      // DeliveryDate will impact shipping estimates if there is a delivery deadline.
      // order.setDeliveryDate(Instant.now().plus(14, java.time.temporal.ChronoUnit.DAYS).toString());

      ArrayList<ChannelPartnerOrderItem> items = new ArrayList<ChannelPartnerOrderItem>();
      ChannelPartnerOrderItem item = new ChannelPartnerOrderItem();
      // item.setArbitraryUnitCost(new BigDecimal("9.99"));
      // item.setAutoOrderLastRebillDts(Instant.now().minus(30, java.time.temporal.ChronoUnit.DAYS).toString());
      // item.setAutoOrderSchedule("Weekly");
      item.setMerchantItemId("shirt");

      ArrayList<ChannelPartnerOrderItemOption> options = new ArrayList<ChannelPartnerOrderItemOption>();
      ChannelPartnerOrderItemOption sizeOption = new ChannelPartnerOrderItemOption();
      sizeOption.setName("Size");
      sizeOption.setValue("Small");
      options.add(sizeOption);

      ChannelPartnerOrderItemOption colorOption = new ChannelPartnerOrderItemOption();
      colorOption.setName("Color");
      colorOption.setValue("Orange");
      options.add(colorOption);

      item.setOptions(options);
      item.setQuantity(BigDecimal.valueOf(1));
      item.setUpsell(false);
      items.add(item);
      order.setItems(items);

      // order.setShipOnDate(Instant.now().plus(7, java.time.temporal.ChronoUnit.DAYS).toString());
      order.setShipToResidential(true);
      order.setShiptoAddress1("55 Main Street");
      order.setShiptoAddress2("Suite 202");
      order.setShiptoCity("Duluth");
      order.setShiptoCompany("Widgets Inc");
      order.setShiptoCountryCode("US");
      order.setShiptoDayPhone("6785552323");
      order.setShiptoEveningPhone("7703334444");
      order.setShiptoFirstName("Sally");
      order.setShiptoLastName("McGonkyDee");
      order.setShiptoPostalCode("30097");
      order.setShiptoStateRegion("GA");
      order.setShiptoTitle("Director");

      ChannelPartnerEstimateTaxResponse apiResponse = channelPartnerApi.estimateTaxForChannelPartnerOrder(order);
      BigDecimal arbitraryTax = apiResponse.getArbitraryTax();
      // TODO: Apply this tax to your channel partner order.

      System.out.println("Estimated tax: " + arbitraryTax);
    } catch (Exception ex) {
      System.out.println("Error: " + ex.getMessage());
      ex.printStackTrace();
    }
  }
}
import { channelPartnerApi } from '../api.js';

/**
 * This is a helper function for call centers to calculate the shipping cost on an order.  In a typical flow, the call center
 * will collect all the shipping information and items being purchased into a ChannelPartnerOrder object.
 * They will then call this method, passing in the order object.  The response will contain the shipping estimates
 * that the call center can present to the customer.  Once the customer selects a particulate estimate,
 * they can then plug that cost into their call center application and complete the order.
 *
 * Possible Errors:
 * Using an API key that is not tied to a channel partner: "This API Key does not have permission to interact with channel partner orders.  Please review your Channel Partner configuration."
 * Order has invalid channel partner code: "Invalid channel partner code"
 * Order has no items: "null order.items passed." or "order.items array contains a null entry."
 * Order has no channel partner order id: "order.channelPartnerOrderId must be specified."
 * Order channel partner order id is a duplicate:  "order.channelPartnerOrderId [XYZ] already used."
 * Channel Partner is inactive: "partner is inactive."
 */
export class EstimateTaxForChannelPartnerOrder {
    /**
     * Execute method to estimate shipping for a channel partner order
     */
    static async execute() {
        console.log(`--- ${this.name} ---`);

        try {
            // Prepare the channel partner order
            const order = {
                channel_partner_order_id: "widget-1245-abc-1",
                coupons: ["10OFF"],
                // Uncomment and modify as needed
                // deliveryDate: DateTime.now().plus({ days: 14 }).toISO(),
                items: [
                    {
                        // Commented out properties preserved from original code
                        // arbitraryUnitCost: 9.99,
                        // autoOrderLastRebillDts: DateTime.now().minus({ days: 30 }).toISO(),
                        // autoOrderSchedule: "Weekly",
                        merchant_item_id: "shirt",
                        options: [
                            {
                                name: "Size",
                                value: "Small"
                            },
                            {
                                name: "Color",
                                value: "Orange"
                            }
                        ],
                        quantity: 1,
                        upsell: false,
                    }
                ],
                // Uncomment and modify as needed
                // shipOnDate: DateTime.now().plus({ days: 7 }).toISO(),
                ship_to_residential: true,
                shipto_address1: "55 Main Street",
                shipto_address2: "Suite 202",
                shipto_city: "Duluth",
                shipto_company: "Widgets Inc",
                shipto_country_code: "US",
                shipto_day_phone: "6785552323",
                shipto_evening_phone: "7703334444",
                shipto_first_name: "Sally",
                shipto_last_name: "McGonkyDee",
                shipto_postal_code: "30097",
                shipto_state_region: "GA",
                shipto_title: "Director"
            };

            // Estimate shipping for the order
            const apiResponse = await new Promise((resolve, reject) => {
                channelPartnerApi.estimateTaxForChannelPartnerOrder(
                    order,
                    function (error, data, response) {
                        if (error) {
                            reject(error);
                        } else {
                            resolve(data);
                        }
                    }
                );
            });

            const tax = apiResponse.arbitrary_tax;
            console.log(`Retrieved tax of ${tax}`);

        } catch (ex) {
            // Log details of the error
            if (ex instanceof Error) {
                console.error(`Error: ${ex.message}`);
                console.error(ex.stack);
            } else {
                console.error("An unknown error occurred");
            }
        }
    }
}

<?php

ini_set('display_errors', 1);

/*
 This is a helper function for call centers to calculate the tax on an order.  In a typical flow, the call center
 will collect all the shipping information and items being purchased into a ChannelPartnerOrder object.
 They will then call this method, passing in the order object.  The response will contain the tax that should be
 collected.  They can then plug that tax into their call center application and complete the order.

 Possible Errors:
 Using an API key that is not tied to a channel partner: "This API Key does not have permission to interact with channel partner orders.  Please review your Channel Partner configuration."
 Order has invalid channel partner code: "Invalid channel partner code"
 Order has no items: "null order.items passed." or "order.items array contains a null entry."
 Order has no channel partner order id: "order.channelPartnerOrderId must be specified."
 Order channel partner order id is a duplicate:  "order.channelPartnerOrderId [XYZ] already used."
 Channel Partner is inactive: "partner is inactive."


 */


use ultracart\v2\api\ChannelPartnerApi;
use ultracart\v2\models\ChannelPartnerOrder;
use ultracart\v2\models\ChannelPartnerOrderItem;
use ultracart\v2\models\ChannelPartnerOrderItemOption;

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


$channel_partner_api = ChannelPartnerApi::usingApiKey(Constants::CHANNEL_PARTNER_API_KEY);

$order = new ChannelPartnerOrder();
$order->setChannelPartnerOrderId("widget-1245-abc-1");
$order->setCoupons(["10OFF"]);
// DeliveryDate will impact shipping estimates if there is a delivery deadline.
// $order->setDeliveryDate(date('c', strtotime('+14 days')));

$item = new ChannelPartnerOrderItem();
// $item->setArbitraryUnitCost(9.99);
// $item->setAutoOrderLastRebillDts(date('c', strtotime('-30 days')));
// $item->setAutoOrderSchedule("Weekly");
$item->setMerchantItemId("shirt");

$sizeOption = new ChannelPartnerOrderItemOption();
$sizeOption->setName("Size");
$sizeOption->setValue("Small");

$colorOption = new ChannelPartnerOrderItemOption();
$colorOption->setName("Color");
$colorOption->setValue("Orange");

$item->setOptions([$sizeOption, $colorOption]);
$item->setQuantity(1);
$item->setUpsell(false);

$order->setItems([$item]);

// $order->setShipOnDate(date('c', strtotime('+7 days')));
$order->setShipToResidential(true);
$order->setShiptoAddress1("55 Main Street");
$order->setShiptoAddress2("Suite 202");
$order->setShiptoCity("Duluth");
$order->setShiptoCompany("Widgets Inc");
$order->setShiptoCountryCode("US");
$order->setShiptoDayPhone("6785552323");
$order->setShiptoEveningPhone("7703334444");
$order->setShiptoFirstName("Sally");
$order->setShiptoLastName("McGonkyDee");
$order->setShiptoPostalCode("30097");
$order->setShiptoStateRegion("GA");
$order->setShiptoTitle("Director");


$api_response = $channel_partner_api->estimateTaxForChannelPartnerOrder($order);
$arbitraryTax = $api_response->getArbitraryTax();
// TODO: Apply this tax to your channel partner order.


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

from ultracart.apis import ChannelPartnerApi
from ultracart.models import ChannelPartnerOrder, ChannelPartnerOrderItem, ChannelPartnerOrderItemOption
from samples import channel_partner_api_client

channel_partner_api = ChannelPartnerApi(channel_partner_api_client())

order = ChannelPartnerOrder()
order.channel_partner_order_id = "widget-1245-abc-1"
order.coupons = ["10OFF"]
# DeliveryDate will impact shipping estimates if there is a delivery deadline.
# order.delivery_date = (datetime.now() + timedelta(days=14)).isoformat()

item = ChannelPartnerOrderItem()
# item.arbitrary_unit_cost = 9.99
# item.auto_order_last_rebill_dts = (datetime.now() - timedelta(days=30)).isoformat()
# item.auto_order_schedule = "Weekly"
item.merchant_item_id = "shirt"

size_option = ChannelPartnerOrderItemOption()
size_option.name = "Size"
size_option.value = "Small"

color_option = ChannelPartnerOrderItemOption()
color_option.name = "Color"
color_option.value = "Orange"

item.options = [size_option, color_option]
item.quantity = 1
item.upsell = False

order.items = [item]

# order.ship_on_date = (datetime.now() + timedelta(days=7)).isoformat()
order.ship_to_residential = True
order.shipto_address1 = "55 Main Street"
order.shipto_address2 = "Suite 202"
order.shipto_city = "Duluth"
order.shipto_company = "Widgets Inc"
order.shipto_country_code = "US"
order.shipto_day_phone = "6785552323"
ord
require 'ultracart_api'
require_relative '../constants'

# This is a helper function for call centers to calculate the tax on an order.  In a typical flow, the call center
# will collect all the shipping information and items being purchased into a ChannelPartnerOrder object.
# They will then call this method, passing in the order object.  The response will contain the tax that should be
# collected.  They can then plug that tax into their call center application and complete the order.
#
# Possible Errors:
# Using an API key that is not tied to a channel partner: "This API Key does not have permission to interact with channel partner orders.  Please review your Channel Partner configuration."
# Order has invalid channel partner code: "Invalid channel partner code"
# Order has no items: "null order.items passed." or "order.items array contains a null entry."
# Order has no channel partner order id: "order.channelPartnerOrderId must be specified."
# Order channel partner order id is a duplicate:  "order.channelPartnerOrderId [XYZ] already used."
# Channel Partner is inactive: "partner is inactive."

channel_partner_api = UltracartClient::ChannelPartnerApi.new_using_api_key(Constants::CHANNEL_PARTNER_API_KEY)

order = UltracartClient::ChannelPartnerOrder.new
order.channel_partner_order_id = "widget-1245-abc-1"
order.coupons = ["10OFF"]
# DeliveryDate will impact shipping estimates if there is a delivery deadline.
# order.delivery_date = (Time.now + (14 * 24 * 60 * 60)).iso8601

item = UltracartClient::ChannelPartnerOrderItem.new
# item.arbitrary_unit_cost = 9.99
# item.auto_order_last_rebill_dts = (Time.now - (30 * 24 * 60 * 60)).iso8601
# item.auto_order_schedule = "Weekly"
item.merchant_item_id = "shirt"

size_option = UltracartClient::ChannelPartnerOrderItemOption.new
size_option.name = "Size"
size_option.value = "Small"

color_option = UltracartClient::ChannelPartnerOrderItemOption.new
color_option.name = "Color"
color_option.value = "Orange"

item.options = [size_option, color_option]
item.quantity = 1
item.upsell = false

order.items = [item]

# order.ship_on_date = (Time.now + (7 * 24 * 60 * 60)).iso8601
order.ship_to_residential = true
order.ship_to_address1 = "55 Main Street"
order.ship_to_address2 = "Suite 202"
order.ship_to_city = "Duluth"
order.ship_to_company = "Widgets Inc"
order.ship_to_country_code = "US"
order.ship_to_day_phone = "6785552323"
order.ship_to_evening_phone = "7703334444"
order.ship_to_first_name = "Sally"
order.ship_to_last_name = "McGonkyDee"
order.ship_to_postal_code = "30097"
order.ship_to_state_region = "GA"
order.ship_to_title = "Director"

api_response = channel_partner_api.estimate_tax_for_channel_partner_order(order)
arbitrary_tax = api_response.arbitrary_tax
# TODO: Apply this tax to your channel partner order.

p arbitrary_tax
import {
    ChannelPartnerOrder
} from 'ultracart_rest_api_v2_typescript';
import {channelPartnerApi} from '../api';

/**
 * This is a helper function for call centers to calculate the shipping cost on an order.  In a typical flow, the call center
 * will collect all the shipping information and items being purchased into a ChannelPartnerOrder object.
 * They will then call this method, passing in the order object.  The response will contain the shipping estimates
 * that the call center can present to the customer.  Once the customer selects a particulate estimate,
 * they can then plug that cost into their call center application and complete the order.
 *
 * Possible Errors:
 * Using an API key that is not tied to a channel partner: "This API Key does not have permission to interact with channel partner orders.  Please review your Channel Partner configuration."
 * Order has invalid channel partner code: "Invalid channel partner code"
 * Order has no items: "null order.items passed." or "order.items array contains a null entry."
 * Order has no channel partner order id: "order.channelPartnerOrderId must be specified."
 * Order channel partner order id is a duplicate:  "order.channelPartnerOrderId [XYZ] already used."
 * Channel Partner is inactive: "partner is inactive."
 */
export class EstimateTaxForChannelPartnerOrder {
    /**
     * Execute method to estimate shipping for a channel partner order
     */
    public static async execute(): Promise<void> {
        console.log(`--- ${this.name} ---`);

        try {
            // Prepare the channel partner order
            const order: ChannelPartnerOrder = {
                channel_partner_order_id: "widget-1245-abc-1",
                coupons: ["10OFF"],
                // Uncomment and modify as needed
                // deliveryDate: DateTime.now().plus({ days: 14 }).toISO(),
                items: [
                    {
                        // Commented out properties preserved from original code
                        // arbitraryUnitCost: 9.99,
                        // autoOrderLastRebillDts: DateTime.now().minus({ days: 30 }).toISO(),
                        // autoOrderSchedule: "Weekly",
                        merchant_item_id: "shirt",
                        options: [
                            {
                                name: "Size",
                                value: "Small"
                            },
                            {
                                name: "Color",
                                value: "Orange"
                            }
                        ],
                        quantity: 1,
                        upsell: false,
                    }
                ],
                // Uncomment and modify as needed
                // shipOnDate: DateTime.now().plus({ days: 7 }).toISO(),
                ship_to_residential: true,
                shipto_address1: "55 Main Street",
                shipto_address2: "Suite 202",
                shipto_city: "Duluth",
                shipto_company: "Widgets Inc",
                shipto_country_code: "US",
                shipto_day_phone: "6785552323",
                shipto_evening_phone: "7703334444",
                shipto_first_name: "Sally",
                shipto_last_name: "McGonkyDee",
                shipto_postal_code: "30097",
                shipto_state_region: "GA",
                shipto_title: "Director"
            };

            // Estimate shipping for the order
            const apiResponse = await channelPartnerApi.estimateTaxForChannelPartnerOrder({channelPartnerOrder: order});
            const tax = apiResponse.arbitrary_tax;

            console.log(`Retrieved tax of ${tax}`);

        } catch (ex: unknown) {
            // Type the error as unknown and log details
            if (ex instanceof Error) {
                console.error(`Error: ${ex.message}`);
                console.error(ex.stack);
            } else {
                console.error("An unknown error occurred");
            }
        }
    }
}

Insert channel partner order

Permissions:
  • channel_partner_write

Consumes: application/json
Produces: application/json
post
/channel_partner/import

Insert order from a channel partner.

SDK Function Name: importChannelPartnerOrder

Parameters
Parameter Description Location Data Type Required
channel_partner_order Order to insert body ChannelPartnerOrder required
Responses
Status Code Reason Response Model
200
Successful response ChannelPartnerImportResponse
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.Reflection;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;

namespace SdkSample.channel_partner
{
    public class ImportChannelPartnerOrder
    {
        /*
            To run channel partner examples, you will need:
            1) An API Key: https://secure.ultracart.com/merchant/configuration/apiManagementApp.do
            2) That API Key must be assigned to a channel partner: https://secure.ultracart.com/merchant/configuration/customChannelPartnerListLoad.do

            The spreadsheet import docs will serve you well here.  They describe many fields
            https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1377246/Channel+Partner+API+-+Spreadsheet+Import
        */
        public static void Execute()
        {
            Console.WriteLine("--- " + MethodBase.GetCurrentMethod()?.DeclaringType?.Name + " ---");
            var doFirstExample = false;
            try
            {
                // Create channel partner API instance using API key
                ChannelPartnerApi channelPartnerApi = new ChannelPartnerApi(Constants.ChannelPartnerApiKey);
                
                // NOTICE:
                // The real difficulty with using this API is the hosted fields requirement for credit card information.
                // You will need to incorporate UltraCart hosted fields in your Customer Service UI and capture credit card
                // information through the hosted fields and then provide the tokens here.  You CANNOT provide raw credit
                // card information via this interface.
                // The two fields in this API are hostedFieldsCardToken and hostedFieldsCvvToken
                // Within this sdk_samples github project, review the /hosted_fields/hosted_fields.html file for an example
                
                // There are TWO examples.  The first is an order that still needs the credit card charged.  This example uses
                // the hosted fields to collect payment information and pass it to UltraCart for processing.  The second example
                // already has payment processed and just passes in the authorization information.
                
                // ---------------------------------------------
                // ---------------------------------------------
                // Example 1 - Order needs payment processing
                // ---------------------------------------------
                // ---------------------------------------------
                
                ChannelPartnerOrder order = new ChannelPartnerOrder();

                if (doFirstExample)
                {

                    // order.AdvertisingSource = "Friend"; // https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1377001/Advertising+Sources
                    // order.AffiliateId = 856234; // https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1377727/Affiliates
                    // order.AffiliateSubId = 1234; // https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1376754/Allowing+Affiliates+to+use+Sub-IDs
                    // order.ArbitraryShippingHandlingTotal = 9.99;
                    // order.ArbitraryTax = 2.50;
                    // order.ArbitraryTaxRate = 7.0;
                    // order.ArbitraryTaxableSubtotal = 69.99;

                    order.AssociateWithCustomerProfileIfPresent = true;
                    order.AutoApprovePurchaseOrder = true;
                    order.BilltoAddress1 = "11460 Johns Creek Parkway";
                    order.BilltoAddress2 = "Suite 101";
                    order.BilltoCity = "Duluth";
                    order.BilltoCompany = "Widgets Inc";
                    order.BilltoCountryCode = "US";
                    order.BilltoDayPhone = "6784153823";
                    order.BilltoEveningPhone = "6784154019";
                    order.BilltoFirstName = "John";
                    order.BilltoLastName = "Smith";
                    order.BilltoPostalCode = "30097";
                    order.BilltoStateRegion = "GA";
                    order.BilltoTitle = "Sir";
                    order.CcEmail = "orders@widgets.com";
                    order.ChannelPartnerOrderId = "widget-1245-abc";
                    order.ConsiderRecurring = false;
                    order.Coupons = new List<string> { "10OFF", "BUY1GET1" };

                    // order.CreditCardAuthorizationAmount = 69.99;
                    // order.CreditCardAuthorizationDts = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ssK"); // this will usually not be 'now'. it will be the actual auth date
                    // order.CreditCardAuthorizationNumber = "1234";

                    order.CreditCardExpirationMonth = 5;
                    order.CreditCardExpirationYear = 2032;
                    order.CreditCardType = "VISA"; // see the hosted fields below for the card number and cvv tokens
                    order.CustomField1 = "Whatever";
                    order.CustomField2 = "You";
                    order.CustomField3 = "Want";
                    order.CustomField4 = "Can";
                    order.CustomField5 = "Go";
                    order.CustomField6 = "In";
                    order.CustomField7 = "CustomFields";
                    order.DeliveryDate = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ssK");
                    order.Email = "ceo@widgets.com";
                    order.Gift = false;

                    order.GiftEmail = "sally@aol.com";
                    order.GiftMessage = "Congratulations on your promotion!";

                    order.HostedFieldsCardToken = "7C97B0AAA26AB10180B4B29F00380101";
                    order.HostedFieldsCvvToken = "C684AB4336787F0180B4B51971380101";

                    // order.InsuranceApplicationId = insuranceApplicationId; // these are used by only a handful of specialized merchants
                    // order.InsuranceClaimId = insuranceClaimId; // these are used by only a handful of specialized merchants

                    order.IpAddress = "34.125.95.217";

                    // -- Items start ---
                    ChannelPartnerOrderItem item = new ChannelPartnerOrderItem();
                    // item.ArbitraryUnitCost = 9.99;
                    // item.AutoOrderLastRebillDts = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ssK");
                    // item.AutoOrderSchedule = "Weekly";

                    item.MerchantItemId = "shirt";
                    item.Quantity = 1;
                    item.Upsell = false;

                    ChannelPartnerOrderItemOption itemOption1 = new ChannelPartnerOrderItemOption();
                    itemOption1.Name = "Size";
                    itemOption1.Value = "Small";

                    ChannelPartnerOrderItemOption itemOption2 = new ChannelPartnerOrderItemOption();
                    itemOption2.Name = "Color";
                    itemOption2.Value = "Orange";

                    item.Options = new List<ChannelPartnerOrderItemOption> { itemOption1, itemOption2 };

                    order.Items = new List<ChannelPartnerOrderItem> { item };
                    // -- Items End ---


                    order.LeastCostRoute = true; // Give me the lowest cost shipping
                    order.LeastCostRouteShippingMethods = new List<string>
                        { "FedEx: Ground", "UPS: Ground", "USPS: Priority" };
                    order.MailingListOptIn =
                        true; // Yes, I confirmed with the customer personally they wish to be on my mailing lists.
                    order.NoRealtimePaymentProcessing = false;
                    order.PaymentMethod = ChannelPartnerOrder.PaymentMethodEnum.CreditCard;
                    // order.PurchaseOrderNumber = "PO-12345";
                    order.RotatingTransactionGatewayCode =
                        "MyStripe"; // We wish this to be charged against our Stripe gateway
                    order.ScreenBrandingThemeCode =
                        "SF1986"; // Theme codes predated StoreFronts. Each StoreFront still has a theme code under the hood. We need that here. See this screen to find your code: https://secure.ultracart.com/merchant/configuration/customerServiceLoad.do
                    order.ShipOnDate = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ssK");
                    order.ShipToResidential = true;
                    // order.ShippingMethod = "FedEx: Ground"; // We're using LeastCostRoute, so we do not supply this value
                    order.ShiptoAddress1 = "55 Main Street";
                    order.ShiptoAddress2 = "Suite 202";
                    order.ShiptoCity = "Duluth";
                    order.ShiptoCompany = "Widgets Inc";
                    order.ShiptoCountryCode = "US";
                    order.ShiptoDayPhone = "6785552323";
                    order.ShiptoEveningPhone = "7703334444";
                    order.ShiptoFirstName = "Sally";
                    order.ShiptoLastName = "McGonkyDee";
                    order.ShiptoPostalCode = "30097";
                    order.ShiptoStateRegion = "GA";
                    order.ShiptoTitle = "Director";
                    order.SkipPaymentProcessing = false;
                    order.SpecialInstructions =
                        "Please wrap this in bubble wrap because my FedEx delivery guy is abusive to packages";
                    order.StoreCompleted =
                        false; // this will bypass everything, including shipping. useful only for importing old orders long completed
                    order.StorefrontHostName = "store.mysite.com";
                    order.StoreIfPaymentDeclines =
                        false; // if payment fails, this can send it to Accounts Receivable. Do not want that. Fail if payment fails.
                    order.TaxCounty = "Gwinnett";
                    order.TaxExempt = false;

                    ChannelPartnerOrderTransaction orderTransaction = new ChannelPartnerOrderTransaction();
                    orderTransaction.Successful = false; // we haven't charged the card yet, so this is false.
                    orderTransaction.Details =
                        new List<ChannelPartnerOrderTransactionDetail>(); // we haven't charged the card yet, so this is empty.
                    order.Transaction = orderTransaction;
                    order.TreatWarningsAsErrors = true;

                    var apiResponse = channelPartnerApi.ImportChannelPartnerOrder(order);
                }

                // ---------------------------------------------
                // ---------------------------------------------
                // Example 2 - Order already processed
                // ---------------------------------------------
                // ---------------------------------------------
                
                ChannelPartnerOrder processedOrder = new ChannelPartnerOrder();
                
                // processedOrder.AdvertisingSource = "Friend"; // https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1377001/Advertising+Sources
                // processedOrder.AffiliateId = 856234; // https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1377727/Affiliates
                // processedOrder.AffiliateSubId = 1234; // https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1376754/Allowing+Affiliates+to+use+Sub-IDs
                // processedOrder.ArbitraryShippingHandlingTotal = 9.99;
                // processedOrder.ArbitraryTax = 2.50;
                // processedOrder.ArbitraryTaxRate = 7.0;
                // processedOrder.ArbitraryTaxableSubtotal = 69.99;
                
                processedOrder.AssociateWithCustomerProfileIfPresent = true;
                processedOrder.AutoApprovePurchaseOrder = true;
                processedOrder.BilltoAddress1 = "11460 Johns Creek Parkway";
                processedOrder.BilltoAddress2 = "Suite 101";
                processedOrder.BilltoCity = "Duluth";
                processedOrder.BilltoCompany = "Widgets Inc";
                processedOrder.BilltoCountryCode = "US";
                processedOrder.BilltoDayPhone = "6784153823";
                processedOrder.BilltoEveningPhone = "6784154019";
                processedOrder.BilltoFirstName = "John";
                processedOrder.BilltoLastName = "Smith";
                processedOrder.BilltoPostalCode = "30097";
                processedOrder.BilltoStateRegion = "GA";
                processedOrder.BilltoTitle = "Sir";
                processedOrder.CcEmail = "orders@widgets.com";
                processedOrder.ChannelPartnerOrderId = "widget-1245-abc";
                processedOrder.ConsiderRecurring = false;
                processedOrder.Coupons = new List<string> { "10OFF", "BUY1GET1" };
                
                // processedOrder.CreditCardAuthorizationAmount = 69.99;
                // processedOrder.CreditCardAuthorizationDts = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ssK"); // this will usually not be 'now'. it will be the actual auth date
                // processedOrder.CreditCardAuthorizationNumber = "1234";
                
                processedOrder.CreditCardExpirationMonth = 5;
                processedOrder.CreditCardExpirationYear = 2032;
                processedOrder.CreditCardType = "VISA"; // see the hosted fields below for the card number and cvv tokens
                processedOrder.CustomField1 = "Whatever";
                processedOrder.CustomField2 = "You";
                processedOrder.CustomField3 = "Want";
                processedOrder.CustomField4 = "Can";
                processedOrder.CustomField5 = "Go";
                processedOrder.CustomField6 = "In";
                processedOrder.CustomField7 = "CustomFields";
                processedOrder.DeliveryDate = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ssK");
                processedOrder.Email = "ceo@widgets.com";
                processedOrder.Gift = false;
                
                processedOrder.GiftEmail = "sally@aol.com";
                processedOrder.GiftMessage = "Congratulations on your promotion!";
                
                // processedOrder.InsuranceApplicationId = insuranceApplicationId; // these are used by only a handful of specialized merchants
                // processedOrder.InsuranceClaimId = insuranceClaimId; // these are used by only a handful of specialized merchants
                
                processedOrder.IpAddress = "34.125.95.217";
                
                // -- Items start ---
                ChannelPartnerOrderItem processedItem = new ChannelPartnerOrderItem();
                // processedItem.ArbitraryUnitCost = 9.99;
                // processedItem.AutoOrderLastRebillDts = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ssK");
                // processedItem.AutoOrderSchedule = "Weekly";
                
                processedItem.MerchantItemId = "shirt";
                processedItem.Quantity = 1;
                processedItem.Upsell = false;
                
                ChannelPartnerOrderItemOption processedItemOption1 = new ChannelPartnerOrderItemOption();
                processedItemOption1.Name = "Size";
                processedItemOption1.Value = "Small";
                
                ChannelPartnerOrderItemOption processedItemOption2 = new ChannelPartnerOrderItemOption();
                processedItemOption2.Name = "Color";
                processedItemOption2.Value = "Orange";
                
                processedItem.Options = new List<ChannelPartnerOrderItemOption> { processedItemOption1, processedItemOption2 };
                
                processedOrder.Items = new List<ChannelPartnerOrderItem> { processedItem };
                // -- Items End ---
                
                // We don't use least cost routing here. We've already completed the order and should know what shipping method
                // the customer was charged for. So that is set in the processedOrder.ShippingMethod property.
                // processedOrder.LeastCostRoute = true; // Give me the lowest cost shipping
                // processedOrder.LeastCostRouteShippingMethods = new List<string> { "FedEx: Ground", "UPS: Ground", "USPS: Priority" };
                processedOrder.MailingListOptIn = true; // Yes, I confirmed with the customer personally they wish to be on my mailing lists.
                processedOrder.NoRealtimePaymentProcessing = true; // nothing to charge, payment was already collected
                processedOrder.PaymentMethod = ChannelPartnerOrder.PaymentMethodEnum.CreditCard;
                // processedOrder.PurchaseOrderNumber = "PO-12345";
                processedOrder.RotatingTransactionGatewayCode = "MyStripe"; // We wish this to be charged against our Stripe gateway
                processedOrder.ScreenBrandingThemeCode = "SF1986"; // Theme codes predated StoreFronts. Each StoreFront still has a theme code under the hood. We need that here. See this screen to find your code: https://secure.ultracart.com/merchant/configuration/customerServiceLoad.do
                processedOrder.ShipOnDate = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ssK");
                processedOrder.ShipToResidential = true;
                processedOrder.ShippingMethod = "FedEx: Ground";
                processedOrder.ShiptoAddress1 = "55 Main Street";
                processedOrder.ShiptoAddress2 = "Suite 202";
                processedOrder.ShiptoCity = "Duluth";
                processedOrder.ShiptoCompany = "Widgets Inc";
                processedOrder.ShiptoCountryCode = "US";
                processedOrder.ShiptoDayPhone = "6785552323";
                processedOrder.ShiptoEveningPhone = "7703334444";
                processedOrder.ShiptoFirstName = "Sally";
                processedOrder.ShiptoLastName = "McGonkyDee";
                processedOrder.ShiptoPostalCode = "30097";
                processedOrder.ShiptoStateRegion = "GA";
                processedOrder.ShiptoTitle = "Director";
                processedOrder.SkipPaymentProcessing = true; // bypass payment
                processedOrder.SpecialInstructions = "Please wrap this in bubble wrap because my FedEx delivery guy is abusive to packages";
                processedOrder.StoreCompleted = true; // this is an old order or an order handled completely outside UltraCart, so do not do anything to it. Just store it.
                processedOrder.StorefrontHostName = "store.mysite.com";
                processedOrder.StoreIfPaymentDeclines = false; // if payment fails, this can send it to Accounts Receivable. Do not want that. Fail if payment fails.
                processedOrder.TaxCounty = "Gwinnett";
                processedOrder.TaxExempt = false;
                
                ChannelPartnerOrderTransaction processedOrderTransaction = new ChannelPartnerOrderTransaction();
                processedOrderTransaction.Successful = true; // transaction was successful
                
                ChannelPartnerOrderTransactionDetail td1 = new ChannelPartnerOrderTransactionDetail(); // 'td' is short for transaction detail
                td1.Name = "AVS Code";
                td1.Value = "X";
                
                ChannelPartnerOrderTransactionDetail td2 = new ChannelPartnerOrderTransactionDetail();
                td2.Name = "Authorization Code";
                td2.Value = "123456";
                
                ChannelPartnerOrderTransactionDetail td3 = new ChannelPartnerOrderTransactionDetail();
                td3.Name = "CVV Code";
                td3.Value = "M";
                
                ChannelPartnerOrderTransactionDetail td4 = new ChannelPartnerOrderTransactionDetail();
                td4.Name = "Response Code";
                td4.Value = "Authorized";
                
                ChannelPartnerOrderTransactionDetail td5 = new ChannelPartnerOrderTransactionDetail();
                td5.Name = "Reason Code";
                td5.Value = "1";
                
                ChannelPartnerOrderTransactionDetail td6 = new ChannelPartnerOrderTransactionDetail();
                td6.Name = "Response Subcode";
                td6.Value = "1";
                
                ChannelPartnerOrderTransactionDetail td7 = new ChannelPartnerOrderTransactionDetail();
                td7.Name = "Transaction ID";
                td7.Value = "1234567890";
                
                processedOrderTransaction.Details = new List<ChannelPartnerOrderTransactionDetail> { td1, td2, td3, td4, td5, td6, td7 };
                processedOrder.Transaction = processedOrderTransaction;
                processedOrder.TreatWarningsAsErrors = true;
                
                var processedApiResponse = channelPartnerApi.ImportChannelPartnerOrder(processedOrder);
                
                Console.WriteLine("Orders imported successfully");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
                Console.WriteLine(ex.StackTrace);
            }
        }
    }
}
package channel_partner;

import com.ultracart.admin.v2.ChannelPartnerApi;
import com.ultracart.admin.v2.models.*;

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

public class ImportChannelPartnerOrder {
  /*
      To run channel partner examples, you will need:
      1) An API Key: https://secure.ultracart.com/merchant/configuration/apiManagementApp.do
      2) That API Key must be assigned to a channel partner: https://secure.ultracart.com/merchant/configuration/customChannelPartnerListLoad.do

      The spreadsheet import docs will serve you well here.  They describe many fields
      https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1377246/Channel+Partner+API+-+Spreadsheet+Import
  */
  public static void execute() {
    System.out.println("--- ImportChannelPartnerOrder ---");

    try {
      // Create channel partner API instance using API key
      ChannelPartnerApi channelPartnerApi = new ChannelPartnerApi(common.Constants.CHANNEL_PARTNER_API_KEY);

      // NOTICE:
      // The real difficulty with using this API is the hosted fields requirement for credit card information.
      // You will need to incorporate UltraCart hosted fields in your Customer Service UI and capture credit card
      // information through the hosted fields and then provide the tokens here.  You CANNOT provide raw credit
      // card information via this interface.
      // The two fields in this API are hostedFieldsCardToken and hostedFieldsCvvToken
      // Within this sdk_samples github project, review the /hosted_fields/hosted_fields.html file for an example

      // There are TWO examples.  The first is an order that still needs the credit card charged.  This example uses
      // the hosted fields to collect payment information and pass it to UltraCart for processing.  The second example
      // already has payment processed and just passes in the authorization information.

      // ---------------------------------------------
      // ---------------------------------------------
      // Example 1 - Order needs payment processing
      // ---------------------------------------------
      // ---------------------------------------------

      ChannelPartnerOrder order = new ChannelPartnerOrder();

      // order.setAdvertisingSource("Friend"); // https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1377001/Advertising+Sources
      // order.setAffiliateId(856234); // https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1377727/Affiliates
      // order.setAffiliateSubId(1234); // https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1376754/Allowing+Affiliates+to+use+Sub-IDs
      // order.setArbitraryShippingHandlingTotal(new java.math.BigDecimal("9.99"));
      // order.setArbitraryTax(new java.math.BigDecimal("2.50"));
      // order.setArbitraryTaxRate(new java.math.BigDecimal("7.0"));
      // order.setArbitraryTaxableSubtotal(new java.math.BigDecimal("69.99"));

      order.setAssociateWithCustomerProfileIfPresent(true);
      order.setAutoApprovePurchaseOrder(true);
      order.setBilltoAddress1("11460 Johns Creek Parkway");
      order.setBilltoAddress2("Suite 101");
      order.setBilltoCity("Duluth");
      order.setBilltoCompany("Widgets Inc");
      order.setBilltoCountryCode("US");
      order.setBilltoDayPhone("6784153823");
      order.setBilltoEveningPhone("6784154019");
      order.setBilltoFirstName("John");
      order.setBilltoLastName("Smith");
      order.setBilltoPostalCode("30097");
      order.setBilltoStateRegion("GA");
      order.setBilltoTitle("Sir");
      order.setCcEmail("orders@widgets.com");
      order.setChannelPartnerOrderId("widget-1245-abc");
      order.setConsiderRecurring(false);

      ArrayList<String> coupons = new ArrayList<String>();
      coupons.add("10OFF");
      coupons.add("BUY1GET1");
      order.setCoupons(coupons);

      // order.setCreditCardAuthorizationAmount(new java.math.BigDecimal("69.99"));
      // order.setCreditCardAuthorizationDts(Instant.now().toString()); // this will usually not be 'now'. it will be the actual auth date
      // order.setCreditCardAuthorizationNumber("1234");

      order.setCreditCardExpirationMonth(5);
      order.setCreditCardExpirationYear(2032);
      order.setCreditCardType("VISA"); // see the hosted fields below for the card number and cvv tokens
      order.setCustomField1("Whatever");
      order.setCustomField2("You");
      order.setCustomField3("Want");
      order.setCustomField4("Can");
      order.setCustomField5("Go");
      order.setCustomField6("In");
      order.setCustomField7("CustomFields");
      order.setDeliveryDate(Instant.now().toString());
      order.setEmail("ceo@widgets.com");
      order.setGift(false);

      order.setGiftEmail("sally@aol.com");
      order.setGiftMessage("Congratulations on your promotion!");

      order.setHostedFieldsCardToken("7C97B0AAA26AB10180B4B29F00380101");
      order.setHostedFieldsCvvToken("C684AB4336787F0180B4B51971380101");

      // order.setInsuranceApplicationId(insuranceApplicationId); // these are used by only a handful of specialized merchants
      // order.setInsuranceClaimId(insuranceClaimId); // these are used by only a handful of specialized merchants

      order.setIpAddress("34.125.95.217");

      // -- Items start ---
      ChannelPartnerOrderItem item = new ChannelPartnerOrderItem();
      // item.setArbitraryUnitCost(new java.math.BigDecimal("9.99"));
      // item.setAutoOrderLastRebillDts(Instant.now().toString());
      // item.setAutoOrderSchedule("Weekly");

      item.setMerchantItemId("shirt");
      item.setQuantity(BigDecimal.valueOf(1));
      item.setUpsell(false);

      ChannelPartnerOrderItemOption itemOption1 = new ChannelPartnerOrderItemOption();
      itemOption1.setName("Size");
      itemOption1.setValue("Small");

      ChannelPartnerOrderItemOption itemOption2 = new ChannelPartnerOrderItemOption();
      itemOption2.setName("Color");
      itemOption2.setValue("Orange");

      ArrayList<ChannelPartnerOrderItemOption> options = new ArrayList<ChannelPartnerOrderItemOption>();
      options.add(itemOption1);
      options.add(itemOption2);
      item.setOptions(options);

      ArrayList<ChannelPartnerOrderItem> items = new ArrayList<ChannelPartnerOrderItem>();
      items.add(item);
      order.setItems(items);
      // -- Items End ---

      order.setLeastCostRoute(true); // Give me the lowest cost shipping
      ArrayList<String> shippingMethods = new ArrayList<String>();
      shippingMethods.add("FedEx: Ground");
      shippingMethods.add("UPS: Ground");
      shippingMethods.add("USPS: Priority");
      order.setLeastCostRouteShippingMethods(shippingMethods);
      order.setMailingListOptIn(true); // Yes, I confirmed with the customer personally they wish to be on my mailing lists.
      order.setNoRealtimePaymentProcessing(false);
      order.setPaymentMethod(ChannelPartnerOrder.PaymentMethodEnum.CREDIT_CARD);
      // order.setPurchaseOrderNumber("PO-12345");
      order.setRotatingTransactionGatewayCode("MyStripe"); // We wish this to be charged against our Stripe gateway
      order.setScreenBrandingThemeCode("SF1986"); // Theme codes predated StoreFronts. Each StoreFront still has a theme code under the hood. We need that here. See this screen to find your code: https://secure.ultracart.com/merchant/configuration/customerServiceLoad.do
      order.setShipOnDate(Instant.now().toString());
      order.setShipToResidential(true);
      // order.setShippingMethod("FedEx: Ground"); // We're using LeastCostRoute, so we do not supply this value
      order.setShiptoAddress1("55 Main Street");
      order.setShiptoAddress2("Suite 202");
      order.setShiptoCity("Duluth");
      order.setShiptoCompany("Widgets Inc");
      order.setShiptoCountryCode("US");
      order.setShiptoDayPhone("6785552323");
      order.setShiptoEveningPhone("7703334444");
      order.setShiptoFirstName("Sally");
      order.setShiptoLastName("McGonkyDee");
      order.setShiptoPostalCode("30097");
      order.setShiptoStateRegion("GA");
      order.setShiptoTitle("Director");
      order.setSkipPaymentProcessing(false);
      order.setSpecialInstructions("Please wrap this in bubble wrap because my FedEx delivery guy is abusive to packages");
      order.setStoreCompleted(false); // this will bypass everything, including shipping. useful only for importing old orders long completed
      order.setStorefrontHostName("store.mysite.com");
      order.setStoreIfPaymentDeclines(false); // if payment fails, this can send it to Accounts Receivable. Do not want that. Fail if payment fails.
      order.setTaxCounty("Gwinnett");
      order.setTaxExempt(false);

      ChannelPartnerOrderTransaction orderTransaction = new ChannelPartnerOrderTransaction();
      orderTransaction.setSuccessful(false); // we haven't charged the card yet, so this is false.
      orderTransaction.setDetails(new ArrayList<ChannelPartnerOrderTransactionDetail>()); // we haven't charged the card yet, so this is empty.
      order.setTransaction(orderTransaction);
      order.setTreatWarningsAsErrors(true);

      ChannelPartnerImportResponse apiResponse = channelPartnerApi.importChannelPartnerOrder(order);

      // ---------------------------------------------
      // ---------------------------------------------
      // Example 2 - Order already processed
      // ---------------------------------------------
      // ---------------------------------------------

      ChannelPartnerOrder processedOrder = new ChannelPartnerOrder();

      // processedOrder.setAdvertisingSource("Friend"); // https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1377001/Advertising+Sources
      // processedOrder.setAffiliateId(856234); // https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1377727/Affiliates
      // processedOrder.setAffiliateSubId(1234); // https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1376754/Allowing+Affiliates+to+use+Sub-IDs
      // processedOrder.setArbitraryShippingHandlingTotal(new java.math.BigDecimal("9.99"));
      // processedOrder.setArbitraryTax(new java.math.BigDecimal("2.50"));
      // processedOrder.setArbitraryTaxRate(new java.math.BigDecimal("7.0"));
      // processedOrder.setArbitraryTaxableSubtotal(new java.math.BigDecimal("69.99"));

      processedOrder.setAssociateWithCustomerProfileIfPresent(true);
      processedOrder.setAutoApprovePurchaseOrder(true);
      processedOrder.setBilltoAddress1("11460 Johns Creek Parkway");
      processedOrder.setBilltoAddress2("Suite 101");
      processedOrder.setBilltoCity("Duluth");
      processedOrder.setBilltoCompany("Widgets Inc");
      processedOrder.setBilltoCountryCode("US");
      processedOrder.setBilltoDayPhone("6784153823");
      processedOrder.setBilltoEveningPhone("6784154019");
      processedOrder.setBilltoFirstName("John");
      processedOrder.setBilltoLastName("Smith");
      processedOrder.setBilltoPostalCode("30097");
      processedOrder.setBilltoStateRegion("GA");
      processedOrder.setBilltoTitle("Sir");
      processedOrder.setCcEmail("orders@widgets.com");
      processedOrder.setChannelPartnerOrderId("widget-1245-abc");
      processedOrder.setConsiderRecurring(false);

      ArrayList<String> processedCoupons = new ArrayList<String>();
      processedCoupons.add("10OFF");
      processedCoupons.add("BUY1GET1");
      processedOrder.setCoupons(processedCoupons);

      // processedOrder.setCreditCardAuthorizationAmount(new java.math.BigDecimal("69.99"));
      // processedOrder.setCreditCardAuthorizationDts(Instant.now().toString()); // this will usually not be 'now'. it will be the actual auth date
      // processedOrder.setCreditCardAuthorizationNumber("1234");

      processedOrder.setCreditCardExpirationMonth(5);
      processedOrder.setCreditCardExpirationYear(2032);
      processedOrder.setCreditCardType("VISA"); // see the hosted fields below for the card number and cvv tokens
      processedOrder.setCustomField1("Whatever");
      processedOrder.setCustomField2("You");
      processedOrder.setCustomField3("Want");
      processedOrder.setCustomField4("Can");
      processedOrder.setCustomField5("Go");
      processedOrder.setCustomField6("In");
      processedOrder.setCustomField7("CustomFields");
      processedOrder.setDeliveryDate(Instant.now().toString());
      processedOrder.setEmail("ceo@widgets.com");
      processedOrder.setGift(false);

      processedOrder.setGiftEmail("sally@aol.com");
      processedOrder.setGiftMessage("Congratulations on your promotion!");

      // processedOrder.setInsuranceApplicationId(insuranceApplicationId); // these are used by only a handful of specialized merchants
      // processedOrder.setInsuranceClaimId(insuranceClaimId); // these are used by only a handful of specialized merchants

      processedOrder.setIpAddress("34.125.95.217");

      // -- Items start ---
      ChannelPartnerOrderItem processedItem = new ChannelPartnerOrderItem();
      // processedItem.setArbitraryUnitCost(new java.math.BigDecimal("9.99"));
      // processedItem.setAutoOrderLastRebillDts(Instant.now().toString());
      // processedItem.setAutoOrderSchedule("Weekly");

      processedItem.setMerchantItemId("shirt");
      processedItem.setQuantity(BigDecimal.valueOf(1));
      processedItem.setUpsell(false);

      ChannelPartnerOrderItemOption processedItemOption1 = new ChannelPartnerOrderItemOption();
      processedItemOption1.setName("Size");
      processedItemOption1.setValue("Small");

      ChannelPartnerOrderItemOption processedItemOption2 = new ChannelPartnerOrderItemOption();
      processedItemOption2.setName("Color");
      processedItemOption2.setValue("Orange");

      ArrayList<ChannelPartnerOrderItemOption> processedOptions = new ArrayList<ChannelPartnerOrderItemOption>();
      processedOptions.add(processedItemOption1);
      processedOptions.add(processedItemOption2);
      processedItem.setOptions(processedOptions);

      ArrayList<ChannelPartnerOrderItem> processedItems = new ArrayList<ChannelPartnerOrderItem>();
      processedItems.add(processedItem);
      processedOrder.setItems(processedItems);
      // -- Items End ---

      // We don't use least cost routing here. We've already completed the order and should know what shipping method
      // the customer was charged for. So that is set in the processedOrder.ShippingMethod property.
      // processedOrder.setLeastCostRoute(true); // Give me the lowest cost shipping
      // ArrayList<String> processedShippingMethods = new ArrayList<String>();
      // processedShippingMethods.add("FedEx: Ground");
      // processedShippingMethods.add("UPS: Ground");
      // processedShippingMethods.add("USPS: Priority");
      // processedOrder.setLeastCostRouteShippingMethods(processedShippingMethods);
      processedOrder.setMailingListOptIn(true); // Yes, I confirmed with the customer personally they wish to be on my mailing lists.
      processedOrder.setNoRealtimePaymentProcessing(true); // nothing to charge, payment was already collected
      processedOrder.setPaymentMethod(ChannelPartnerOrder.PaymentMethodEnum.CREDIT_CARD);
      // processedOrder.setPurchaseOrderNumber("PO-12345");
      processedOrder.setRotatingTransactionGatewayCode("MyStripe"); // We wish this to be charged against our Stripe gateway
      processedOrder.setScreenBrandingThemeCode("SF1986"); // Theme codes predated StoreFronts. Each StoreFront still has a theme code under the hood. We need that here. See this screen to find your code: https://secure.ultracart.com/merchant/configuration/customerServiceLoad.do
      processedOrder.setShipOnDate(Instant.now().toString());
      processedOrder.setShipToResidential(true);
      processedOrder.setShippingMethod("FedEx: Ground");
      processedOrder.setShiptoAddress1("55 Main Street");
      processedOrder.setShiptoAddress2("Suite 202");
      processedOrder.setShiptoCity("Duluth");
      processedOrder.setShiptoCompany("Widgets Inc");
      processedOrder.setShiptoCountryCode("US");
      processedOrder.setShiptoDayPhone("6785552323");
      processedOrder.setShiptoEveningPhone("7703334444");
      processedOrder.setShiptoFirstName("Sally");
      processedOrder.setShiptoLastName("McGonkyDee");
      processedOrder.setShiptoPostalCode("30097");
      processedOrder.setShiptoStateRegion("GA");
      processedOrder.setShiptoTitle("Director");
      processedOrder.setSkipPaymentProcessing(true); // bypass payment
      processedOrder.setSpecialInstructions("Please wrap this in bubble wrap because my FedEx delivery guy is abusive to packages");
      processedOrder.setStoreCompleted(true); // this is an old order or an order handled completely outside UltraCart, so do not do anything to it. Just store it.
      processedOrder.setStorefrontHostName("store.mysite.com");
      processedOrder.setStoreIfPaymentDeclines(false); // if payment fails, this can send it to Accounts Receivable. Do not want that. Fail if payment fails.
      processedOrder.setTaxCounty("Gwinnett");
      processedOrder.setTaxExempt(false);

      ChannelPartnerOrderTransaction processedOrderTransaction = new ChannelPartnerOrderTransaction();
      processedOrderTransaction.setSuccessful(true); // transaction was successful

      ArrayList<ChannelPartnerOrderTransactionDetail> details = new ArrayList<ChannelPartnerOrderTransactionDetail>();
      ChannelPartnerOrderTransactionDetail td1 = new ChannelPartnerOrderTransactionDetail(); // 'td' is short for transaction detail
      td1.setName("AVS Code");
      td1.setValue("X");
      details.add(td1);

      ChannelPartnerOrderTransactionDetail td2 = new ChannelPartnerOrderTransactionDetail();
      td2.setName("Authorization Code");
      td2.setValue("123456");
      details.add(td2);

      ChannelPartnerOrderTransactionDetail td3 = new ChannelPartnerOrderTransactionDetail();
      td3.setName("CVV Code");
      td3.setValue("M");
      details.add(td3);

      ChannelPartnerOrderTransactionDetail td4 = new ChannelPartnerOrderTransactionDetail();
      td4.setName("Response Code");
      td4.setValue("Authorized");
      details.add(td4);

      ChannelPartnerOrderTransactionDetail td5 = new ChannelPartnerOrderTransactionDetail();
      td5.setName("Reason Code");
      td5.setValue("1");
      details.add(td5);

      ChannelPartnerOrderTransactionDetail td6 = new ChannelPartnerOrderTransactionDetail();
      td6.setName("Response Subcode");
      td6.setValue("1");
      details.add(td6);

      ChannelPartnerOrderTransactionDetail td7 = new ChannelPartnerOrderTransactionDetail();
      td7.setName("Transaction ID");
      td7.setValue("1234567890");
      details.add(td7);

      processedOrderTransaction.setDetails(details);
      processedOrder.setTransaction(processedOrderTransaction);
      processedOrder.setTreatWarningsAsErrors(true);

      ChannelPartnerImportResponse processedApiResponse = channelPartnerApi.importChannelPartnerOrder(processedOrder);

      System.out.println("Orders imported successfully");
    } catch (Exception ex) {
      System.out.println("Error: " + ex.getMessage());
      ex.printStackTrace();
    }
  }
}
import { DateTime } from 'luxon';
import { channelPartnerApi } from '../api.js';

/**
 * Imports channel partner orders into UltraCart
 *
 * To run channel partner examples, you will need:
 * 1) An API Key: https://secure.ultracart.com/merchant/configuration/apiManagementApp.do
 * 2) That API Key must be assigned to a channel partner: https://secure.ultracart.com/merchant/configuration/customChannelPartnerListLoad.do
 *
 * The spreadsheet import docs will serve you well here. They describe many fields
 * https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1377246/Channel+Partner+API+-+Spreadsheet+Import
 */
export async function execute() {
    console.log(`--- ${execute.name} ---`);

    try {
        // ---------------------------------------------
        // Example 1 - Order needs payment processing
        // ---------------------------------------------
        const order = {
            associate_with_customer_profile_if_present: true,
            auto_approve_purchase_order: true,
            billto_address1: "11460 Johns Creek Parkway",
            billto_address2: "Suite 101",
            billto_city: "Duluth",
            billto_company: "Widgets Inc",
            billto_country_code: "US",
            billto_day_phone: "6784153823",
            billto_evening_phone: "6784154019",
            billto_first_name: "John",
            billto_last_name: "Smith",
            billto_postal_code: "30097",
            billto_state_region: "GA",
            billto_title: "Sir",
            cc_email: "orders@widgets.com",
            channel_partner_order_id: "widget-1245-abc",
            consider_recurring: false,
            coupons: ["10OFF", "BUY1GET1"],
            credit_card_expiration_month: 5,
            credit_card_expiration_year: 2032,
            credit_card_type: "VISA",
            custom_field1: "Whatever",
            custom_field2: "You",
            custom_field3: "Want",
            custom_field4: "Can",
            custom_field5: "Go",
            custom_field6: "In",
            custom_field7: "CustomFields",
            delivery_date: DateTime.now().toISO(),
            email: "ceo@widgets.com",
            gift: false,
            gift_email: "sally@aol.com",
            gift_message: "Congratulations on your promotion!",
            hosted_fields_card_token: "7C97B0AAA26AB10180B4B29F00380101",
            hosted_fields_cvv_token: "C684AB4336787F0180B4B51971380101",
            ip_address: "34.125.95.217",
            least_cost_route: true,
            least_cost_route_shipping_methods: ["FedEx: Ground", "UPS: Ground", "USPS: Priority"],
            mailing_list_opt_in: true,
            no_realtime_payment_processing: false,
            payment_method: "CreditCard",
            rotating_transaction_gateway_code: "MyStripe",
            screen_branding_theme_code: "SF1986",
            ship_on_date: DateTime.now().toISO(),
            ship_to_residential: true,
            shipto_address1: "55 Main Street",
            shipto_address2: "Suite 202",
            shipto_city: "Duluth",
            shipto_company: "Widgets Inc",
            shipto_country_code: "US",
            shipto_day_phone: "6785552323",
            shipto_evening_phone: "7703334444",
            shipto_first_name: "Sally",
            shipto_last_name: "McGonkyDee",
            shipto_postal_code: "30097",
            shipto_state_region: "GA",
            shipto_title: "Director",
            skip_payment_processing: false,
            special_instructions: "Please wrap this in bubble wrap because my FedEx delivery guy is abusive to packages",
            store_completed: false,
            storefront_host_name: "store.mysite.com",
            store_if_payment_declines: false,
            tax_county: "Gwinnett",
            tax_exempt: false,
            treat_warnings_as_errors: true,

            // Items
            items: [{
                merchant_item_id: "shirt",
                quantity: 1,
                upsell: false,
                options: [
                    { name: "Size", value: "Small" },
                    { name: "Color", value: "Orange" }
                ]
            }],

            // Transaction
            transaction: {
                successful: false,
                details: []
            }
        };

        // Import the first order
        const apiResponse = await new Promise((resolve, reject) => {
            channelPartnerApi.importChannelPartnerOrder(order, (error, data, response) => {
                if (error) {
                    reject(error);
                } else {
                    resolve(data, response);
                }
            });
        });

        // ---------------------------------------------
        // Example 2 - Order already processed
        // ---------------------------------------------
        const processedOrder = {
            ...order,
            no_realtime_payment_processing: true,
            skip_payment_processing: true,
            store_completed: true,
            shipping_method: "FedEx: Ground",
            transaction: {
                successful: true,
                details: [
                    { name: "AVS Code", value: "X" },
                    { name: "Authorization Code", value: "123456" },
                    { name: "CVV Code", value: "M" },
                    { name: "Response Code", value: "Authorized" },
                    { name: "Reason Code", value: "1" },
                    { name: "Response Subcode", value: "1" },
                    { name: "Transaction ID", value: "1234567890" }
                ]
            }
        };

        // Import the processed order
        const processedApiResponse = await new Promise((resolve, reject) => {
            channelPartnerApi.importChannelPartnerOrder(processedOrder, (error, data, response) => {
                if (error) {
                    reject(error);
                } else {
                    resolve(data, response);
                }
            });
        });

        console.log("Orders imported successfully");
    } catch (ex) {
        console.error(`Error: ${ex instanceof Error ? ex.message : 'Unknown error'}`);
        console.error(ex instanceof Error ? ex.stack : ex);
    }
}

// Optional: If you want to run this directly
if (require.main === module) {
    execute().catch(console.error);
}

<?php

ini_set('display_errors', 1);

/*
    To run channel partner examples, you will need:
    1) An API Key: https://secure.ultracart.com/merchant/configuration/apiManagementApp.do
    2) That API Key must be assigned to a channel partner: https://secure.ultracart.com/merchant/configuration/customChannelPartnerListLoad.do

    The spreadsheet import docs will serve you well here.  They describe many fields
    https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1377246/Channel+Partner+API+-+Spreadsheet+Import

 */


use ultracart\v2\api\ChannelPartnerApi;
use ultracart\v2\models\ChannelPartnerOrder;
use ultracart\v2\models\ChannelPartnerOrderItem;
use ultracart\v2\models\ChannelPartnerOrderItemOption;
use ultracart\v2\models\ChannelPartnerOrderTransaction;
use ultracart\v2\models\ChannelPartnerOrderTransactionDetail;

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


$channel_partner_api = ChannelPartnerApi::usingApiKey(Constants::CHANNEL_PARTNER_API_KEY);

// NOTICE:
// The real difficulty with using this API is the hosted fields requirement for credit card information.
// You will need to incorporate UltraCart hosted fields in your Customer Service UI and capture credit card
// information through the hosted fields and then provide the tokens here.  You CANNOT provide raw credit
// card information via this interface.
// The two fields in this API are hostedFieldsCardToken and hostedFieldsCvvToken
// Within this sdk_samples github project, review the /hosted_fields/hosted_fields.html file for an example

// There are TWO examples.  The first is an order that still needs the credit card charged.  This example uses
// the hosted fields to collect payment information and pass it to UltraCart for processing.  The second example
// already has payment processed and just passes in the authorization information.

// ---------------------------------------------
// ---------------------------------------------
// Example 1 - Order needs payment processing
// ---------------------------------------------
// ---------------------------------------------

$order = new ChannelPartnerOrder();

// $order->setAdvertisingSource("Friend"); // https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1377001/Advertising+Sources
// $order->setAffiliateId(856234); // https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1377727/Affiliates
// $order->setAffiliateSubId(1234); // https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1376754/Allowing+Affiliates+to+use+Sub-IDs
// $order->setArbitraryShippingHandlingTotal(9.99);
// $order->setArbitraryTax(2.50);
// $order->setArbitraryTaxRate(7.0);
// $order->setArbitraryTaxableSubtotal(69.99);

$order->setAssociateWithCustomerProfileIfPresent(true);
$order->setAutoApprovePurchaseOrder(true);
$order->setBilltoAddress1("11460 Johns Creek Parkway");
$order->setBilltoAddress2("Suite 101");
$order->setBilltoCity("Duluth");
$order->setBilltoCompany("Widgets Inc");
$order->setBilltoCountryCode("US");
$order->setBilltoDayPhone("6784153823");
$order->setBilltoEveningPhone("6784154019");
$order->setBilltoFirstName("John");
$order->setBilltoLastName("Smith");
$order->setBilltoPostalCode("30097");
$order->setBilltoStateRegion("GA");
$order->setBilltoTitle("Sir");
$order->setCcEmail("orders@widgets.com");
$order->setChannelPartnerOrderId("widget-1245-abc");
$order->setConsiderRecurring(false);
$order->setCoupons(["10OFF", "BUY1GET1"]);

// $order->setCreditCardAuthorizationAmount( 69.99);
// $order->setCreditCardAuthorizationDts(date('Y-m-d', time()) . "T00:00:00+00:00"); // this will usually not be 'now'.  it will be the actual auth date
// $order->setCreditCardAuthorizationNumber("1234");

$order->setCreditCardExpirationMonth(5);
$order->setCreditCardExpirationYear(2032);
$order->setCreditCardType("VISA"); // see the hosted fields below for the card number and cvv tokens
$order->setCustomField1("Whatever");
$order->setCustomField2("You");
$order->setCustomField3("Want");
$order->setCustomField4("Can");
$order->setCustomField5("Go");
$order->setCustomField6("In");
$order->setCustomField7("CustomFields");
$order->setDeliveryDate(date('Y-m-d', time()) . "T00:00:00+00:00");
$order->setEmail("ceo@widgets.com");
$order->setGift(false);

$order->setGiftEmail("sally@aol.com");
$order->setGiftMessage("Congratulations on your promotion!");

$order->setHostedFieldsCardToken("7C97B0AAA26AB10180B4B29F00380101");
$order->setHostedFieldsCvvToken("C684AB4336787F0180B4B51971380101");

// $order->setInsuranceApplicationId(insuranceApplicationId); // these are used by only a handful of specialized merchants
// $order->setInsuranceClaimId(insuranceClaimId); // these are used by only a handful of specialized merchants

$order->setIpAddress("34.125.95.217");

// -- Items start ---
$item = new ChannelPartnerOrderItem();
// $item->setArbitraryUnitCost(9.99);
// $item->setAutoOrderLastRebillDts(date('Y-m-d', time()) . "T00:00:00+00:00");
// $item->setAutoOrderSchedule("Weekly");

$item->setMerchantItemId("shirt");
$item->setQuantity(1);
$item->setUpsell(false);

$item_option1 = new ChannelPartnerOrderItemOption();
$item_option1->setName("Size");
$item_option1->setValue("Small");

$item_option2 = new ChannelPartnerOrderItemOption();
$item_option2->setName("Color");
$item_option2->setValue("Orange");

$item->setOptions([$item_option1, $item_option2]);

$order->setItems([$item]);
// -- Items End ---


$order->setLeastCostRoute(true); // Give me the lowest cost shipping
$order->setLeastCostRouteShippingMethods(["FedEx: Ground", "UPS: Ground", "USPS: Priority"]);
$order->setMailingListOptIn(true); // Yes); I confirmed with the customer personally they wish to be on my mailing lists.
$order->setNoRealtimePaymentProcessing(false);
$order->setPaymentMethod(ChannelPartnerOrder::PAYMENT_METHOD_CREDIT_CARD);
// $order->setPurchaseOrderNumber("PO-12345");
$order->setRotatingTransactionGatewayCode("MyStripe"); // We wish this to be charged against our Stripe gateway
$order->setScreenBrandingThemeCode("SF1986"); // Theme codes predated StoreFronts.  Each StoreFront still has a theme code under the hood.  We need that here.  See this screen to find your code: https://secure.ultracart.com/merchant/configuration/customerServiceLoad.do
$order->setShipOnDate(date('Y-m-d', time()) . "T00:00:00+00:00");
$order->setShipToResidential(true);
// $order->setShippingMethod("FedEx: Ground"); // We're using LeastCostRoute); so we do not supply this value
$order->setShiptoAddress1("55 Main Street");
$order->setShiptoAddress2("Suite 202");
$order->setShiptoCity("Duluth");
$order->setShiptoCompany("Widgets Inc");
$order->setShiptoCountryCode("US");
$order->setShiptoDayPhone("6785552323");
$order->setShiptoEveningPhone("7703334444");
$order->setShiptoFirstName("Sally");
$order->setShiptoLastName("McGonkyDee");
$order->setShiptoPostalCode("30097");
$order->setShiptoStateRegion("GA");
$order->setShiptoTitle("Director");
$order->setSkipPaymentProcessing(false);
$order->setSpecialInstructions("Please wrap this in bubble wrap because my FedEx delivery guy is abusive to packages");
$order->setStoreCompleted(false); // this will bypass everything); including shipping.  useful only for importing old orders long completed
$order->setStorefrontHostName('store.mysite.com');
$order->setStoreIfPaymentDeclines(false); // if payment fails); this can send it to Accounts Receivable.  Do not want that.  Fail if payment fails.
$order->setTaxCounty("Gwinnett");
$order->setTaxExempt(false);

$orderTransaction = new ChannelPartnerOrderTransaction();
$orderTransaction->setSuccessful(false); // we haven't charged the card yet, so this is false.
$orderTransaction->setDetails([]); // we haven't charged the card yet, so this is empty.
$order->setTransaction($orderTransaction);
$order->setTreatWarningsAsErrors(true);


$api_response = $channel_partner_api->importChannelPartnerOrder($order);


// ---------------------------------------------
// ---------------------------------------------
// Example 2 - Order already processed
// ---------------------------------------------
// ---------------------------------------------

$order = new ChannelPartnerOrder();

// $order->setAdvertisingSource("Friend"); // https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1377001/Advertising+Sources
// $order->setAffiliateId(856234); // https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1377727/Affiliates
// $order->setAffiliateSubId(1234); // https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1376754/Allowing+Affiliates+to+use+Sub-IDs
// $order->setArbitraryShippingHandlingTotal(9.99);
// $order->setArbitraryTax(2.50);
// $order->setArbitraryTaxRate(7.0);
// $order->setArbitraryTaxableSubtotal(69.99);

$order->setAssociateWithCustomerProfileIfPresent(true);
$order->setAutoApprovePurchaseOrder(true);
$order->setBilltoAddress1("11460 Johns Creek Parkway");
$order->setBilltoAddress2("Suite 101");
$order->setBilltoCity("Duluth");
$order->setBilltoCompany("Widgets Inc");
$order->setBilltoCountryCode("US");
$order->setBilltoDayPhone("6784153823");
$order->setBilltoEveningPhone("6784154019");
$order->setBilltoFirstName("John");
$order->setBilltoLastName("Smith");
$order->setBilltoPostalCode("30097");
$order->setBilltoStateRegion("GA");
$order->setBilltoTitle("Sir");
$order->setCcEmail("orders@widgets.com");
$order->setChannelPartnerOrderId("widget-1245-abc");
$order->setConsiderRecurring(false);
$order->setCoupons(["10OFF", "BUY1GET1"]);

// $order->setCreditCardAuthorizationAmount( 69.99);
// $order->setCreditCardAuthorizationDts(date('Y-m-d', time()) . "T00:00:00+00:00"); // this will usually not be 'now'.  it will be the actual auth date
// $order->setCreditCardAuthorizationNumber("1234");

$order->setCreditCardExpirationMonth(5);
$order->setCreditCardExpirationYear(2032);
$order->setCreditCardType("VISA"); // see the hosted fields below for the card number and cvv tokens
$order->setCustomField1("Whatever");
$order->setCustomField2("You");
$order->setCustomField3("Want");
$order->setCustomField4("Can");
$order->setCustomField5("Go");
$order->setCustomField6("In");
$order->setCustomField7("CustomFields");
$order->setDeliveryDate(date('Y-m-d', time()) . "T00:00:00+00:00");
$order->setEmail("ceo@widgets.com");
$order->setGift(false);

$order->setGiftEmail("sally@aol.com");
$order->setGiftMessage("Congratulations on your promotion!");

// $order->setInsuranceApplicationId(insuranceApplicationId); // these are used by only a handful of specialized merchants
// $order->setInsuranceClaimId(insuranceClaimId); // these are used by only a handful of specialized merchants

$order->setIpAddress("34.125.95.217");

// -- Items start ---
$item = new ChannelPartnerOrderItem();
// $item->setArbitraryUnitCost(9.99);
// $item->setAutoOrderLastRebillDts(date('Y-m-d', time()) . "T00:00:00+00:00");
// $item->setAutoOrderSchedule("Weekly");

$item->setMerchantItemId("shirt");
$item->setQuantity(1);
$item->setUpsell(false);

$item_option1 = new ChannelPartnerOrderItemOption();
$item_option1->setName("Size");
$item_option1->setValue("Small");

$item_option2 = new ChannelPartnerOrderItemOption();
$item_option2->setName("Color");
$item_option2->setValue("Orange");

$item->setOptions([$item_option1, $item_option2]);

$order->setItems([$item]);
// -- Items End ---


// We don't use least cost routing here.  We've already completed the order and should know what shipping method
// the customer was charged for.  So that is set in the $order->setShippingMethod() function.
// $order->setLeastCostRoute(true); // Give me the lowest cost shipping
// $order->setLeastCostRouteShippingMethods(["FedEx: Ground", "UPS: Ground", "USPS: Priority"]);
$order->setMailingListOptIn(true); // Yes); I confirmed with the customer personally they wish to be on my mailing lists.
$order->setNoRealtimePaymentProcessing(true); // nothing to charge, payment was already collected
$order->setPaymentMethod(ChannelPartnerOrder::PAYMENT_METHOD_CREDIT_CARD);
// $order->setPurchaseOrderNumber("PO-12345");
$order->setRotatingTransactionGatewayCode("MyStripe"); // We wish this to be charged against our Stripe gateway
$order->setScreenBrandingThemeCode("SF1986"); // Theme codes predated StoreFronts.  Each StoreFront still has a theme code under the hood.  We need that here.  See this screen to find your code: https://secure.ultracart.com/merchant/configuration/customerServiceLoad.do
$order->setShipOnDate(date('Y-m-d', time()) . "T00:00:00+00:00");
$order->setShipToResidential(true);
$order->setShippingMethod("FedEx: Ground");
$order->setShiptoAddress1("55 Main Street");
$order->setShiptoAddress2("Suite 202");
$order->setShiptoCity("Duluth");
$order->setShiptoCompany("Widgets Inc");
$order->setShiptoCountryCode("US");
$order->setShiptoDayPhone("6785552323");
$order->setShiptoEveningPhone("7703334444");
$order->setShiptoFirstName("Sally");
$order->setShiptoLastName("McGonkyDee");
$order->setShiptoPostalCode("30097");
$order->setShiptoStateRegion("GA");
$order->setShiptoTitle("Director");
$order->setSkipPaymentProcessing(true);  // bypass payment
$order->setSpecialInstructions("Please wrap this in bubble wrap because my FedEx delivery guy is abusive to packages");
$order->setStoreCompleted(true); // this is an old order or an order handled completely outside UltraCart, so do not do anything to it.  Just store it.
$order->setStorefrontHostName('store.mysite.com');
$order->setStoreIfPaymentDeclines(false); // if payment fails); this can send it to Accounts Receivable.  Do not want that.  Fail if payment fails.
$order->setTaxCounty("Gwinnett");
$order->setTaxExempt(false);

$orderTransaction = new ChannelPartnerOrderTransaction();
$orderTransaction->setSuccessful(true); // we haven't charged the card yet, so this is false.

$td1 = new ChannelPartnerOrderTransactionDetail(); // 'td' is short for transaction detail
$td1->setName("AVS Code");
$td1->setValue("X");

$td2 = new ChannelPartnerOrderTransactionDetail(); // 'td' is short for transaction detail
$td2->setName("Authorization Code");
$td2->setValue("123456");

$td3 = new ChannelPartnerOrderTransactionDetail(); // 'td' is short for transaction detail
$td3->setName("CVV Code");
$td3->setValue("M");

$td4 = new ChannelPartnerOrderTransactionDetail(); // 'td' is short for transaction detail
$td4->setName("Response Code");
$td4->setValue("Authorized");

$td5 = new ChannelPartnerOrderTransactionDetail(); // 'td' is short for transaction detail
$td5->setName("Reason Code");
$td5->setValue("1");

$td6 = new ChannelPartnerOrderTransactionDetail(); // 'td' is short for transaction detail
$td6->setName("Response Subcode");
$td6->setValue("1");

$td7 = new ChannelPartnerOrderTransactionDetail(); // 'td' is short for transaction detail
$td7->setName("Transaction ID");
$td7->setValue("1234567890");

$orderTransaction->setDetails([$td1, $td2, $td3, $td4, $td5, $td6, $td7]); //
$order->setTransaction($orderTransaction);
$order->setTreatWarningsAsErrors(true);


$api_response = $channel_partner_api->importChannelPartnerOrder($order);
from datetime import datetime
from ultracart.models import (ChannelPartnerOrder, ChannelPartnerOrderItem, 
    ChannelPartnerOrderItemOption, ChannelPartnerOrderTransaction, 
    ChannelPartnerOrderTransactionDetail)
from samples import channel_partner_api_client
from ultracart.apis import ChannelPartnerApi

channel_partner_api = ChannelPartnerApi(channel_partner_api_client())

# ---------------------------------------------
# Example 1 - Order needs payment processing
# ---------------------------------------------

order = ChannelPartnerOrder()

# order.advertising_source = "Friend"  # https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1377001/Advertising+Sources
# order.affiliate_id = 856234  # https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1377727/Affiliates
# order.affiliate_sub_id = 1234  # https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1376754/Allowing+Affiliates+to+use+Sub-IDs
# order.arbitrary_shipping_handling_total = 9.99
# order.arbitrary_tax = 2.50
# order.arbitrary_tax_rate = 7.0
# order.arbitrary_taxable_subtotal = 69.99

order.associate_with_customer_profile_if_present = True
order.auto_approve_purchase_order = True
order.billto_address1 = "11460 Johns Creek Parkway"
order.billto_address2 = "Suite 101"
order.billto_city = "Duluth"
order.billto_company = "Widgets Inc"
order.billto_country_code = "US"
order.billto_day_phone = "6784153823"
order.billto_evening_phone = "6784154019"
order.billto_first_name = "John"
order.billto_last_name = "Smith"
order.billto_postal_code = "30097"
order.billto_state_region = "GA"
order.billto_title = "Sir"
order.cc_email = "orders@widgets.com"
order.channel_partner_order_id = "widget-1245-abc"
order.consider_recurring = False
order.coupons = ["10OFF", "BUY1GET1"]

# order.credit_card_authorization_amount = 69.99
# order.credit_card_authorization_dts = datetime.now().strftime("%Y-%m-%dT%H:%M:%S+00:00")
# order.credit_card_authorization_number = "1234"

order.credit_card_expiration_month = 5
order.credit_card_expiration_year = 2032
order.credit_card_type = "VISA"
order.custom_field1 = "Whatever"
order.custom_field2 = "You"
order.custom_field3 = "Want"
order.custom_field4 = "Can"
order.custom_field5 = "Go"
order.custom_field6 = "In"
order.custom_field7 = "CustomFields"
order.delivery_date = datetime.now().strftime("%Y-%m-%dT%H:%M:%S+00:00")
order.email = "ceo@widgets.com"
order.gift = False

order.gift_email = "sally@aol.com"
order.gift_message = "Congratulations on your promotion!"

order.hosted_fields_card_token = "7C97B0AAA26AB10180B4B29F00380101"
order.hosted_fields_cvv_token = "C684AB4336787F0180B4B51971380101"

# order.insurance_application_id = insurance_application_id  # specialized merchants only
# order.insurance_claim_id = insurance_claim_id  # specialized merchants only

order.ip_address = "34.125.95.217"

# -- Items start ---
item = ChannelPartnerOrderItem()
# item.arbitrary_unit_cost = 9.99
# item.auto_order_last_rebill_dts = datetime.now().strftime("%Y-%m-%dT%H:%M:%S+00:00")
# item.auto_order_schedule = "Weekly"

item.merchant_item_id = "shirt"
item.quantity = 1.0
item.upsell = False

item_option1 = ChannelPartnerOrderItemOption()
item_option1.name = "Size"
item_option1.value = "Small"

item_option2 = ChannelPartnerOrderItemOption()
item_option2.name = "Color"
item_option2.value = "Orange"

item.options = [item_option1, item_option2]

order.items = [item]
# -- Items End ---

order.least_cost_route = True  # Give me the lowest cost shipping
order.least_cost_route_shipping_methods = ["FedEx: Ground", "UPS: Ground", "USPS: Priority"]
order.mailing_list_opt_in = True
order.no_realtime_payment_processing = False
order.payment_method = "Credit Card"
# order.purchase_order_number = "PO-12345"
order.rotating_transaction_gateway_code = "MyStripe"
order.screen_branding_theme_code = "SF1986"
order.ship_on_date = datetime.now().strftime("%Y-%m-%dT%H:%M:%S+00:00")
order.ship_to_residential = True
# order.shipping_method = "FedEx: Ground"  # Using LeastCostRoute instead
order.shipto_address1 = "55 Main Street"
order.shipto_address2 = "Suite 202"
order.shipto_city = "Duluth"
order.shipto_company = "Widgets Inc"
order.shipto_country_code = "US"
order.shipto_day_phone = "6785552323"
order.shipto_evening_phone = "7703334444"
order.shipto_first_name = "Sally"
order.shipto_last_name = "McGonkyDee"
order.shipto_postal_code = "30097"
order.shipto_state_region = "GA"
order.shipto_title = "Director"
order.skip_payment_processing = False
order.special_instructions = "Please wrap this in bubble wrap because my FedEx delivery guy is abusive to packages"
order.store_completed = False
order.storefront_host_name = 'store.mysite.com'
order.store_if_payment_declines = False
order.tax_county = "Gwinnett"
order.tax_exempt = False

order_transaction = ChannelPartnerOrderTransaction()
order_transaction.successful = False  # haven't charged card yet
order_transaction.details = []  # haven't charged card yet
order.transaction = order_transaction
order.treat_warnings_as_errors = True

api_response = channel_partner_api.import_channel_partner_order(order)

# ---------------------------------------------
# Example 2 - Order already processed
# ---------------------------------------------

order = ChannelPartnerOrder()

# order.advertising_source = "Friend"
# order.affiliate_id = 856234
# order.affiliate_sub_id = 1234
# order.arbitrary_shipping_handling_total = 9.99
# order.arbitrary_tax = 2.50
# order.arbitrary_tax_rate = 7.0
# order.arbitrary_taxable_subtotal = 69.99

order.associate_with_customer_profile_if_present = True
order.auto_approve_purchase_order = True
order.billto_address1 = "11460 Johns Creek Parkway"
order.billto_address2 = "Suite 101"
order.billto_city = "Duluth"
order.billto_company = "Widgets Inc"
order.billto_country_code = "US"
order.billto_day_phone = "6784153823"
order.billto_evening_phone = "6784154019"
order.billto_first_name = "John"
order.billto_last_name = "Smith"
order.billto_postal_code = "30097"
order.billto_state_region = "GA"
order.billto_title = "Sir"
order.cc_email = "orders@widgets.com"
order.channel_partner_order_id = "widget-1245-abc"
order.consider_recurring = False
order.coupons = ["10OFF", "BUY1GET1"]

order.credit_card_expiration_month = 5
order.credit_card_expiration_year = 2032
order.credit_card_type = "VISA"
order.custom_field1 = "Whatever"
order.custom_field2 = "You"
order.custom_field3 = "Want"
order.custom_field4 = "Can"
order.custom_field5 = "Go"
order.custom_field6 = "In"
order.custom_field7 = "CustomFields"
order.delivery_date = datetime.now().strftime("%Y-%m-%dT%H:%M:%S+00:00")
order.email = "ceo@widgets.com"
order.gift = False

order.gift_email = "sally@aol.com"
order.gift_message = "Congratulations on your promotion!"

order.ip_address = "34.125.95.217"

# -- Items start ---
item = ChannelPartnerOrderItem()
item.merchant_item_id = "shirt"
item.quantity = 1.0
item.upsell = False

item_option1 = ChannelPartnerOrderItemOption()
item_option1.name = "Size"
item_option1.value = "Small"

item_option2 = ChannelPartnerOrderItemOption()
item_option2.name = "Color"
item_option2.value = "Orange"

item.options = [item_option1, item_option2]

order.items = [item]
# -- Items End ---

order.mailing_list_opt_in = True
order.no_realtime_payment_processing = True  # payment already collected
order.payment_method = "Credit Card"
order.rotating_transaction_gateway_code = "MyStripe"
order.screen_branding_theme_code = "SF1986"
order.ship_on_date = datetime.now().strftime("%Y-%m-%dT%H:%M:%S+00:00")
order.ship_to_residential = True
order.shipping_method = "FedEx: Ground"
order.shipto_address1 = "55 Main Street"
order.shipto_address2 = "Suite 202"
order.shipto_city = "Duluth"
order.shipto_company = "Widgets Inc"
order.shipto_country_code = "US"
order.shipto_day_phone = "6785552323"
order.shipto_evening_phone = "7703334444"
order.shipto_first_name = "Sally"
order.shipto_last_name = "McGonkyDee"
order.shipto_postal_code = "30097"
order.shipto_state_region = "GA"
order.shipto_title = "Director"
order.skip_payment_processing = True  # bypass payment
order.special_instructions = "Please wrap this in bubble wrap because my FedEx delivery guy is abusive to packages"
order.store_completed = True  # old order, just store it
order.storefront_host_name = 'store.mysite.com'
order.store_if_payment_declines = False
order.tax_county = "Gwinnett"
order.tax_exempt = False

order_transaction = ChannelPartnerOrderTransaction()
order_transaction.successful = True

# Create transaction details
td1 = ChannelPartnerOrderTransactionDetail()
td1.name = "AVS Code"
td1.value = "X"

td2 = ChannelPartnerOrderTransactionDetail()
td2.name = "Authorization Code"
td2.value = "123456"

td3 = ChannelPartnerOrderTransactionDetail()
td3.name = "CVV Code"
td3.value = "M"

td4 = ChannelPartnerOrderTransactionDetail()
td4.name = "Response Code"
td4.value = "Authorized"

td5 = ChannelPartnerOrderTransactionDetail()
td5.name = "Reason Code"
td5.value = "1"

td6 = ChannelPartnerOrderTransactionDetail()
td6.name = "Response Subcode"
td6.value = "1"

td7 = ChannelPartnerOrderTransactionDetail()
td7.name = "Transaction ID"
td7.value = "1234567890"

order_transaction.details = [td1, td2, td3, td4, td5, td6, td7]
order.transaction = order_transaction
order.treat_warnings_as_errors = True

api_response = channel_partner_api.import_channel_partner_order(order)
# To run channel partner examples, you will need:
# 1) An API Key: https://secure.ultracart.com/merchant/configuration/apiManagementApp.do
# 2) That API Key must be assigned to a channel partner: https://secure.ultracart.com/merchant/configuration/customChannelPartnerListLoad.do
#
# The spreadsheet import docs will serve you well here. They describe many fields
# https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1377246/Channel+Partner+API+-+Spreadsheet+Import

require 'ultracart_api'
require_relative '../constants'

channel_partner_api = UltracartClient::ChannelPartnerApi.new_using_api_key(Constants::CHANNEL_PARTNER_API_KEY)

# NOTICE:
# The real difficulty with using this API is the hosted fields requirement for credit card information.
# You will need to incorporate UltraCart hosted fields in your Customer Service UI and capture credit card
# information through the hosted fields and then provide the tokens here. You CANNOT provide raw credit
# card information via this interface.
# The two fields in this API are hostedFieldsCardToken and hostedFieldsCvvToken
# Within this sdk_samples github project, review the /hosted_fields/hosted_fields.html file for an example

# ---------------------------------------------
# ---------------------------------------------
# Example 1 - Order needs payment processing
# ---------------------------------------------
# ---------------------------------------------

order = UltracartClient::ChannelPartnerOrder.new

# order.advertising_source = "Friend" # https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1377001/Advertising+Sources
# order.affiliate_id = 856234 # https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1377727/Affiliates
# order.affiliate_sub_id = 1234 # https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1376754/Allowing+Affiliates+to+use+Sub-IDs
# order.arbitrary_shipping_handling_total = 9.99
# order.arbitrary_tax = 2.50
# order.arbitrary_tax_rate = 7.0
# order.arbitrary_taxable_subtotal = 69.99

order.associate_with_customer_profile_if_present = true
order.auto_approve_purchase_order = true
order.billto_address1 = "11460 Johns Creek Parkway"
order.billto_address2 = "Suite 101"
order.billto_city = "Duluth"
order.billto_company = "Widgets Inc"
order.billto_country_code = "US"
order.billto_day_phone = "6784153823"
order.billto_evening_phone = "6784154019"
order.billto_first_name = "John"
order.billto_last_name = "Smith"
order.billto_postal_code = "30097"
order.billto_state_region = "GA"
order.billto_title = "Sir"
order.cc_email = "orders@widgets.com"
order.channel_partner_order_id = "widget-1245-abc"
order.consider_recurring = false
order.coupons = ["10OFF", "BUY1GET1"]

order.credit_card_expiration_month = 5
order.credit_card_expiration_year = 2032
order.credit_card_type = "VISA" # see the hosted fields below for the card number and cvv tokens
order.custom_field1 = "Whatever"
order.custom_field2 = "You"
order.custom_field3 = "Want"
order.custom_field4 = "Can"
order.custom_field5 = "Go"
order.custom_field6 = "In"
order.custom_field7 = "CustomFields"
order.delivery_date = Time.now.strftime('%Y-%m-%dT00:00:00+00:00')
order.email = "ceo@widgets.com"
order.gift = false

order.gift_email = "sally@aol.com"
order.gift_message = "Congratulations on your promotion!"

order.hosted_fields_card_token = "7C97B0AAA26AB10180B4B29F00380101"
order.hosted_fields_cvv_token = "C684AB4336787F0180B4B51971380101"

order.ip_address = "34.125.95.217"

# -- Items start ---
item = UltracartClient::ChannelPartnerOrderItem.new
# item.arbitrary_unit_cost = 9.99
# item.auto_order_last_rebill_dts = Time.now.strftime('%Y-%m-%dT00:00:00+00:00')
# item.auto_order_schedule = "Weekly"

item.merchant_item_id = "shirt"
item.quantity = 1
item.upsell = false

item_option1 = UltracartClient::ChannelPartnerOrderItemOption.new
item_option1.name = "Size"
item_option1.value = "Small"

item_option2 = UltracartClient::ChannelPartnerOrderItemOption.new
item_option2.name = "Color"
item_option2.value = "Orange"

item.options = [item_option1, item_option2]

order.items = [item]
# -- Items End ---

order.least_cost_route = true # Give me the lowest cost shipping
order.least_cost_route_shipping_methods = ["FedEx: Ground", "UPS: Ground", "USPS: Priority"]
order.mailing_list_opt_in = true # Yes, I confirmed with the customer personally they wish to be on my mailing lists.
order.no_realtime_payment_processing = false
order.payment_method = "Credit Card"
order.rotating_transaction_gateway_code = "MyStripe" # We wish this to be charged against our Stripe gateway
order.screen_branding_theme_code = "SF1986" # Theme codes predated StoreFronts. Each StoreFront still has a theme code under the hood
order.ship_on_date = Time.now.strftime('%Y-%m-%dT00:00:00+00:00')
order.ship_to_residential = true
order.shipto_address1 = "55 Main Street"
order.shipto_address2 = "Suite 202"
order.shipto_city = "Duluth"
order.shipto_company = "Widgets Inc"
order.shipto_country_code = "US"
order.shipto_day_phone = "6785552323"
order.shipto_evening_phone = "7703334444"
order.shipto_first_name = "Sally"
order.shipto_last_name = "McGonkyDee"
order.shipto_postal_code = "30097"
order.shipto_state_region = "GA"
order.shipto_title = "Director"
order.skip_payment_processing = false
order.special_instructions = "Please wrap this in bubble wrap because my FedEx delivery guy is abusive to packages"
order.store_completed = false # this will bypass everything, including shipping. useful only for importing old orders long completed
order.storefront_host_name = 'store.mysite.com'
order.store_if_payment_declines = false # if payment fails, this can send it to Accounts Receivable. Do not want that. Fail if payment fails.
order.tax_county = "Gwinnett"
order.tax_exempt = false

order_transaction = UltracartClient::ChannelPartnerOrderTransaction.new
order_transaction.successful = false # we haven't charged the card yet, so this is false
order_transaction.details = [] # we haven't charged the card yet, so this is empty
order.transaction = order_transaction
order.treat_warnings_as_errors = true

api_response = channel_partner_api.import_channel_partner_order(order)

# ---------------------------------------------
# ---------------------------------------------
# Example 2 - Order already processed
# ---------------------------------------------
# ---------------------------------------------

order = UltracartClient::ChannelPartnerOrder.new

order.associate_with_customer_profile_if_present = true
order.auto_approve_purchase_order = true
order.billto_address1 = "11460 Johns Creek Parkway"
order.billto_address2 = "Suite 101"
order.billto_city = "Duluth"
order.billto_company = "Widgets Inc"
order.billto_country_code = "US"
order.billto_day_phone = "6784153823"
order.billto_evening_phone = "6784154019"
order.billto_first_name = "John"
order.billto_last_name = "Smith"
order.billto_postal_code = "30097"
order.billto_state_region = "GA"
order.billto_title = "Sir"
order.cc_email = "orders@widgets.com"
order.channel_partner_order_id = "widget-1245-abc"
order.consider_recurring = false
order.coupons = ["10OFF", "BUY1GET1"]

order.credit_card_expiration_month = 5
order.credit_card_expiration_year = 2032
order.credit_card_type = "VISA"
order.custom_field1 = "Whatever"
order.custom_field2 = "You"
order.custom_field3 = "Want"
order.custom_field4 = "Can"
order.custom_field5 = "Go"
order.custom_field6 = "In"
order.custom_field7 = "CustomFields"
order.delivery_date = Time.now.strftime('%Y-%m-%dT00:00:00+00:00')
order.email = "ceo@widgets.com"
order.gift = false

order.gift_email = "sally@aol.com"
order.gift_message = "Congratulations on your promotion!"

order.ip_address = "34.125.95.217"

# -- Items start ---
item = UltracartClient::ChannelPartnerOrderItem.new

item.merchant_item_id = "shirt"
item.quantity = 1
item.upsell = false

item_option1 = UltracartClient::ChannelPartnerOrderItemOption.new
item_option1.name = "Size"
item_option1.value = "Small"

item_option2 = UltracartClient::ChannelPartnerOrderItemOption.new
item_option2.name = "Color"
item_option2.value = "Orange"

item.options = [item_option1, item_option2]

order.items = [item]
# -- Items End ---

order.mailing_list_opt_in = true # Yes, I confirmed with the customer personally they wish to be on my mailing lists.
order.no_realtime_payment_processing = true # nothing to charge, payment was already collected
order.payment_method = "Credit Card"
order.rotating_transaction_gateway_code = "MyStripe" # We wish this to be charged against our Stripe gateway
order.screen_branding_theme_code = "SF1986" # Theme codes predated StoreFronts. Each StoreFront still has a theme code under the hood
order.ship_on_date = Time.now.strftime('%Y-%m-%dT00:00:00+00:00')
order.ship_to_residential = true
order.shipping_method = "FedEx: Ground"
order.shipto_address1 = "55 Main Street"
order.shipto_address2 = "Suite 202"
order.shipto_city = "Duluth"
order.shipto_company = "Widgets Inc"
order.shipto_country_code = "US"
order.shipto_day_phone = "6785552323"
order.shipto_evening_phone = "7703334444"
order.shipto_first_name = "Sally"
order.shipto_last_name = "McGonkyDee"
order.shipto_postal_code = "30097"
order.shipto_state_region = "GA"
order.shipto_title = "Director"
order.skip_payment_processing = true # bypass payment
order.special_instructions = "Please wrap this in bubble wrap because my FedEx delivery guy is abusive to packages"
order.store_completed = true # this is an old order or an order handled completely outside UltraCart, so do not do anything to it. Just store it.
order.storefront_host_name = 'store.mysite.com'
order.store_if_payment_declines = false # if payment fails, this can send it to Accounts Receivable. Do not want that. Fail if payment fails.
order.tax_county = "Gwinnett"
order.tax_exempt = false

order_transaction = UltracartClient::ChannelPartnerOrderTransaction.new
order_transaction.successful = true

td1 = UltracartClient::ChannelPartnerOrderTransactionDetail.new
td1.name = "AVS Code"
td1.value = "X"

td2 = UltracartClient::ChannelPartnerOrderTransactionDetail.new
td2.name = "Authorization Code"
td2.value = "123456"

td3 = UltracartClient::ChannelPartnerOrderTransactionDetail.new
td3.name = "CVV Code"
td3.value = "M"

td4 = UltracartClient::ChannelPartnerOrderTransactionDetail.new
td4.name = "Response Code"
td4.value = "Authorized"

td5 = UltracartClient::ChannelPartnerOrderTransactionDetail.new
td5.name = "Reason Code"
td5.value = "1"

td6 = UltracartClient::ChannelPartnerOrderTransactionDetail.new
td6.name = "Response Subcode"
td6.value = "1"

td7 = UltracartClient::ChannelPartnerOrderTransactionDetail.new
td7.name = "Transaction ID"
td7.value = "1234567890"

order_transaction.details = [td1, td2, td3, td4, td5, td6, td7]
order.transaction = order_transaction
order.treat_warnings_as_errors = true

api_response = channel_partner_api.import_channel_partner_order(order)
import { DateTime } from 'luxon';
import {
    ChannelPartnerApi,
    ChannelPartnerOrder,
    ChannelPartnerOrderItem,
    ChannelPartnerOrderItemOption, ChannelPartnerOrderPaymentMethodEnum,
    ChannelPartnerOrderTransaction,
    ChannelPartnerOrderTransactionDetail
} from 'ultracart_rest_api_v2_typescript';
import { channelPartnerApi } from '../api';

/**
 * Imports channel partner orders into UltraCart
 *
 * To run channel partner examples, you will need:
 * 1) An API Key: https://secure.ultracart.com/merchant/configuration/apiManagementApp.do
 * 2) That API Key must be assigned to a channel partner: https://secure.ultracart.com/merchant/configuration/customChannelPartnerListLoad.do
 *
 * The spreadsheet import docs will serve you well here. They describe many fields
 * https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1377246/Channel+Partner+API+-+Spreadsheet+Import
 */
export async function execute(): Promise<void> {
    console.log(`--- ${execute.name} ---`);

    try {
        // ---------------------------------------------
        // Example 1 - Order needs payment processing
        // ---------------------------------------------
        const order: ChannelPartnerOrder = {
            associate_with_customer_profile_if_present: true,
            auto_approve_purchase_order: true,
            billto_address1: "11460 Johns Creek Parkway",
            billto_address2: "Suite 101",
            billto_city: "Duluth",
            billto_company: "Widgets Inc",
            billto_country_code: "US",
            billto_day_phone: "6784153823",
            billto_evening_phone: "6784154019",
            billto_first_name: "John",
            billto_last_name: "Smith",
            billto_postal_code: "30097",
            billto_state_region: "GA",
            billto_title: "Sir",
            cc_email: "orders@widgets.com",
            channel_partner_order_id: "widget-1245-abc",
            consider_recurring: false,
            coupons: ["10OFF", "BUY1GET1"],
            credit_card_expiration_month: 5,
            credit_card_expiration_year: 2032,
            credit_card_type: "VISA",
            custom_field1: "Whatever",
            custom_field2: "You",
            custom_field3: "Want",
            custom_field4: "Can",
            custom_field5: "Go",
            custom_field6: "In",
            custom_field7: "CustomFields",
            delivery_date: DateTime.now().toISO(),
            email: "ceo@widgets.com",
            gift: false,
            gift_email: "sally@aol.com",
            gift_message: "Congratulations on your promotion!",
            hosted_fields_card_token: "7C97B0AAA26AB10180B4B29F00380101",
            hosted_fields_cvv_token: "C684AB4336787F0180B4B51971380101",
            ip_address: "34.125.95.217",
            least_cost_route: true,
            least_cost_route_shipping_methods: ["FedEx: Ground", "UPS: Ground", "USPS: Priority"],
            mailing_list_opt_in: true,
            no_realtime_payment_processing: false,
            payment_method: ChannelPartnerOrderPaymentMethodEnum.CreditCard,
            rotating_transaction_gateway_code: "MyStripe",
            screen_branding_theme_code: "SF1986",
            ship_on_date: DateTime.now().toISO(),
            ship_to_residential: true,
            shipto_address1: "55 Main Street",
            shipto_address2: "Suite 202",
            shipto_city: "Duluth",
            shipto_company: "Widgets Inc",
            shipto_country_code: "US",
            shipto_day_phone: "6785552323",
            shipto_evening_phone: "7703334444",
            shipto_first_name: "Sally",
            shipto_last_name: "McGonkyDee",
            shipto_postal_code: "30097",
            shipto_state_region: "GA",
            shipto_title: "Director",
            skip_payment_processing: false,
            special_instructions: "Please wrap this in bubble wrap because my FedEx delivery guy is abusive to packages",
            store_completed: false,
            storefront_host_name: "store.mysite.com",
            store_if_payment_declines: false,
            tax_county: "Gwinnett",
            tax_exempt: false,
            treat_warnings_as_errors: true,

            // Items
            items: [{
                merchant_item_id: "shirt",
                quantity: 1,
                upsell: false,
                options: [
                    { name: "Size", value: "Small" },
                    { name: "Color", value: "Orange" }
                ]
            }],

            // Transaction
            transaction: {
                successful: false,
                details: []
            }
        };

        // Import the first order
        const apiResponse = await channelPartnerApi.importChannelPartnerOrder({channelPartnerOrder: order});

        // ---------------------------------------------
        // Example 2 - Order already processed
        // ---------------------------------------------
        const processedOrder: ChannelPartnerOrder = {
            associate_with_customer_profile_if_present: true,
            auto_approve_purchase_order: true,
            billto_address1: "11460 Johns Creek Parkway",
            billto_address2: "Suite 101",
            billto_city: "Duluth",
            billto_company: "Widgets Inc",
            billto_country_code: "US",
            billto_day_phone: "6784153823",
            billto_evening_phone: "6784154019",
            billto_first_name: "John",
            billto_last_name: "Smith",
            billto_postal_code: "30097",
            billto_state_region: "GA",
            billto_title: "Sir",
            cc_email: "orders@widgets.com",
            channel_partner_order_id: "widget-1245-abc",
            consider_recurring: false,
            coupons: ["10OFF", "BUY1GET1"],
            credit_card_expiration_month: 5,
            credit_card_expiration_year: 2032,
            credit_card_type: "VISA",
            custom_field1: "Whatever",
            custom_field2: "You",
            custom_field3: "Want",
            custom_field4: "Can",
            custom_field5: "Go",
            custom_field6: "In",
            custom_field7: "CustomFields",
            delivery_date: DateTime.now().toISO(),
            email: "ceo@widgets.com",
            gift: false,
            gift_email: "sally@aol.com",
            gift_message: "Congratulations on your promotion!",
            ip_address: "34.125.95.217",
            mailing_list_opt_in: true,
            no_realtime_payment_processing: true,
            payment_method: ChannelPartnerOrderPaymentMethodEnum.CreditCard,
            rotating_transaction_gateway_code: "MyStripe",
            screen_branding_theme_code: "SF1986",
            ship_on_date: DateTime.now().toISO(),
            ship_to_residential: true,
            shipping_method: "FedEx: Ground",
            shipto_address1: "55 Main Street",
            shipto_address2: "Suite 202",
            shipto_city: "Duluth",
            shipto_company: "Widgets Inc",
            shipto_country_code: "US",
            shipto_day_phone: "6785552323",
            shipto_evening_phone: "7703334444",
            shipto_first_name: "Sally",
            shipto_last_name: "McGonkyDee",
            shipto_postal_code: "30097",
            shipto_state_region: "GA",
            shipto_title: "Director",
            skip_payment_processing: true,
            special_instructions: "Please wrap this in bubble wrap because my FedEx delivery guy is abusive to packages",
            store_completed: true,
            storefront_host_name: "store.mysite.com",
            store_if_payment_declines: false,
            tax_county: "Gwinnett",
            tax_exempt: false,
            treat_warnings_as_errors: true,

            // Items
            items: [{
                merchant_item_id: "shirt",
                quantity: 1,
                upsell: false,
                options: [
                    { name: "Size", value: "Small" },
                    { name: "Color", value: "Orange" }
                ]
            }],

            // Transaction
            transaction: {
                successful: true,
                details: [
                    { name: "AVS Code", value: "X" },
                    { name: "Authorization Code", value: "123456" },
                    { name: "CVV Code", value: "M" },
                    { name: "Response Code", value: "Authorized" },
                    { name: "Reason Code", value: "1" },
                    { name: "Response Subcode", value: "1" },
                    { name: "Transaction ID", value: "1234567890" }
                ]
            }
        };

        // Import the processed order
        const processedApiResponse = await channelPartnerApi.importChannelPartnerOrder({channelPartnerOrder: processedOrder});

        console.log("Orders imported successfully");
    }
    catch (ex: unknown) {
        const error = ex as Error;
        console.error(`Error: ${error.message}`);
        console.error(error.stack);
    }
}

// Optional: If you want to run this directly
if (require.main === module) {
    execute().catch(console.error);
}

Retrieve a channel partner order by the channel partner order id

Permissions:
  • channel_partner_read

Produces: application/json
get
/channel_partner/orders/by_channel_partner_order_id/{order_id}

Retrieves a single order using the channel partner order id, not the ultracart order id. Only orders belonging to this channel partner may be retrieved.

SDK Function Name: getChannelPartnerOrderByChannelPartnerOrderId

Parameters
Parameter Description Location Data Type Required
order_id The channel partner order id to retrieve. path string required
_expand The object expansion to perform on the result. See OrderApi.getOrder 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.Reflection;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;

namespace SdkSample.channel_partner
{
    public class GetChannelPartnerOrderByChannelPartnerOrderId
    {
        /*
         * ChannelPartnerApi.getChannelPartnerOrderByChannelPartnerOrderId() retrieves a single order for a given
         * channel partner order_id.  This might be useful for call centers which only have their order ids and not UltraCart's.
         * It is identical to the OrderApi.getOrder() call in functionality and result,
         * but allows for a restricted permission set.  The channel partner api assumes a tie to a Channel Partner and
         * only allows retrieval of orders created by that Channel Partner.
         */
        public static void Execute()
        {
            Console.WriteLine("--- " + MethodBase.GetCurrentMethod()?.DeclaringType?.Name + " ---");
            
            try
            {
                // Create channel partner API instance using API key
                ChannelPartnerApi channelPartnerApi = new ChannelPartnerApi(Constants.ChannelPartnerApiKey);
                
                // 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
                */
                
                // A channel partner will almost always query an order for the purpose of turning around and submitting it to a refund call.
                // As such, the expansion most likely needed is listed below.
                string expansion = "item,summary,shipping";
                
                // This order MUST be an order associated with this channel partner or you will receive a 400 Bad Request.
                string channelPartnerOrderId = "MY-CALL-CENTER-BLAH-BLAH";
                var apiResponse = channelPartnerApi.GetChannelPartnerOrderByChannelPartnerOrderId(channelPartnerOrderId, 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(order);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
                Console.WriteLine(ex.StackTrace);
            }
        }
    }
}
package channel_partner;

import com.ultracart.admin.v2.ChannelPartnerApi;
import com.ultracart.admin.v2.models.Order;
import com.ultracart.admin.v2.models.OrderResponse;

public class GetChannelPartnerOrderByChannelPartnerOrderId {
    /*
     * ChannelPartnerApi.getChannelPartnerOrderByChannelPartnerOrderId() retrieves a single order for a given
     * channel partner order_id.  This might be useful for call centers which only have their order ids and not UltraCart's.
     * It is identical to the OrderApi.getOrder() call in functionality and result,
     * but allows for a restricted permission set.  The channel partner api assumes a tie to a Channel Partner and
     * only allows retrieval of orders created by that Channel Partner.
     */
    public static void execute() {
        System.out.println("--- GetChannelPartnerOrderByChannelPartnerOrderId ---");

        try {
            // Create channel partner API instance using API key
            ChannelPartnerApi channelPartnerApi = new ChannelPartnerApi(common.Constants.CHANNEL_PARTNER_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
            */

            // A channel partner will almost always query an order for the purpose of turning around and submitting it to a refund call.
            // As such, the expansion most likely needed is listed below.
            String expansion = "item,summary,shipping";

            // This order MUST be an order associated with this channel partner or you will receive a 400 Bad Request.
            String channelPartnerOrderId = "MY-CALL-CENTER-BLAH-BLAH";
            OrderResponse apiResponse = channelPartnerApi.getChannelPartnerOrderByChannelPartnerOrderId(channelPartnerOrderId, expansion);

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

            Order order = apiResponse.getOrder();
            System.out.println(order);
        }
        catch (Exception ex) {
            System.out.println("Error: " + ex.getMessage());
            ex.printStackTrace();
        }
    }
}
import { channelPartnerApi } from '../api.js';

/**
 * ChannelPartnerApi.getChannelPartnerOrderByChannelPartnerOrderId() retrieves a single order for a given
 * channel partner order_id.  This might be useful for call centers which only have their order ids and not UltraCart's.
 * It is identical to the OrderApi.getOrder() call in functionality and result,
 * but allows for a restricted permission set.  The channel partner api assumes a tie to a Channel Partner and
 * only allows retrieval of orders created by that Channel Partner.
 *
 * 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
 */
export class GetChannelPartnerOrderByChannelPartnerOrderId {
    /**
     * Execute method to retrieve a channel partner order by its channel partner order ID
     */
    static async execute() {
        console.log(`--- ${this.name} ---`);

        try {
            // 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.
            // A channel partner will almost always query an order for the purpose of turning
            // around and submitting it to a refund call.
            const expand = "item,summary,shipping";

            // This order MUST be an order associated with this channel partner or you will receive a 400 Bad Request.
            const channelPartnerOrderId = "MY-CALL-CENTER-BLAH-BLAH";

            // Retrieve the channel partner order
            const apiResponse = await new Promise((resolve, reject) => {
                channelPartnerApi.getChannelPartnerOrderByChannelPartnerOrderId(
                    channelPartnerOrderId, {_expand: expand },
                    function (error, data, response) {
                        if (error) {
                            reject(error);
                        } else {
                            resolve(data);
                        }
                    }
                );
            });

            // Check for any errors in the API response
            if (apiResponse.error) {
                console.error(apiResponse.error.developer_message);
                console.error(apiResponse.error.user_message);
                process.exit(1);
            }

            // Extract and log the order
            const order = apiResponse.order;
            console.log(order);

        } catch (ex) {
            // Log details of the error
            if (ex instanceof Error) {
                console.error(`Error: ${ex.message}`);
                console.error(ex.stack);
            } else {
                console.error("An unknown error occurred");
            }
        }
    }
}

<?php

ini_set('display_errors', 1);

/*
 * ChannelPartnerApi.getChannelPartnerOrderByChannelPartnerOrderId() retrieves a single order for a given
 * channel partner order_id.  This might be useful for call centers which only have their order ids and not UltraCart's.
 * It is identical to the OrderApi.getOrder() call in functionality and result,
 * but allows for a restricted permission set.  The channel partner api assumes a tie to a Channel Partner and
 * only allows retrieval of orders created by that Channel Partner.
 */


use ultracart\v2\api\ChannelPartnerApi;

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


$channel_partner_api = ChannelPartnerApi::usingApiKey(Constants::CHANNEL_PARTNER_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
*/

// A channel partner will almost always query an order for the purpose of turning around and submitting it to a refund call.
// As such, the expansion most likely needed is listed below.
$expansion = "item,summary,shipping";


// This order MUST be an order associated with this channel partner or you will receive a 400 Bad Request.
$channel_partner_order_id = 'MY-CALL-CENTER-BLAH-BLAH';
$api_response = $channel_partner_api->getChannelPartnerOrderByChannelPartnerOrderId($channel_partner_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 ChannelPartnerApi
from samples import channel_partner_api_client

channel_partner_api = ChannelPartnerApi(channel_partner_api_client())

# 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
"""

# A channel partner will almost always query an order for the purpose of turning around and submitting it to a refund call.
# As such, the expansion most likely needed is listed below.
expand = "item,summary,shipping"

# This order MUST be an order associated with this channel partner or you will receive a 400 Bad Request.
channel_partner_order_id = 'MY-CALL-CENTER-BLAH-BLAH'
api_response = channel_partner_api.get_channel_partner_order_by_channel_partner_order_id(channel_partner_order_id, expand=expand)

if api_response.error is not None:
    print(api_response.error.developer_message)
    print(api_response.error.user_message)
    exit()

order = api_response.order

print(order)
require 'ultracart_api'
require_relative '../constants'

# ChannelPartnerApi.get_channel_partner_order_by_channel_partner_order_id() retrieves a single order for a given
# channel partner order_id.  This might be useful for call centers which only have their order ids and not UltraCart's.
# It is identical to the OrderApi.get_order() call in functionality and result,
# but allows for a restricted permission set.  The channel partner api assumes a tie to a Channel Partner and
# only allows retrieval of orders created by that Channel Partner.

channel_partner_api = UltracartClient::ChannelPartnerApi.new_using_api_key(Constants::CHANNEL_PARTNER_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

# A channel partner will almost always query an order for the purpose of turning around and submitting it to a refund call.
# As such, the expansion most likely needed is listed below.
_expand = "item,summary,shipping"

# This order MUST be an order associated with this channel partner or you will receive a 400 Bad Request.
channel_partner_order_id = 'MY-CALL-CENTER-BLAH-BLAH'
api_response = channel_partner_api.get_channel_partner_order_by_channel_partner_order_id(channel_partner_order_id, { '_expand' => _expand })

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

order = api_response.order

p order
import {
    Order, OrderResponse
} from 'ultracart_rest_api_v2_typescript';
import { channelPartnerApi } from '../api';

/**
 * ChannelPartnerApi.getChannelPartnerOrderByChannelPartnerOrderId() retrieves a single order for a given
 * channel partner order_id.  This might be useful for call centers which only have their order ids and not UltraCart's.
 * It is identical to the OrderApi.getOrder() call in functionality and result,
 * but allows for a restricted permission set.  The channel partner api assumes a tie to a Channel Partner and
 * only allows retrieval of orders created by that Channel Partner.
 *
 * 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
 */
export class GetChannelPartnerOrderByChannelPartnerOrderId {
    /**
     * Execute method to retrieve a channel partner order by its channel partner order ID
     */
    public static async execute(): Promise<void> {
        console.log(`--- ${this.name} ---`);

        try {
            // 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.
            // A channel partner will almost always query an order for the purpose of turning
            // around and submitting it to a refund call.
            const expand: string = "item,summary,shipping";

            // This order MUST be an order associated with this channel partner or you will receive a 400 Bad Request.
            const channelPartnerOrderId: string = "MY-CALL-CENTER-BLAH-BLAH";

            // Retrieve the channel partner order
            const apiResponse: OrderResponse = await channelPartnerApi.getChannelPartnerOrderByChannelPartnerOrderId({orderId: channelPartnerOrderId, expand});

            // Check for any errors in the API response
            if (apiResponse.error) {
                console.error(apiResponse.error.developer_message);
                console.error(apiResponse.error.user_message);
                process.exit(1);
            }

            // Extract and log the order
            const order: Order | undefined = apiResponse.order;
            console.log(order);
        } catch (ex: unknown) {
            // Type the error as unknown and log details
            if (ex instanceof Error) {
                console.error(`Error: ${ex.message}`);
                console.error(ex.stack);
            } else {
                console.error("An unknown error occurred");
            }
        }
    }
}

Retrieve a channel partner order

Permissions:
  • channel_partner_read

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

Retrieves a single order using the specified order id. Only orders belonging to this channel partner may be retrieved.

SDK Function Name: getChannelPartnerOrder

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 OrderApi.getOrder 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.Reflection;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;

namespace SdkSample.channel_partner
{
    public class GetChannelPartnerOrder
    {
        /*
         * ChannelPartnerApi.getChannelPartnerOrder() retrieves a single order for a given order_id.  It is identical to the
         * OrderApi.getOrder() call, but allows for a restricted permission set.  The channel partner api assumes
         * a tie to a Channel Partner and only allows retrieval of orders created by that Channel Partner.
         */
        public static void Execute()
        {
            Console.WriteLine("--- " + MethodBase.GetCurrentMethod()?.DeclaringType?.Name + " ---");
            
            try
            {
                // Create channel partner API instance using API key
                ChannelPartnerApi channelPartnerApi = new ChannelPartnerApi(Constants.ChannelPartnerApiKey);
                
                // 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
                */
                
                // A channel partner will almost always query an order for the purpose of turning around and submitting it to a refund call.
                // As such, the expansion most likely needed is listed below.
                string expansion = "item,summary,shipping";
                
                // This order MUST be an order associated with this channel partner or you will receive a 400 Bad Request.
                string orderId = "DEMO-0009110366";
                var apiResponse = channelPartnerApi.GetChannelPartnerOrder(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(order);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
                Console.WriteLine(ex.StackTrace);
            }
        }
    }
}
package channel_partner;

import com.ultracart.admin.v2.ChannelPartnerApi;
import com.ultracart.admin.v2.models.Order;
import com.ultracart.admin.v2.models.OrderResponse;

public class GetChannelPartnerOrder {
    /*
     * ChannelPartnerApi.getChannelPartnerOrder() retrieves a single order for a given order_id.  It is identical to the
     * OrderApi.getOrder() call, but allows for a restricted permission set.  The channel partner api assumes
     * a tie to a Channel Partner and only allows retrieval of orders created by that Channel Partner.
     */
    public static void execute() {
        System.out.println("--- GetChannelPartnerOrder ---");

        try {
            // Create channel partner API instance using API key
            ChannelPartnerApi channelPartnerApi = new ChannelPartnerApi(common.Constants.CHANNEL_PARTNER_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
            */

            // A channel partner will almost always query an order for the purpose of turning around and submitting it to a refund call.
            // As such, the expansion most likely needed is listed below.
            String expansion = "item,summary,shipping";

            // This order MUST be an order associated with this channel partner or you will receive a 400 Bad Request.
            String orderId = "DEMO-0009110366";
            OrderResponse apiResponse = channelPartnerApi.getChannelPartnerOrder(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();
            System.out.println(order);
        }
        catch (Exception ex) {
            System.out.println("Error: " + ex.getMessage());
            ex.printStackTrace();
        }
    }
}
import {channelPartnerApi} from '../api.js';

/**
 * ChannelPartnerApi.getChannelPartnerOrder() retrieves a single order for a given order_id.  It is identical to the
 * OrderApi.getOrder() call, but allows for a restricted permission set.  The channel partner api assumes
 * a tie to a Channel Partner and only allows retrieval of orders created by that Channel Partner.
 *
 * 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
 */
export class GetChannelPartnerOrder {
    /**
     * Execute method to retrieve a channel partner order
     */
    static async execute() {
        console.log(`--- ${this.name} ---`);

        try {
            // 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.
            // A channel partner will almost always query an order for the purpose of turning
            // around and submitting it to a refund call.
            const expand = "item,summary,shipping";

            // This order MUST be an order associated with this channel partner or you will receive a 400 Bad Request.
            const orderId = "DEMO-0009110366";

            // Retrieve the channel partner order
            const apiResponse = await new Promise((resolve, reject) => {
                channelPartnerApi.getChannelPartnerOrder(
                    orderId, {_expand: expand},
                    function (error, data, response) {
                        if (error) {
                            reject(error);
                        } else {
                            resolve(data);
                        }
                    }
                );
            });

            // Check for any errors in the API response
            if (apiResponse.error) {
                console.error(apiResponse.error.developer_message);
                console.error(apiResponse.error.user_message);
                process.exit(1);
            }

            // Extract and log the order
            const order = apiResponse.order;
            console.log(order);

        } catch (ex) {
            // Log details of the error
            if (ex instanceof Error) {
                console.error(`Error: ${ex.message}`);
                console.error(ex.stack);
            } else {
                console.error("An unknown error occurred");
            }
        }
    }
}

<?php

ini_set('display_errors', 1);

/*
 * ChannelPartnerApi.getChannelPartnerOrder() retrieves a single order for a given order_id.  It is identical to the
 * OrderApi.getOrder() call, but allows for a restricted permission set.  The channel partner api assumes
 * a tie to a Channel Partner and only allows retrieval of orders created by that Channel Partner.
 */


use ultracart\v2\api\ChannelPartnerApi;

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


$channel_partner_api = ChannelPartnerApi::usingApiKey(Constants::CHANNEL_PARTNER_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
*/

// A channel partner will almost always query an order for the purpose of turning around and submitting it to a refund call.
// As such, the expansion most likely needed is listed below.
$expansion = "item,summary,shipping";


// This order MUST be an order associated with this channel partner or you will receive a 400 Bad Request.
$order_id = 'DEMO-0009110366';
$api_response = $channel_partner_api->getChannelPartnerOrder($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 ChannelPartnerApi
from samples import channel_partner_api_client

channel_partner_api = ChannelPartnerApi(channel_partner_api_client())

# 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
"""

# A channel partner will almost always query an order for the purpose of turning around and submitting it to a refund call.
# As such, the expansion most likely needed is listed below.
expand = "item,summary,shipping"

# This order MUST be an order associated with this channel partner or you will receive a 400 Bad Request.
order_id = 'DEMO-0009110366'
api_response = channel_partner_api.get_channel_partner_order(order_id, expand=expand)

if api_response.error is not None:
    print(api_response.error.developer_message)
    print(api_response.error.user_message)
    exit()

order = api_response.order

print(order)
require 'ultracart_api'
require_relative '../constants'

# ChannelPartnerApi.get_channel_partner_order() retrieves a single order for a given order_id.  It is identical to the
# OrderApi.get_order() call, but allows for a restricted permission set.  The channel partner api assumes
# a tie to a Channel Partner and only allows retrieval of orders created by that Channel Partner.

channel_partner_api = UltracartClient::ChannelPartnerApi.new_using_api_key(Constants::CHANNEL_PARTNER_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

# A channel partner will almost always query an order for the purpose of turning around and submitting it to a refund call.
# As such, the expansion most likely needed is listed below.
_expand = "item,summary,shipping"

# This order MUST be an order associated with this channel partner or you will receive a 400 Bad Request.
order_id = 'DEMO-0009110366'
api_response = channel_partner_api.get_channel_partner_order(order_id, { '_expand' => _expand })

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

order = api_response.order

p order
import {
    Order, OrderResponse
} from 'ultracart_rest_api_v2_typescript';
import {channelPartnerApi} from '../api';

/**
 * ChannelPartnerApi.getChannelPartnerOrder() retrieves a single order for a given order_id.  It is identical to the
 * OrderApi.getOrder() call, but allows for a restricted permission set.  The channel partner api assumes
 * a tie to a Channel Partner and only allows retrieval of orders created by that Channel Partner.
 *
 * 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
 */
export class GetChannelPartnerOrder {
    /**
     * Execute method to retrieve a channel partner order
     */
    public static async execute(): Promise<void> {
        console.log(`--- ${this.name} ---`);

        try {
            // 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.
            // A channel partner will almost always query an order for the purpose of turning
            // around and submitting it to a refund call.
            const expand: string = "item,summary,shipping";

            // This order MUST be an order associated with this channel partner or you will receive a 400 Bad Request.
            const orderId: string = "DEMO-0009110366";

            // Retrieve the channel partner order
            const apiResponse: OrderResponse = await channelPartnerApi.getChannelPartnerOrder({orderId, expand});

            // Check for any errors in the API response
            if (apiResponse.error) {
                console.error(apiResponse.error.developer_message);
                console.error(apiResponse.error.user_message);
                process.exit(1);
            }

            // Extract and log the order
            const order: Order | undefined = apiResponse.order;
            console.log(order);
        } catch (ex: unknown) {
            // Type the error as unknown and log details
            if (ex instanceof Error) {
                console.error(`Error: ${ex.message}`);
                console.error(ex.stack);
            } else {
                console.error("An unknown error occurred");
            }
        }
    }
}

Refund a channel partner order

Permissions:
  • channel_partner_write

Consumes: application/json
Produces: application/json
put
/channel_partner/orders/{order_id}/refund

Perform a refund operation on a channel partner 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: refundChannelPartnerOrder

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 OrderApi.refundOrder 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;
using Newtonsoft.Json;

namespace SdkSample.channel_partner
{
    public class RefundChannelPartnerOrder
    {
        /// <summary>
        /// IMPORTANT: Do NOT construct the refunded order. This method does a refund but also update the entire object, so start with an order query.
        /// ALWAYS start with an order retrieved from the system.
        /// 1. Call getChannelPartnerOrder or getChannelPartnerOrderByChannelPartnerOrderId to retrieve the order being refunded
        /// 2. For a full refund, reverse the following:
        ///    A. Set the refunded qty and refunded amount for each item.
        ///    B. Set the refunded tax (if any)
        ///    C. Set the refunded shipping
        /// NOTE: refund amounts are positive numbers. If any item total cost is $20.00, a full refunded amount would also be positive $20.00
        /// See the ChannelPartnerApi.getChannelPartnerOrder() sample for details on that method.
        /// </summary>
        public static void Execute()
        {
            // Create channel partner API instance
            ChannelPartnerApi channelPartnerApi = new ChannelPartnerApi(Constants.ChannelPartnerApiKey);
            
            // For a comment on this expansion, see getChannelPartnerOrder sample.
            string expansion = "item,summary,shipping";
            
            // This order MUST be an order associated with this channel partner, or you will receive a 400 Bad Request.
            string orderId = "DEMO-0009106820";
            OrderResponse apiResponse = channelPartnerApi.GetChannelPartnerOrder(orderId, expansion);

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

            Order order = apiResponse.Order;

            // RefundReason may be required, but is optional by default.
            // RefundReason may be a set list, or may be freeform. This is configured on the backend (secure.ultracart.com)
            // by Navigating to Home -> Configuration -> Order Management -> Refund/Reject Reasons
            // Warning: If this is a 2nd refund after an initial partial refund, be sure you account for the units and amount already refunded.
            order.RefundReason = "Damage Product";
            order.Summary.TaxRefunded = order.Summary.Tax;
            order.Summary.ShippingHandlingRefunded = order.Summary.ShippingHandlingTotal;
            
            foreach (OrderItem item in order.Items)
            {
                // Item level refund reasons are optional, but may be required. See the above breadcrumb trail for refund reason config.
                item.RefundReason = "DifferentItem";
                item.QuantityRefunded = item.Quantity;
                item.TotalRefunded = item.TotalCostWithDiscount;
            }

            bool rejectAfterRefund = false;
            bool skipCustomerNotifications = true;
            bool autoOrderCancel = false; // If this was an auto order, and they wanted to cancel it, set this flag to true.
            // Set manualRefund to true if the actual refund happened outside the system, and you just want a record of it.
            // If UltraCart did not process this refund, manualRefund should be true.
            bool manualRefund = false;
            bool reverseAffiliateTransactions = true; // For a full refund, the affiliate should not get credit, or should they?
            bool issueStoreCredit = false; // If true, the customer would receive store credit instead of a return on their credit card.
            string autoOrderCancelReason = null;

            apiResponse = channelPartnerApi.RefundChannelPartnerOrder(
                orderId, 
                order, 
                rejectAfterRefund,
                skipCustomerNotifications, 
                autoOrderCancel, 
                manualRefund, 
                reverseAffiliateTransactions,
                issueStoreCredit, 
                autoOrderCancelReason, 
                expansion);

            Error error = apiResponse.Error;
            Order updatedOrder = apiResponse.Order;
            // Verify the updated order contains all the desired refunds. Verify that refunded total is equal to total.

            // Note: The error 'Request to refund an invalid amount.' means you requested a total refund amount less than or equal to zero.
            Console.WriteLine("Error:");
            Console.WriteLine(error != null ? JsonConvert.SerializeObject(error, Formatting.Indented) : "null");
            Console.WriteLine("\n\n--------------------\n\n");
            Console.WriteLine("Updated Order:");
            Console.WriteLine(updatedOrder != null ? JsonConvert.SerializeObject(updatedOrder, Formatting.Indented) : "null");
        }
    }
}
package channel_partner;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ultracart.admin.v2.ChannelPartnerApi;
import com.ultracart.admin.v2.models.Error;
import com.ultracart.admin.v2.models.Order;
import com.ultracart.admin.v2.models.OrderItem;
import com.ultracart.admin.v2.models.OrderResponse;

import java.util.List;

public class RefundChannelPartnerOrder {
    /**
     * IMPORTANT: Do NOT construct the refunded order. This method does a refund but also update the entire object, so start with an order query.
     * ALWAYS start with an order retrieved from the system.
     * 1. Call getChannelPartnerOrder or getChannelPartnerOrderByChannelPartnerOrderId to retrieve the order being refunded
     * 2. For a full refund, reverse the following:
     *    A. Set the refunded qty and refunded amount for each item.
     *    B. Set the refunded tax (if any)
     *    C. Set the refunded shipping
     * NOTE: refund amounts are positive numbers. If any item total cost is $20.00, a full refunded amount would also be positive $20.00
     * See the ChannelPartnerApi.getChannelPartnerOrder() sample for details on that method.
     */
    public static void execute() {
        try {
            // Create channel partner API instance
            ChannelPartnerApi channelPartnerApi = new ChannelPartnerApi(common.Constants.CHANNEL_PARTNER_API_KEY);

            // For a comment on this expansion, see getChannelPartnerOrder sample.
            String expansion = "item,summary,shipping";

            // This order MUST be an order associated with this channel partner, or you will receive a 400 Bad Request.
            String orderId = "DEMO-0009106820";
            OrderResponse apiResponse = channelPartnerApi.getChannelPartnerOrder(orderId, expansion);

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

            Order order = apiResponse.getOrder();

            // RefundReason may be required, but is optional by default.
            // RefundReason may be a set list, or may be freeform. This is configured on the backend (secure.ultracart.com)
            // by Navigating to Home -> Configuration -> Order Management -> Refund/Reject Reasons
            // Warning: If this is a 2nd refund after an initial partial refund, be sure you account for the units and amount already refunded.
            order.setRefundReason("Damage Product");
            order.getSummary().setTaxRefunded(order.getSummary().getTax());
            order.getSummary().setShippingHandlingRefunded(order.getSummary().getShippingHandlingTotal());

            List<OrderItem> items = order.getItems();
            for (OrderItem item : items) {
                // Item level refund reasons are optional, but may be required. See the above breadcrumb trail for refund reason config.
                item.setRefundReason("DifferentItem");
                item.setQuantityRefunded(item.getQuantity());
                item.setTotalRefunded(item.getTotalCostWithDiscount());
            }

            boolean rejectAfterRefund = false;
            boolean skipCustomerNotifications = true;
            boolean autoOrderCancel = false; // If this was an auto order, and they wanted to cancel it, set this flag to true.
            // Set manualRefund to true if the actual refund happened outside the system, and you just want a record of it.
            // If UltraCart did not process this refund, manualRefund should be true.
            boolean manualRefund = false;
            boolean reverseAffiliateTransactions = true; // For a full refund, the affiliate should not get credit, or should they?
            boolean issueStoreCredit = false; // If true, the customer would receive store credit instead of a return on their credit card.
            String autoOrderCancelReason = null;

            apiResponse = channelPartnerApi.refundChannelPartnerOrder(
                orderId,
                order,
                rejectAfterRefund,
                skipCustomerNotifications,
                autoOrderCancel,
                manualRefund,
                reverseAffiliateTransactions,
                issueStoreCredit,
                autoOrderCancelReason,
                expansion);

            Error error = apiResponse.getError();
            Order updatedOrder = apiResponse.getOrder();
            // Verify the updated order contains all the desired refunds. Verify that refunded total is equal to total.

            // Note: The error 'Request to refund an invalid amount.' means you requested a total refund amount less than or equal to zero.
            ObjectMapper mapper = new ObjectMapper();
            System.out.println("Error:");
            System.out.println(error != null ? mapper.writerWithDefaultPrettyPrinter().writeValueAsString(error) : "null");
            System.out.println("\n\n--------------------\n\n");
            System.out.println("Updated Order:");
            System.out.println(updatedOrder != null ? mapper.writerWithDefaultPrettyPrinter().writeValueAsString(updatedOrder) : "null");
        }
        catch (Exception ex) {
            System.out.println("Error: " + ex.getMessage());
            ex.printStackTrace();
        }
    }
}
import { channelPartnerApi } from '../api.js';

/**
 * IMPORTANT: Do NOT construct the refunded order. This method does a refund but also updates the entire object, so start with an order query.
 * ALWAYS start with an order retrieved from the system.
 * 1. Call getChannelPartnerOrder or getChannelPartnerOrderByChannelPartnerOrderId to retrieve the order being refunded
 * 2. For a full refund, reverse the following:
 *    A. Set the refunded qty and refunded amount for each item.
 *    B. Set the refunded tax (if any)
 *    C. Set the refunded shipping
 * NOTE: refund amounts are positive numbers. If any item total cost is $20.00, a full refunded amount would also be positive $20.00
 * See the ChannelPartnerApi.getChannelPartnerOrder() sample for details on that method.
 */
export async function execute() {
    try {
        // For a comment on this expand, see getChannelPartnerOrder sample.
        const expand = "item,summary,shipping";

        // This order MUST be an order associated with this channel partner, or you will receive a 400 Bad Request.
        const orderId = "DEMO-0009106820";

        // Retrieve the order
        const apiResponse = await new Promise((resolve, reject) => {
            channelPartnerApi.getChannelPartnerOrder(
                { orderId, expand },
                function (error, data) {
                    if (error) {
                        reject(error);
                    } else {
                        resolve(data);
                    }
                }
            );
        });

        // Check for errors
        if (apiResponse.error) {
            const error = apiResponse.error;
            console.error(error);
            console.error(error.user_message);
            process.exit(1);
        }

        // Ensure order exists
        if (!apiResponse.order) {
            console.error("No order found");
            process.exit(1);
        }

        // Create a copy of the order to modify
        const order = { ...apiResponse.order };

        // RefundReason may be required, but is optional by default.
        order.refund_reason = "Damage Product";

        // Ensure summary exists before modifying
        if (order.summary) {
            order.summary.tax_refunded = order.summary.tax;
            order.summary.shipping_handling_refunded = order.summary.shipping_handling_total;
        }

        // Modify items for refund
        if (order.items) {
            order.items.forEach(item => {
                item.refund_reason = "DifferentItem";
                item.quantity_refunded = item.quantity;
                item.total_refunded = item.total_cost_with_discount;
            });
        }

        // Refund parameters
        const rejectAfterRefund = false;
        const skipCustomerNotification = true;
        const autoOrderCancel = false;
        const manualRefund = false;
        const reverseAffiliateTransactions = true;
        const issueStoreCredit = false;
        const autoOrderCancelReason = undefined;

        // Process the refund
        const refundResponse = await new Promise((resolve, reject) => {
            channelPartnerApi.refundChannelPartnerOrder(
                    orderId,
                    order,
                {
                    reject_after_refund: rejectAfterRefund,
                    skip_customer_notification: skipCustomerNotification,
                    auto_order_cancel: autoOrderCancel,
                    manual_refund: manualRefund,
                    reverse_affiliate_transactions: reverseAffiliateTransactions,
                    issue_store_credit: issueStoreCredit,
                    auto_order_cancel_reason: autoOrderCancelReason,
                    _expand: expand
                },
                function (error, data) {
                    if (error) {
                        reject(error);
                    } else {
                        resolve(data);
                    }
                }
            );
        });

        // Log error and updated order
        const error = refundResponse.error;
        const updatedOrder = refundResponse.order;

        // Log error and updated order details
        console.log("Error:");
        console.log(error ? JSON.stringify(error, null, 2) : "null");
        console.log("\n\n--------------------\n\n");
        console.log("Updated Order:");
        console.log(updatedOrder ? JSON.stringify(updatedOrder, null, 2) : "null");
    } catch (ex) {
        const error = ex instanceof Error ? ex : new Error('Unknown error');
        console.error(`Error: ${error.message}`);
        console.error(error.stack);
    }
}

// Optional: If you want to run this directly
if (require.main === module) {
    execute().catch(console.error);
}

<?php

ini_set('display_errors', 1);

/*
 * IMPORTANT: Do NOT construct the refunded order.  This method does a refund but also update the entire object, so start with an order query.
 * ALWAYS start with an order retrieved from the system.
 * 1. Call getChannelPartnerOrder or getChannelPartnerOrderByChannelPartnerOrderId to retrieve the order being refunded
 * 2. For a full refund, reverse the following:
 *    A. Set the refunded qty and refunded amount for each item.
 *    B. Set the refunded tax (if any)
 *    C. Set the refunded shipping
 * NOTE: refund amounts are positive numbers.  If any item total cost is $20.00, a full refunded amount would also be positive $20.00
 * See the ChannelPartnerApi.getChannelPartnerOrder() sample for details on that method.
 */


use ultracart\v2\api\ChannelPartnerApi;

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


$channel_partner_api = ChannelPartnerApi::usingApiKey(Constants::CHANNEL_PARTNER_API_KEY);
// for a comment on this expansion, see getChannelPartnerOrder sample.
$expansion = "item,summary,shipping";


// This order MUST be an order associated with this channel partner, or you will receive a 400 Bad Request.
$order_id = 'DEMO-0009106820';
$api_response = $channel_partner_api->getChannelPartnerOrder($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();

// RefundReason may be required, but is optional by default.
// RefundReason may be a set list, or may be freeform.  This is configured on the backend (secure.ultracart.com)
// by Navigating to Home -> Configuration -> Order Management -> Refund/Reject Reasons
// Warning: If this is a 2nd refund after an initial partial refund, be sure you account for the units and amount already refunded.
$order->setRefundReason('Damage Product');
$order->getSummary()->setTaxRefunded($order->getSummary()->getTaxRefunded());
$order->getSummary()->setShippingHandlingRefunded($order->getSummary()->getShippingHandlingTotal());
foreach ($order->getItems() as $item) {
    // item level refund reasons are optional, but may be required.  See the above breadcrumb trail for refund reason config.
    $item->setRefundReason('DifferentItem');
    $item->setQuantityRefunded($item->getQuantity());
    $item->setTotalRefunded($item->getTotalCostWithDiscount());
}

$reject_after_refund = false;
$skip_customer_notifications = true;
$auto_order_cancel = false; // if this was an auto order, and they wanted to cancel it, set this flag to true.
// set $manual_refund to true if the actual refund happened outside the system, and you just want a record of it.
// If UltraCart did not process this refund, $manual_refund should be true.
$manual_refund = false;
$reverse_affiliate_transactions = true; // for a full refund, the affiliate should not get credit, or should they?
$issue_store_credit = false;  // if true, the customer would receive store credit instead of a return on their credit card.
$auto_order_cancel_reason = null;

/** @noinspection PhpConditionAlreadyCheckedInspection */
$api_response = $channel_partner_api->refundChannelPartnerOrder($order_id, $order, $reject_after_refund,
    $skip_customer_notifications, $auto_order_cancel, $manual_refund, $reverse_affiliate_transactions,
    $issue_store_credit, $auto_order_cancel_reason, $expansion);

$error = $api_response->getError();
$updated_order = $api_response->getOrder();
// verify the updated order contains all the desired refunds.  verify that refunded total is equal to total.

// Note: The error 'Request to refund an invalid amount.' means you requested a total refund amount less than or equal to zero.
echo '<html lang="en"><body><pre>';
var_dump($error);
echo '<br/><br/><hr/><hr/><br/><br/>';
var_dump($updated_order);
echo '</pre></body></html>';

from ultracart.apis import ChannelPartnerApi
from samples import channel_partner_api_client

# Initialize API
channel_partner_api = ChannelPartnerApi(channel_partner_api_client())

# Expansion parameter for order details
expand = "item,summary,shipping"

# Order ID must be associated with this channel partner
order_id = 'DEMO-0009106820'
api_response = channel_partner_api.get_channel_partner_order(order_id, expand=expand)

if api_response.error is not None:
    print(api_response.error.developer_message)
    print(api_response.error.user_message)
    exit()

order = api_response.order

# Set refund details
order.refund_reason = 'Damage Product'
order.summary.tax_refunded = order.summary.tax_refunded
order.summary.shipping_handling_refunded = order.summary.shipping_handling_total

# Process refunds for all items
for item in order.items:
    item.refund_reason = 'DifferentItem'
    item.quantity_refunded = item.quantity
    item.total_refunded = item.total_cost_with_discount

# Refund parameters
reject_after_refund = False
skip_customer_notifications = True
auto_order_cancel = False  # Set True to cancel auto orders
manual_refund = False  # Set True if refund processed outside system
reverse_affiliate_transactions = True  # Whether affiliate should get credit
issue_store_credit = False  # True for store credit instead of card refund
auto_order_cancel_reason = None

# Process the refund
api_response = channel_partner_api.refund_channel_partner_order(
    order_id, order, reject_after_refund, skip_customer_notifications,
    auto_order_cancel, manual_refund, reverse_affiliate_transactions,
    issue_store_credit, auto_order_cancel_reason, expand=expand
)

error = api_response.error
updated_order = api_response.order
print(error)
print("\n\n")
print(updated_order)
# IMPORTANT: Do NOT construct the refunded order. This method does a refund but also update the entire object, so start with an order query.
# ALWAYS start with an order retrieved from the system.
# 1. Call getChannelPartnerOrder or getChannelPartnerOrderByChannelPartnerOrderId to retrieve the order being refunded
# 2. For a full refund, reverse the following:
#    A. Set the refunded qty and refunded amount for each item.
#    B. Set the refunded tax (if any)
#    C. Set the refunded shipping
# NOTE: refund amounts are positive numbers. If any item total cost is $20.00, a full refunded amount would also be positive $20.00
# See the ChannelPartnerApi.getChannelPartnerOrder() sample for details on that method.

require 'ultracart_api'
require_relative '../constants'

channel_partner_api = UltracartClient::ChannelPartnerApi.new_using_api_key(Constants::CHANNEL_PARTNER_API_KEY)
# for a comment on this expansion, see getChannelPartnerOrder sample.
expansion = "item,summary,shipping"

# This order MUST be an order associated with this channel partner, or you will receive a 400 Bad Request.
order_id = 'DEMO-0009106820'
api_response = channel_partner_api.get_channel_partner_order(order_id, _expand: expansion)

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

order = api_response.order

# RefundReason may be required, but is optional by default.
# RefundReason may be a set list, or may be freeform. This is configured on the backend (secure.ultracart.com)
# by Navigating to Home -> Configuration -> Order Management -> Refund/Reject Reasons
# Warning: If this is a 2nd refund after an initial partial refund, be sure you account for the units and amount already refunded.
order.refund_reason = 'Damage Product'
order.summary.tax_refunded = order.summary.tax_refunded
order.summary.shipping_handling_refunded = order.summary.shipping_handling_total

order.items.each do |item|
  # item level refund reasons are optional, but may be required. See the above breadcrumb trail for refund reason config.
  item.refund_reason = 'DifferentItem'
  item.quantity_refunded = item.quantity
  item.total_refunded = item.total_cost_with_discount
end

reject_after_refund = false
skip_customer_notifications = true
auto_order_cancel = false # if this was an auto order, and they wanted to cancel it, set this flag to true.
# set manual_refund to true if the actual refund happened outside the system, and you just want a record of it.
# If UltraCart did not process this refund, manual_refund should be true.
manual_refund = false
reverse_affiliate_transactions = true # for a full refund, the affiliate should not get credit, or should they?
issue_store_credit = false  # if true, the customer would receive store credit instead of a return on their credit card.
auto_order_cancel_reason = nil

api_response = channel_partner_api.refund_channel_partner_order(order_id, order,
  reject_after_refund: reject_after_refund,
  skip_customer_notifications: skip_customer_notifications,
  auto_order_cancel: auto_order_cancel,
  manual_refund: manual_refund,
  reverse_affiliate_transactions: reverse_affiliate_transactions,
  issue_store_credit: issue_store_credit,
  auto_order_cancel_reason: auto_order_cancel_reason,
  _expand: expansion)

error = api_response.error
updated_order = api_response.order
# verify the updated order contains all the desired refunds. verify that refunded total is equal to total.

# Note: The error 'Request to refund an invalid amount.' means you requested a total refund amount less than or equal to zero.
p error
puts "\n\n-----------------\n\n"
p updated_order
import {
    ModelError,
    Order
} from 'ultracart_rest_api_v2_typescript';
import { channelPartnerApi } from '../api';

/**
 * IMPORTANT: Do NOT construct the refunded order. This method does a refund but also update the entire object, so start with an order query.
 * ALWAYS start with an order retrieved from the system.
 * 1. Call getChannelPartnerOrder or getChannelPartnerOrderByChannelPartnerOrderId to retrieve the order being refunded
 * 2. For a full refund, reverse the following:
 *    A. Set the refunded qty and refunded amount for each item.
 *    B. Set the refunded tax (if any)
 *    C. Set the refunded shipping
 * NOTE: refund amounts are positive numbers. If any item total cost is $20.00, a full refunded amount would also be positive $20.00
 * See the ChannelPartnerApi.getChannelPartnerOrder() sample for details on that method.
 */
export async function execute(): Promise<void> {
    try {
        // For a comment on this expand, see getChannelPartnerOrder sample.
        const expand: string = "item,summary,shipping";

        // This order MUST be an order associated with this channel partner, or you will receive a 400 Bad Request.
        const orderId: string = "DEMO-0009106820";

        // Retrieve the order
        const apiResponse = await channelPartnerApi.getChannelPartnerOrder({orderId, expand});

        // Check for errors
        if (apiResponse.error) {
            const error: ModelError = apiResponse.error;
            console.error(error);
            console.error(error.user_message);
            process.exit(1);
        }

        // Ensure order exists
        if (!apiResponse.order) {
            console.error("No order found");
            process.exit(1);
        }

        // Create a copy of the order to modify
        const order: Order = { ...apiResponse.order };

        // RefundReason may be required, but is optional by default.
        // RefundReason may be a set list, or may be freeform. This is configured on the backend (secure.ultracart.com)
        // by Navigating to Home -> Configuration -> Order Management -> Refund/Reject Reasons
        // Warning: If this is a 2nd refund after an initial partial refund, be sure you account for the units and amount already refunded.
        order.refund_reason = "Damage Product";

        // Ensure summary exists before modifying
        if (order.summary) {
            order.summary.tax_refunded = order.summary.tax;
            order.summary.shipping_handling_refunded = order.summary.shipping_handling_total;
        }

        // Modify items for refund
        if (order.items) {
            order.items.forEach(item => {
                // Item level refund reasons are optional, but may be required.
                // See the above breadcrumb trail for refund reason config.
                item.refund_reason = "DifferentItem";
                item.quantity_refunded = item.quantity;
                item.total_refunded = item.total_cost_with_discount;
            });
        }

        // Refund parameters
        const rejectAfterRefund: boolean = false;
        const skipCustomerNotification: boolean = true;
        const autoOrderCancel: boolean = false; // If this was an auto order, and they wanted to cancel it, set this flag to true.
        // Set manualRefund to true if the actual refund happened outside the system, and you just want a record of it.
        // If UltraCart did not process this refund, manualRefund should be true.
        const manualRefund: boolean = false;
        const reverseAffiliateTransactions: boolean = true; // For a full refund, the affiliate should not get credit, or should they?
        const issueStoreCredit: boolean = false; // If true, the customer would receive store credit instead of a return on their credit card.
        const autoOrderCancelReason: string | undefined = undefined;

        // Process the refund
        const refundResponse = await channelPartnerApi.refundChannelPartnerOrder({
            orderId,
            order,
            rejectAfterRefund,
            skipCustomerNotification,
            autoOrderCancel,
            manualRefund,
            reverseAffiliateTransactions,
            issueStoreCredit,
            autoOrderCancelReason,
            expand
        });

        // Log error and updated order
        const error: ModelError | undefined = refundResponse.error;
        const updatedOrder: Order | undefined = refundResponse.order;

        // Note: The error 'Request to refund an invalid amount.' means you requested a total refund amount less than or equal to zero.
        console.log("Error:");
        console.log(error ? JSON.stringify(error, null, 2) : "null");
        console.log("\n\n--------------------\n\n");
        console.log("Updated Order:");
        console.log(updatedOrder ? JSON.stringify(updatedOrder, null, 2) : "null");
    }
    catch (ex: unknown) {
        const error = ex as Error;
        console.error(`Error: ${error.message}`);
        console.error(error.stack);
    }
}

// Optional: If you want to run this directly
if (require.main === module) {
    execute().catch(console.error);
}

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

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

ChanelPartnerReasonCodesResponse

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.
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.
success boolean Indicates if API call was successful
warning Warning Warning object if a non-fatal issue or side-effect occurs

ChannelPartner

Attributes
Name Data Type Description
channel_partner_oid integer (int32) Channel partner object id
code string Code associated with the channel partner
communication_method string Communication method of the channel partner
dont_hold_shipment boolean True if shipments should immediately process for this channel partner.
inactive boolean True if the channel partner is inactive
merchant_id string Merchant ID of the channel partner
name string Name of the channel partner
skip_customer_emails boolean True if emails to the customer are skipped for this channel partner.

ChannelPartnerCancelResponse

Attributes
Name Data Type Description
cancel_errors array of string Array of errors if errors occurred
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

ChannelPartnerEstimateShippingResponse

Attributes
Name Data Type Description
error Error Error object if unsuccessful
estimates array of ChannelPartnerShippingEstimate An array of shipping methods and their costs
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

ChannelPartnerEstimateTaxResponse

Attributes
Name Data Type Description
arbitrary_tax number
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

ChannelPartnerImportResponse

Attributes
Name Data Type Description
error Error Error object if unsuccessful
import_errors array of string Array of errors if errors occurred
import_warnings array of string Array of warnings if warnings occurred
metadata ResponseMetadata Meta-data about the response such as payload or paging information
order_id string The order id of the newly imported order if successful
success boolean Indicates if API call was successful
warning Warning Warning object if a non-fatal issue or side-effect occurs

ChannelPartnerOrder

Attributes
Name Data Type Description
advertisingSource string advertising_source
affiliate_id string Affiliate Id
affiliate_sub_id string Affiliate Sub Id
arbitrary_shipping_handling_total number Arbitrary shipping handling total
arbitrary_tax number Arbitrary tax for overriding calculated taxes
arbitrary_tax_rate number Arbitrary tax rate
arbitrary_taxable_subtotal number Arbitrary taxable subtotal
associate_with_customer_profile_if_present boolean If true any matching customer profile based on email is associated with this order
auto_approve_purchase_order boolean If true any purchase orders are automatically approved
billto_address1 string(50) Billing Address line 1
billto_address2 string(50) Billing Address line 2
billto_city string(32) Billing City
billto_company string(50) Billing Company
billto_country_code string(2) Billing ISO-3166 two letter country code
billto_day_phone string(25) Billing Day phone
billto_evening_phone string(25) Billing Evening phone
billto_first_name string(30) Billing First name
billto_last_name string(30) Billing Last name
billto_postal_code string(20) Billing Postal code
billto_state_region string(32) Billing State for United States otherwise region or province for other countries
billto_title string(50) Billing Title
cc_email string(100) CC email.
channel_partner_order_id string The id for this order within the channel partner system.
consider_recurring boolean If true this order is marked as an auto order (recurring)
coupons array of string Array of coupon codes
credit_card_authorization_amount number The amount authorized externally
credit_card_authorization_dts string (dateTime) Date/Time of credit card authorization in ISO8601 format
credit_card_authorization_number string The reference number provided by an externally processed transaction
credit_card_expiration_month integer (int32) Credit card expiration month
credit_card_expiration_year integer (int32) Credit card expiration year
credit_card_type string Credit card type
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
delivery_date string (dateTime) Date the customer is requesting delivery on. Typically used for perishable product delivery.
echeck_bank_aba_code string eCheck bank ABA code
echeck_bank_account_name string eCheck bank account name
echeck_bank_account_number string eCheck bank account number
echeck_bank_account_type string eCheck bank account type
Allowed Values
  • Checking
  • Savings
echeck_bank_name string eCheck bank name
echeck_bank_owner_type string eCheck bank owner type
Allowed Values
  • Business
  • Personal
echeck_customer_tax_id string eCheck customer tax id
echeck_drivers_license_dob string eCheck drivers license dob
echeck_drivers_license_number string eCheck drivers license number
echeck_drivers_license_state string eCheck drivers license state
email string(100) Email
gift boolean True if this order is a gift
gift_email string(100) Email address of the gift recipient
gift_message string(10000) Message to the gift recipient
hosted_fields_card_token string The token provided by UltraCart hosted fields when a credit card number is uploaded into the system. This is the only way to provide a credit card number.
hosted_fields_cvv_token string The token provided by UltraCart hosted fields when a credit card cvv is uploaded into the system. This is the only way to provide a cvv number.
insurance_application_id string Insurance application id
insurance_claim_id string Insurance claim id
ip_address string IP Address of the customer
items array of ChannelPartnerOrderItem Items
least_cost_route boolean If true the least expensive shipping method is automatically chosen during the order import
least_cost_route_shipping_methods array of string An optional array of shipping methods to restict choices if least_cost_route is true
mailing_list_opt_in boolean If true the customer is subscribed to any configured mailing lists
no_realtime_payment_processing boolean If true no payment processing is done and the order is placed into Accounts Receivable
payment_method string Payment method
Allowed Values
  • Affirm
  • Amazon
  • Check
  • COD
  • Credit Card
  • eCheck
  • LoanHero
  • Money Order
  • PayPal
  • Purchase Order
  • Quote Request
  • Wire Transfer
  • PayPal Fastlane
purchase_order_number string Purchase order number
rotating_transaction_gateway_code string The rotating transaction gateway code for the gateway used to charge this order
sales_rep_code string Sales rep code
screen_branding_theme_code string(10) Screen branding theme code
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 adress is residential. Effects the methods that are available to the customer as well as the price of the shipping method.
shipping_method string Shipping method
shipto_address1 string(50) Shipping Address line 1
shipto_address2 string(50) Shipping Address line 2
shipto_city string(32) Shipping City
shipto_company string(50) Shipping Company
shipto_country_code string(2) Shipping ISO-3166 two letter country code
shipto_day_phone string(25) Shipping Day phone
shipto_evening_phone string(25) Shipping Evening phone
shipto_first_name string(30) Shipping First name
shipto_last_name string(30) Shipping Last name
shipto_postal_code string(20) Shipping Postal code
shipto_state_region string(32) Shipping State for United States otherwise region or province for other countries
shipto_title string(50) Shipping Title
skip_payment_processing boolean If true the order is placed directly into the shipping department
special_instructions string(10000) Special instructions from the customer regarding shipping
store_completed boolean If true the order bypasses shipping and is marked completed
store_if_payment_declines boolean If true any failed payments are placed into Accounts Receivable. If false any failed payments result in a rejected order resulting in errors thrown during the insert routine
storefront_host_name string StoreFront host name associated with the order
tax_county string The optional shipping county used to determine exact taxes
tax_exempt boolean If true this order is marked as being tax exempt
transaction ChannelPartnerOrderTransaction Transaction status and details
treat_warnings_as_errors boolean If true all warnings are considered errors, this is true by default
use_prior_payment_information_from_order_id string An Order Id from a prior purchase of this customer which is used to retrieve vaulted payment information in order to pay for this current order.

ChannelPartnerOrderItem

Attributes
Name Data Type Description
arbitrary_unit_cost number Arbitrary unit cost for this item that differs from the listed price
auto_order_last_rebill_dts string (dateTime) Optional date/time of the last rebill if this item is part of an auto (recurring) order
auto_order_schedule string The frequency schedule for this item if this item is part of an auto (recurring) order
Allowed Values
  • Weekly
  • Every 10 Days
  • Biweekly
  • 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
merchant_item_id string(20) Item ID
options array of ChannelPartnerOrderItemOption Item options
properties array of ChannelPartnerOrderItemProperty Properties
quantity number Quantity
upsell boolean True if this item was an upsell item.

ChannelPartnerOrderItemOption

Attributes
Name Data Type Description
name string The name of the item option.
value string The value of the item option.

ChannelPartnerOrderItemProperty

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

ChannelPartnerOrderTransaction

Attributes
Name Data Type Description
details array of ChannelPartnerOrderTransactionDetail Transaction gateway details
successful boolean True if the transaction was successfully charged

ChannelPartnerOrderTransactionDetail

Attributes
Name Data Type Description
name string The name of the item option.
value string The value of the item option.

ChannelPartnerShippingEstimate

Attributes
Name Data Type Description
shipping_handling_total number The total estimate for this shipping method based on the provided order.
shipping_method string The name of the shipping method

ChannelPartnerShipToPreference

Attributes
Name Data Type Description
additional_kit_component_item_ids array of string Additional item ids to add as kit components to the order with a zero price.
channel_partner_oid integer (int32) The channel partner object identifier this preference is associated with
channel_partner_ship_to_preference_oid integer (int32) Object identifier for the ship to preference
description string(100) A description that is meaningful to the merchant.
merchant_id string The merchant id that owns the channel partner
return_policy string Alternate return policy to print on the packing slip.
ship_to_edi_code string The ship to EDI code that the preferences are for

ChannelPartnerShipToPreferenceResponse

Attributes
Name Data Type Description
error Error Error object if unsuccessful
metadata ResponseMetadata Meta-data about the response such as payload or paging information
ship_to_preference ChannelPartnerShipToPreference
success boolean Indicates if API call was successful
warning Warning Warning object if a non-fatal issue or side-effect occurs

ChannelPartnerShipToPreferencesResponse

Attributes
Name Data Type Description
error Error Error object if unsuccessful
metadata ResponseMetadata Meta-data about the response such as payload or paging information
shipToPreferences array of ChannelPartnerShipToPreference ship_to_preferences
success boolean Indicates if API call was successful
warning Warning Warning object if a non-fatal issue or side-effect occurs

ChannelPartnersResponse

Attributes
Name Data Type Description
channelPartners array of ChannelPartner channel_partners
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

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

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

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

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

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
  • PayPal Fastlane
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.

OrderProperty

Attributes
Name Data Type Description
created_by string(20) Created by user
created_dts string (dateTime) The date/time that the property was created by the user
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

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.

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

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

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

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