coupon
/coupon
/coupon
using System;
using System.Reflection;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;
namespace SdkSample.coupon
{
public class GetAutoApply
{
/*
getAutoApply returns back the items and subtotals that trigger "auto coupons", i.e. coupons that are automatically
added to a shopping cart. The manual configuration of auto coupons is at the bottom of the main coupons screen.
See: https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1376525/Coupons#Coupons-Navigation
*/
public static void Execute()
{
Console.WriteLine("--- " + MethodBase.GetCurrentMethod()?.DeclaringType?.Name + " ---");
try
{
// Create coupon API instance using API key
CouponApi couponApi = new CouponApi(Constants.ApiKey);
// Get auto apply coupons information
var apiResponse = couponApi.GetAutoApply();
// Display subtotal levels
Console.WriteLine("These are the subtotal levels:");
foreach (var subtotalLevel in apiResponse.SubtotalLevels)
{
Console.WriteLine(subtotalLevel);
}
// Display item triggers
Console.WriteLine("These are the item triggers:");
foreach (var requiredItem in apiResponse.RequiredItems)
{
Console.WriteLine(requiredItem);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
Console.WriteLine(ex.StackTrace);
}
}
}
}
package coupon;
import com.ultracart.admin.v2.CouponApi;
import com.ultracart.admin.v2.models.CouponAutoApplyConditions;
import com.ultracart.admin.v2.util.ApiException;
import common.Constants;
public class GetAutoApply {
/*
getAutoApply returns back the items and subtotals that trigger "auto coupons", i.e. coupons that are automatically
added to a shopping cart. The manual configuration of auto coupons is at the bottom of the main coupons screen.
See: https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1376525/Coupons#Coupons-Navigation
*/
public static void execute() {
try {
// Create coupon API instance using API key
CouponApi couponApi = new CouponApi(Constants.API_KEY);
// Get auto apply coupons information
CouponAutoApplyConditions apiResponse = couponApi.getAutoApply();
// Display subtotal levels
System.out.println("These are the subtotal levels:");
for (Object subtotalLevel : apiResponse.getSubtotalLevels()) {
System.out.println(subtotalLevel);
}
// Display item triggers
System.out.println("These are the item triggers:");
for (Object requiredItem : apiResponse.getRequiredItems()) {
System.out.println(requiredItem);
}
}
catch (ApiException ex) {
System.out.println("Error: " + ex.getMessage());
ex.printStackTrace();
}
}
}
import { couponApi } from '../api.js';
export class GetAutoApply {
/*
getAutoApply returns back the items and subtotals that trigger "auto coupons", i.e. coupons that are automatically
added to a shopping cart. The manual configuration of auto coupons is at the bottom of the main coupons screen.
See: https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1376525/Coupons#Coupons-Navigation
*/
static async execute() {
console.log("--- GetAutoApply ---");
try {
// Get auto apply coupons information
const apiResponse = await new Promise((resolve, reject) => {
couponApi.getAutoApply(function (error, data, response) {
if (error) {
reject(error);
} else {
resolve(data, response);
}
});
});
// Display subtotal levels
console.log("These are the subtotal levels:");
for (const subtotalLevel of apiResponse.subtotal_levels || []) {
console.log(subtotalLevel);
}
// Display item triggers
console.log("These are the item triggers:");
for (const requiredItem of apiResponse.required_items || []) {
console.log(requiredItem);
}
} catch (ex) {
console.log(`Error: ${ex.message}`);
console.log(ex.stack);
}
}
}
<?php
/*
getAutoApply returns back the items and subtotals that trigger "auto coupons", i.e. coupons that are automatically
added to a shopping cart. The manual configuration of auto coupons is at the bottom of the main coupons screen.
See: https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1376525/Coupons#Coupons-Navigation
*/
use ultracart\v2\api\CouponApi;
require_once '../vendor/autoload.php';
$coupon_api = CouponApi::usingApiKey(Constants::API_KEY);
$api_response = $coupon_api->getAutoApply();
echo 'These are the subtotal levels:<br>';
foreach ($api_response->getSubtotalLevels() as $subtotalLevel) {
var_dump($subtotalLevel);
echo '<br>';
}
echo 'These are the item triggers:<br>';
foreach ($api_response->getRequiredItems() as $requiredItem) {
var_dump($requiredItem);
echo '<br>';
}
"""
getAutoApply returns back the items and subtotals that trigger "auto coupons", i.e. coupons that are automatically
added to a shopping cart. The manual configuration of auto coupons is at the bottom of the main coupons screen.
See: https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1376525/Coupons#Coupons-Navigation
"""
from ultracart.apis import CouponApi
from samples import api_client
coupon_api = CouponApi(api_client())
api_response = coupon_api.get_auto_apply()
print('These are the subtotal levels:')
for subtotal_level in api_response.subtotal_levels:
print(subtotal_level)
print()
print('These are the item triggers:')
for required_item in api_response.required_items:
print(required_item)
print()
require_relative '../constants'
require 'ultracart_api'
=begin
getAutoApply returns back the items and subtotals that trigger "auto coupons", i.e. coupons that are automatically
added to a shopping cart. The manual configuration of auto coupons is at the bottom of the main coupons screen.
See: https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1376525/Coupons#Coupons-Navigation
=end
coupon_api = UltracartClient::CouponApi.new_using_api_key(Constants::API_KEY)
api_response = coupon_api.get_auto_apply
puts 'These are the subtotal levels:'
api_response.subtotal_levels.each do |subtotal_level|
puts subtotal_level.inspect
end
puts "\nThese are the item triggers:"
api_response.required_items.each do |required_item|
puts required_item.inspect
end
import { couponApi } from '../api';
import {CouponAutoApplyConditions} from 'ultracart_rest_api_v2_typescript';
export class GetAutoApply {
/*
getAutoApply returns back the items and subtotals that trigger "auto coupons", i.e. coupons that are automatically
added to a shopping cart. The manual configuration of auto coupons is at the bottom of the main coupons screen.
See: https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1376525/Coupons#Coupons-Navigation
*/
public static async execute(): Promise<void> {
console.log("--- GetAutoApply ---");
try {
// Get auto apply coupons information
const apiResponse: CouponAutoApplyConditions = await couponApi.getAutoApply();
// Display subtotal levels
console.log("These are the subtotal levels:");
for (const subtotalLevel of apiResponse.subtotal_levels || []) {
console.log(subtotalLevel);
}
// Display item triggers
console.log("These are the item triggers:");
for (const requiredItem of apiResponse.required_items || []) {
console.log(requiredItem);
}
} catch (ex: any) {
console.log(`Error: ${ex.message}`);
console.log(ex.stack);
}
}
}
Update auto apply rules and conditions
SDK Function Name: updateAutoApply
Parameter | Description | Location | Data Type | Required |
---|---|---|---|---|
conditions | Conditions | body | CouponAutoApplyConditions | required |
using System;
using System.Collections.Generic;
using System.Reflection;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;
namespace SdkSample.coupon
{
public class UpdateAutoApply
{
/*
updateAutoApply updates the items and subtotals conditions that trigger "auto coupons", i.e. coupons that are automatically
added to a shopping cart. The manual configuration of auto coupons is at the bottom of the main coupons screen.
See: https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1376525/Coupons#Coupons-Navigation
// Success is 200 (There is no content. Yes, this should return a 204, but it returns a 200 with no content)
*/
public static void Execute()
{
Console.WriteLine("--- " + MethodBase.GetCurrentMethod()?.DeclaringType?.Name + " ---");
try
{
// Create coupon API instance using API key
CouponApi couponApi = new CouponApi(Constants.ApiKey);
// Create auto apply conditions
CouponAutoApplyConditions autoApply = new CouponAutoApplyConditions();
// Create item condition
CouponAutoApplyCondition itemCondition = new CouponAutoApplyCondition();
itemCondition.RequiredItemId = "ITEM_ABC";
itemCondition.CouponCode = "10OFF";
List<CouponAutoApplyCondition> itemConditions = new List<CouponAutoApplyCondition> { itemCondition };
// Create subtotal condition
CouponAutoApplyCondition subtotalCondition = new CouponAutoApplyCondition();
subtotalCondition.MinimumSubtotal = 50; // must spend fifty dollars
subtotalCondition.CouponCode = "5OFF"; // Corrected from item condition in original code
List<CouponAutoApplyCondition> subtotalConditions = new List<CouponAutoApplyCondition> { subtotalCondition };
// Set conditions to auto apply object
autoApply.RequiredItems = itemConditions;
autoApply.SubtotalLevels = subtotalConditions;
// Update auto apply conditions
couponApi.UpdateAutoApply(autoApply);
Console.WriteLine("Auto apply conditions updated successfully");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
Console.WriteLine(ex.StackTrace);
}
}
}
}
package coupon;
import java.math.BigDecimal;
import java.util.List;
import java.util.ArrayList;
import com.ultracart.admin.v2.CouponApi;
import com.ultracart.admin.v2.models.CouponAutoApplyConditions;
import com.ultracart.admin.v2.models.CouponAutoApplyCondition;
import com.ultracart.admin.v2.util.ApiException;
import common.Constants;
public class UpdateAutoApply {
/*
updateAutoApply updates the items and subtotals conditions that trigger "auto coupons", i.e. coupons that are automatically
added to a shopping cart. The manual configuration of auto coupons is at the bottom of the main coupons screen.
See: https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1376525/Coupons#Coupons-Navigation
// Success is 200 (There is no content. Yes, this should return a 204, but it returns a 200 with no content)
*/
public static void Execute() {
System.out.println("--- " + UpdateAutoApply.class.getSimpleName() + " ---");
try {
// Create coupon API instance using API key
CouponApi couponApi = new CouponApi(Constants.API_KEY);
// Create auto apply conditions
CouponAutoApplyConditions autoApply = new CouponAutoApplyConditions();
// Create item condition
CouponAutoApplyCondition itemCondition = new CouponAutoApplyCondition();
itemCondition.setRequiredItemId("ITEM_ABC");
itemCondition.setCouponCode("10OFF");
List<CouponAutoApplyCondition> itemConditions = new ArrayList<>();
itemConditions.add(itemCondition);
// Create subtotal condition
CouponAutoApplyCondition subtotalCondition = new CouponAutoApplyCondition();
subtotalCondition.setMinimumSubtotal(new BigDecimal("50")); // must spend fifty dollars
subtotalCondition.setCouponCode("5OFF");
List<CouponAutoApplyCondition> subtotalConditions = new ArrayList<>();
subtotalConditions.add(subtotalCondition);
// Set conditions to auto apply object
autoApply.setRequiredItems(itemConditions);
autoApply.setSubtotalLevels(subtotalConditions);
// Update auto apply conditions
couponApi.updateAutoApply(autoApply);
System.out.println("Auto apply conditions updated successfully");
}
catch (ApiException ex) {
System.out.println("Error: " + ex.getMessage());
ex.printStackTrace();
}
}
}
// Import API and UltraCart types
import { couponApi } from '../api.js';
// Namespace-like structure using a class
export class UpdateAutoApply {
/*
* updateAutoApply updates the items and subtotals conditions that trigger "auto coupons", i.e. coupons that are automatically
* added to a shopping cart. The manual configuration of auto coupons is at the bottom of the main coupons screen.
* See: https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1376525/Coupons#Coupons-Navigation
*
* // Success is 200 (There is no content. Yes, this should return a 204, but it returns a 200 with no content)
*/
static async execute() {
console.log(`--- UpdateAutoApply ---`);
try {
// Create auto apply conditions
const autoApply = {};
// Create item condition
const itemCondition = {
required_item_id: "ITEM_ABC",
coupon_code: "10OFF",
};
const itemConditions = [itemCondition];
// Create subtotal condition
const subtotalCondition = {
minimum_subtotal: 50, // must spend fifty dollars
coupon_code: "5OFF", // Corrected from item condition in original code
};
const subtotalConditions = [subtotalCondition];
// Set conditions to auto apply object
autoApply.required_items = itemConditions;
autoApply.subtotal_levels = subtotalConditions;
// Update auto apply conditions
const response = await new Promise((resolve, reject) => {
couponApi.updateAutoApply(autoApply, function (error, data, response) {
if (error) {
reject(error);
} else {
resolve(data, response);
}
});
});
console.log("Auto apply conditions updated successfully");
} catch (ex) {
console.log(`Error: ${ex.message}`);
console.log(ex.stack);
}
}
}
<?php
/*
updateAutoApply updates the items and subtotals conditions that trigger "auto coupons", i.e. coupons that are automatically
added to a shopping cart. The manual configuration of auto coupons is at the bottom of the main coupons screen.
See: https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1376525/Coupons#Coupons-Navigation
// Success is 200 (There is no content. Yes, this should return a 204, but it returns a 200 with no content)
*/
use ultracart\v2\api\CouponApi;
use ultracart\v2\models\CouponAutoApplyCondition;
use ultracart\v2\models\CouponAutoApplyConditions;
require_once '../vendor/autoload.php';
$coupon_api = CouponApi::usingApiKey(Constants::API_KEY);
$autoApply = new CouponAutoApplyConditions();
$itemCondition = new CouponAutoApplyCondition();
$itemCondition->setRequiredItemId('ITEM_ABC');
$itemCondition->setCouponCode('10OFF');
$itemConditions = [$itemCondition];
$subtotalCondition = new CouponAutoApplyCondition();
$subtotalCondition->setMinimumSubtotal(50); // must spend fifty dollars
$itemCondition->setCouponCode('5OFF');
$subtotalConditions = [$subtotalCondition];
$autoApply->setRequiredItems($itemConditions);
$autoApply->setSubtotalLevels($subtotalConditions);
$coupon_api->updateAutoApply($autoApply);
from ultracart.apis import CouponApi
from ultracart.models import CouponAutoApplyCondition, CouponAutoApplyConditions
from samples import api_client
coupon_api = CouponApi(api_client())
auto_apply = CouponAutoApplyConditions()
item_condition = CouponAutoApplyCondition()
item_condition.required_item_id = 'ITEM_ABC'
item_condition.coupon_code = '10OFF'
item_conditions = [item_condition]
subtotal_condition = CouponAutoApplyCondition()
subtotal_condition.minimum_subtotal = 50 # must spend fifty dollars
subtotal_condition.coupon_code = '5OFF' # Fixed bug: was setting on item_condition in PHP
subtotal_conditions = [subtotal_condition]
auto_apply.required_items = item_conditions
auto_apply.subtotal_levels = subtotal_conditions
coupon_api.update_auto_apply(auto_apply)
require 'ultracart_api'
require_relative '../constants'
# updateAutoApply updates the items and subtotals conditions that trigger "auto coupons", i.e. coupons that are automatically
# added to a shopping cart. The manual configuration of auto coupons is at the bottom of the main coupons screen.
# See: https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1376525/Coupons#Coupons-Navigation
# Success is 200 (There is no content. Yes, this should return a 204, but it returns a 200 with no content)
# Initialize the coupon API
coupon_api = UltracartClient::CouponApi.new_using_api_key(Constants::API_KEY)
auto_apply = UltracartClient::CouponAutoApplyConditions.new
item_condition = UltracartClient::CouponAutoApplyCondition.new
item_condition.required_item_id = 'ITEM_ABC'
item_condition.coupon_code = '10OFF'
item_conditions = [item_condition]
subtotal_condition = UltracartClient::CouponAutoApplyCondition.new
subtotal_condition.minimum_subtotal = 50 # must spend fifty dollars
item_condition.coupon_code = '5OFF'
subtotal_conditions = [subtotal_condition]
auto_apply.required_items = item_conditions
auto_apply.subtotal_levels = subtotal_conditions
coupon_api.update_auto_apply(auto_apply)
// Import API and UltraCart types
import { couponApi } from '../api';
import { CouponAutoApplyCondition, CouponAutoApplyConditions } from 'ultracart_rest_api_v2_typescript';
// Namespace-like structure using a class
export class UpdateAutoApply {
/*
* updateAutoApply updates the items and subtotals conditions that trigger "auto coupons", i.e. coupons that are automatically
* added to a shopping cart. The manual configuration of auto coupons is at the bottom of the main coupons screen.
* See: https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/1376525/Coupons#Coupons-Navigation
*
* // Success is 200 (There is no content. Yes, this should return a 204, but it returns a 200 with no content)
*/
public static async execute(): Promise<void> {
console.log(`--- UpdateAutoApply ---`);
try {
// Create auto apply conditions
const autoApply: CouponAutoApplyConditions = {};
// Create item condition
const itemCondition: CouponAutoApplyCondition = {
required_item_id: "ITEM_ABC",
coupon_code: "10OFF",
};
const itemConditions: CouponAutoApplyCondition[] = [itemCondition];
// Create subtotal condition
const subtotalCondition: CouponAutoApplyCondition = {
minimum_subtotal: 50, // must spend fifty dollars
coupon_code: "5OFF", // Corrected from item condition in original code
};
const subtotalConditions: CouponAutoApplyCondition[] = [subtotalCondition];
// Set conditions to auto apply object
autoApply.required_items = itemConditions;
autoApply.subtotal_levels = subtotalConditions;
// Update auto apply conditions
await couponApi.updateAutoApply({
conditions: autoApply
});
console.log("Auto apply conditions updated successfully");
} catch (ex) {
console.log(`Error: ${(ex as Error).message}`);
console.log((ex as Error).stack);
}
}
}
Retrieves coupons for this account. If no parameters are specified, all coupons will be returned. You will need to make multiple API calls in order to retrieve the entire result set since this API performs result set pagination.
SDK Function Name: getCoupons
Parameter | Description | Location | Data Type | Required |
---|---|---|---|---|
merchant_code | Merchant code | query | string | optional |
description | Description | query | string | optional |
coupon_type | Coupon type | query | string | optional |
start_date_begin | Start date begin | query | string | optional |
start_date_end | Start date end | query | string | optional |
expiration_date_begin | Expiration date begin | query | string | optional |
expiration_date_end | Expiration date end | query | string | optional |
affiliate_oid | Affiliate oid | query | integer (int32) | optional |
exclude_expired | Exclude expired | query | boolean | optional |
${parameter.name} | ${parameter.in} | string | optional | |
_limit | The maximum number of records to return on this one API call. (Max 200)
Default: 100 |
query | integer | optional |
_offset | Pagination of the record set. Offset is a zero based index.
Default: 0 |
query | integer | optional |
_sort | The sort order of the coupons. See Sorting documentation for examples of using multiple values and sorting by ascending and descending.
Allowed Values
|
query | string | optional |
_expand | The object expansion to perform on the result. See documentation for examples | query | string | optional |
using System;
using System.Collections.Generic;
using System.Reflection;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;
namespace SdkSample.coupon
{
public class GetCoupons
{
public static void Execute()
{
Console.WriteLine("--- " + MethodBase.GetCurrentMethod()?.DeclaringType?.Name + " ---");
try
{
List<Coupon> coupons = new List<Coupon>();
int iteration = 1;
int offset = 0;
int limit = 200;
bool needMoreRecords = true;
while (needMoreRecords)
{
Console.WriteLine($"executing iteration #{iteration++}");
List<Coupon> blockOfCoupons = GetCouponsChunk(offset, limit);
foreach (Coupon coupon in blockOfCoupons)
{
coupons.Add(coupon);
}
offset += limit;
needMoreRecords = blockOfCoupons.Count == limit;
// Thread.Sleep(1000); // I'm testing rate limiter headers. this should probably be uncommented. maybe.
}
// Display the coupons
foreach (var coupon in coupons)
{
Console.WriteLine(coupon);
}
Console.WriteLine($"Total coupons retrieved: {coupons.Count}");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
Console.WriteLine(ex.StackTrace);
}
}
/// <summary>
/// Returns a block of coupons
/// </summary>
/// <param name="offset">pagination variable</param>
/// <param name="limit">pagination variable. max server will allow is 200</param>
/// <returns>List of Coupon objects</returns>
public static List<Coupon> GetCouponsChunk(int offset = 0, int limit = 200)
{
// Create coupon API instance using API key
CouponApi couponApi = new CouponApi(Constants.ApiKey);
// TODO: consider using GetCouponsByQuery() as it does not require all search parameters
string merchantCode = null;
string description = null;
string couponType = null;
string startDateBegin = null;
string startDateEnd = null;
string expirationDateBegin = null;
string expirationDateEnd = null;
int? affiliateOid = null;
bool? excludeExpired = null;
string sort = null;
string expand = null; // getCoupons doesn't have any expansions. full record is always returned.
var getResponse = couponApi.GetCoupons(merchantCode, description, couponType,
startDateBegin, startDateEnd, expirationDateBegin, expirationDateEnd,
affiliateOid, excludeExpired, limit, offset, sort, expand);
if (getResponse.Success && getResponse.Success)
{
return getResponse.Coupons;
}
return new List<Coupon>();
}
}
}
package coupon;
import com.ultracart.admin.v2.CouponApi;
import com.ultracart.admin.v2.models.Coupon;
import com.ultracart.admin.v2.models.CouponsResponse;
import com.ultracart.admin.v2.util.ApiException;
import common.Constants;
import java.util.ArrayList;
import java.util.List;
public class GetCoupons {
public static void execute() {
try {
List<Coupon> coupons = new ArrayList<>();
int iteration = 1;
int offset = 0;
int limit = 200;
boolean needMoreRecords = true;
while (needMoreRecords) {
System.out.println("executing iteration #" + iteration++);
List<Coupon> blockOfCoupons = getCouponsChunk(offset, limit);
coupons.addAll(blockOfCoupons);
offset += limit;
needMoreRecords = blockOfCoupons.size() == limit;
}
// Display the coupons
for (Coupon coupon : coupons) {
System.out.println(coupon);
}
System.out.println("Total coupons retrieved: " + coupons.size());
}
catch (ApiException ex) {
System.out.println("Error: " + ex.getMessage());
ex.printStackTrace();
}
}
/**
* Returns a block of coupons
*
* @param offset pagination variable
* @param limit pagination variable. max server will allow is 200
* @return List of Coupon objects
*/
public static List<Coupon> getCouponsChunk(int offset, int limit) throws ApiException {
// Create coupon API instance using API key
CouponApi couponApi = new CouponApi(Constants.API_KEY);
// TODO: consider using getCouponsByQuery() as it does not require all search parameters
String merchantCode = null;
String description = null;
String couponType = null;
String startDateBegin = null;
String startDateEnd = null;
String expirationDateBegin = null;
String expirationDateEnd = null;
Integer affiliateOid = null;
Boolean excludeExpired = null;
String sort = null;
String expand = null; // getCoupons doesn't have any expansions. full record is always returned.
CouponsResponse getResponse = couponApi.getCoupons(
merchantCode, description, couponType,
startDateBegin, startDateEnd,
expirationDateBegin, expirationDateEnd,
affiliateOid, excludeExpired,
limit, offset, sort, expand
);
return getResponse.getCoupons() != null ? getResponse.getCoupons() : new ArrayList<>();
}
}
import { DateTime } from 'luxon';
import { couponApi } from '../api.js'; // Added .js extension
/**
* Retrieves and processes coupons from UltraCart
*/
export class GetCoupons {
/**
* Executes the coupon retrieval process
* @returns Promise resolving to an array of retrieved coupons
*/
static async execute() {
console.log(`--- ${this.name} ---`);
try {
const coupons = [];
let iteration = 1;
let offset = 0;
const limit = 200;
let needMoreRecords = true;
while (needMoreRecords) {
console.log(`executing iteration #${iteration++}`);
const blockOfCoupons = await this.getCouponsChunk({ limit, offset });
if(blockOfCoupons !== undefined && blockOfCoupons !== null) {
blockOfCoupons.forEach(coupon => {
coupons.push(coupon);
});
offset += limit;
needMoreRecords = blockOfCoupons.length === limit;
} else {
needMoreRecords = false;
}
// Optional: rate limiting
// await new Promise(resolve => setTimeout(resolve, 1000));
}
// Display the coupons
coupons.forEach(coupon => {
console.log(coupon);
});
console.log(`Total coupons retrieved: ${coupons.length}`);
return coupons;
}
catch (ex) {
const error = ex;
console.error(`Error: ${error.message}`);
console.error(error.stack);
throw ex; // Re-throw to allow caller to handle the error
}
}
/**
* Returns a block of coupons
* @param params - Coupon retrieval parameters
* @returns Promise resolving to a list of Coupon objects
*/
static async getCouponsChunk(params = {}) {
// Default parameters
const defaultParams = {
merchantCode: undefined,
description: undefined,
couponType: undefined,
startDateBegin: undefined,
startDateEnd: undefined,
expirationDateBegin: undefined,
expirationDateEnd: undefined,
affiliateOid: undefined,
excludeExpired: false,
_limit: 200,
_offset: 0,
_sort: undefined,
_expand: undefined
};
// Merge default params with provided params
const mergedParams = { ...defaultParams, ...params };
const getResponse = await new Promise((resolve, reject) => {
couponApi.getCoupons(mergedParams, function (error, data, response) {
if (error) {
reject(error);
} else {
resolve(data, response);
}
});
});
if (getResponse.success && getResponse.success) {
return getResponse.coupons;
}
return [];
}
}
// Example of how to call the method
// async function example() {
// try {
// // Retrieve all coupons
// const coupons = await GetCoupons.execute();
// // Retrieve coupons with specific parameters
// const specificCoupons = await GetCoupons.getCouponsChunk({
// merchantCode: 'MERCHANT123',
// excludeExpired: true,
// limit: 100
// });
// } catch (error) {
// console.error('Failed to retrieve coupons', error);
// }
// }
<?php
// Create a Simple Key: https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/38688545/API+Simple+Key
// Error help: https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/39077885/Troubleshooting+API+Errors
// Additional Docs: https://www.ultracart.com/api/#introduction.html
// This is an old example. Please see getCouponsByQuery as they do essentially the same thing, but
// getCouponsByQuery is easier to use.
use ultracart\v2\api\CouponApi;
use ultracart\v2\ApiException;
use ultracart\v2\models\Coupon;
require_once '../vendor/autoload.php';
$coupon_api = ultracart\v2\api\CouponApi::usingApiKey(Constants::API_KEY);
?>
<?php
/**
* returns a block of customers
* @param CouponApi $coupon_api
* @param int $offset pagination variable
* @param int $limit pagination variable. max server will allow is 200
* @return array|Coupon[]
* @throws ApiException
*/
function get_coupons_chunk(CouponApi $coupon_api, int $offset = 0, int $limit = 200) {
// TODO: consider using getCouponsByQuery() as it does not require all search parameters
$merchant_code = null;
$description = null;
$coupon_type = null;
$start_date_begin = null;
$start_date_end = null;
$expiration_date_begin = null;
$expiration_date_end = null;
$affiliate_oid = null;
$exclude_expired = null;
$_limit = $limit;
$_offset = $offset;
$_sort = null;
$_expand = null; // getCoupons doesn't have any expansions. full record is always returned.
$get_response = $coupon_api->getCoupons($merchant_code, $description, $coupon_type, $start_date_begin, $start_date_end, $expiration_date_begin, $expiration_date_end, $affiliate_oid, $exclude_expired, $_limit, $_offset, $_sort, $_expand);
if($get_response->getSuccess()){
return $get_response->getCoupons();
}
return array();
}
?>
<html>
<body>
<?php
$coupons = array();
try {
$iteration = 1;
$offset = 0;
$limit = 200;
$need_more_records = true;
while($need_more_records){
echo "executing iteration #" . $iteration++ . "<br>";
$block_of_customers = get_coupons_chunk($coupon_api, $offset, $limit);
foreach($block_of_customers as $coupon){
$coupons[] = $coupon;
}
$offset += $limit;
$need_more_records = count($block_of_customers) == $limit;
// sleep(1); // I'm testing rate limiter headers. this should probably be uncommented. maybe.
}
} catch (ApiException $e) {
echo 'API Exception when calling CouponApi->getCoupons: ', $e->getMessage(), PHP_EOL;
echo print_r($e->getResponseBody()), PHP_EOL;
} catch (Exception $e) {
echo 'Exception when calling CouponApi->getCoupons: ', $e->getMessage(), PHP_EOL;
}
echo '<pre>';
var_dump($coupons);
echo '</pre>';
?>
</body>
</html>
# Create a Simple Key: https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/38688545/API+Simple+Key
# Error help: https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/39077885/Troubleshooting+API+Errors
# Additional Docs: https://www.ultracart.com/api/#introduction.html
# This is an old example. Please see get_coupons_by_query as they do essentially the same thing, but
# get_coupons_by_query is easier to use.
from ultracart.apis import CouponApi
from ultracart.exceptions import ApiException
from ultracart.models import Coupon
from typing import List
from samples import api_client
def get_coupons_chunk(coupon_api: CouponApi, offset: int = 0, limit: int = 200) -> List[Coupon]:
"""
Returns a block of customers
Args:
coupon_api: CouponApi instance
offset: pagination variable
limit: pagination variable. max server will allow is 200
Returns:
List of Coupon objects
Raises:
ApiException
"""
# TODO: consider using get_coupons_by_query() as it does not require all search parameters
merchant_code = None
description = None
coupon_type = None
start_date_begin = None
start_date_end = None
expiration_date_begin = None
expiration_date_end = None
affiliate_oid = None
exclude_expired = None
limit = limit
offset = offset
sort = None
expand = None # getCoupons doesn't have any expansions. full record is always returned.
get_response = coupon_api.get_coupons(merchant_code, description, coupon_type, start_date_begin, start_date_end,
expiration_date_begin, expiration_date_end, affiliate_oid, exclude_expired,
limit=limit, offset=offset, sort=sort, expand=expand)
if get_response.success:
return get_response.coupons
return []
def main():
coupon_api = CouponApi(api_client())
coupons = []
try:
iteration = 1
offset = 0
limit = 200
need_more_records = True
while need_more_records:
print(f"executing iteration #{iteration}")
iteration += 1
block_of_customers = get_coupons_chunk(coupon_api, offset, limit)
coupons.extend(block_of_customers)
offset += limit
need_more_records = len(block_of_customers) == limit
# time.sleep(1) # I'm testing rate limiter headers. this should probably be uncommented. maybe.
except ApiException as e:
print('API Exception when calling CouponApi->get_coupons:', e.message)
print(e.response_body)
except Exception as e:
print('Exception when calling CouponApi->get_coupons:', str(e))
print(coupons)
if __name__ == '__main__':
main()
require_relative '../constants'
require 'ultracart_api'
# Create a Simple Key: https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/38688545/API+Simple+Key
# Error help: https://ultracart.atlassian.net/wiki/spaces/ucdoc/pages/39077885/Troubleshooting+API+Errors
# Additional Docs: https://www.ultracart.com/api/#introduction.html
# This is an old example. Please see get_coupons_by_query as they do essentially the same thing, but
# get_coupons_by_query is easier to use.
# returns a block of customers
# @param coupon_api [UltracartClient::CouponApi]
# @param offset [Integer] pagination variable
# @param limit [Integer] pagination variable. max server will allow is 200
# @return [Array<UltracartClient::Coupon>]
def get_coupons_chunk(coupon_api, offset = 0, limit = 200)
# TODO: consider using get_coupons_by_query() as it does not require all search parameters
merchant_code = nil
description = nil
coupon_type = nil
start_date_begin = nil
start_date_end = nil
expiration_date_begin = nil
expiration_date_end = nil
affiliate_oid = nil
exclude_expired = nil
# getCoupons doesn't have any expansions. full record is always returned.
opts = {
merchant_code: merchant_code,
description: description,
coupon_type: coupon_type,
start_date_begin: start_date_begin,
start_date_end: start_date_end,
expiration_date_begin: expiration_date_begin,
expiration_date_end: expiration_date_end,
affiliate_oid: affiliate_oid,
exclude_expired: exclude_expired,
_limit: limit,
_offset: offset,
_sort: nil,
_expand: nil
}
get_response = coupon_api.get_coupons(opts)
return get_response.coupons if get_response.success
[]
end
begin
coupon_api = UltracartClient::CouponApi.new_using_api_key(Constants::API_KEY)
coupons = []
iteration = 1
offset = 0
limit = 200
need_more_records = true
while need_more_records
puts "executing iteration ##{iteration}"
iteration += 1
block_of_customers = get_coupons_chunk(coupon_api, offset, limit)
coupons.concat(block_of_customers)
offset += limit
need_more_records = block_of_customers.length == limit
# sleep(1) # I'm testing rate limiter headers. this should probably be uncommented. maybe.
end
puts coupons.inspect
rescue UltracartClient::ApiError => e
puts "API Exception when calling CouponApi->get_coupons: #{e.message}"
puts e.response_body.inspect
rescue StandardError => e
puts "Exception when calling CouponApi->get_coupons: #{e.message}"
end
import { DateTime } from 'luxon';
import {Coupon, GetCouponsRequest} from 'ultracart_rest_api_v2_typescript';
import { couponApi } from '../api'; // Assuming this is how the API is imported
/**
* Retrieves and processes coupons from UltraCart
*/
export class GetCoupons {
/**
* Executes the coupon retrieval process
* @returns Promise resolving to an array of retrieved coupons
*/
public static async execute(): Promise<Coupon[]> {
console.log(`--- ${this.name} ---`);
try {
const coupons: Coupon[] = [];
let iteration = 1;
let offset = 0;
const limit = 200;
let needMoreRecords = true;
while (needMoreRecords) {
console.log(`executing iteration #${iteration++}`);
const blockOfCoupons = await this.getCouponsChunk({ limit, offset });
if(blockOfCoupons !== undefined && blockOfCoupons !== null) {
blockOfCoupons.forEach(coupon => {
coupons.push(coupon);
});
offset += limit;
needMoreRecords = blockOfCoupons.length === limit;
} else {
needMoreRecords = false;
}
// Optional: rate limiting
// await new Promise(resolve => setTimeout(resolve, 1000));
}
// Display the coupons
coupons.forEach(coupon => {
console.log(coupon);
});
console.log(`Total coupons retrieved: ${coupons.length}`);
return coupons;
}
catch (ex: unknown) {
const error = ex as Error;
console.error(`Error: ${error.message}`);
console.error(error.stack);
throw ex; // Re-throw to allow caller to handle the error
}
}
/**
* Returns a block of coupons
* @param params - Coupon retrieval parameters
* @returns Promise resolving to a list of Coupon objects
*/
public static async getCouponsChunk(params: GetCouponsRequest = {}): Promise<Coupon[]|undefined> {
// Default parameters
const defaultParams: GetCouponsRequest = {
merchantCode: undefined,
description: undefined,
couponType: undefined,
startDateBegin: undefined,
startDateEnd: undefined,
expirationDateBegin: undefined,
expirationDateEnd: undefined,
affiliateOid: undefined,
excludeExpired: false,
limit: 200,
offset: 0,
sort: undefined,
expand: undefined
};
// Merge default params with provided params
const mergedParams = { ...defaultParams, ...params };
const getResponse = await couponApi.getCoupons(mergedParams);
if (getResponse.success && getResponse.success) {
return getResponse.coupons;
}
return [];
}
}
// Example of how to call the method
// async function example() {
// try {
// // Retrieve all coupons
// const coupons = await GetCoupons.execute();
// // Retrieve coupons with specific parameters
// const specificCoupons = await GetCoupons.getCouponsChunk({
// merchantCode: 'MERCHANT123',
// excludeExpired: true,
// limit: 100
// });
// } catch (error) {
// console.error('Failed to retrieve coupons', error);
// }
// }
Insert a coupon on the UltraCart account.
SDK Function Name: insertCoupon
Parameter | Description | Location | Data Type | Required |
---|---|---|---|---|
coupon | Coupon to insert | body | Coupon | required |
_expand | The object expansion to perform on the result. See documentation for examples | query | string | optional |
using System;
using System.Reflection;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;
namespace SdkSample.coupon
{
public class InsertCoupon
{
public static void Execute()
{
Console.WriteLine("--- " + MethodBase.GetCurrentMethod()?.DeclaringType?.Name + " ---");
try
{
// Create coupon API instance using API key
CouponApi couponApi = new CouponApi(Constants.ApiKey);
// Create a new coupon
Coupon coupon = new Coupon();
coupon.MerchantCode = "InsertCouponSample";
coupon.Description ="One penny off subtotal";
// Each coupon must have a 'type' defined by creating a child object directly beneath the main Coupon object.
// This is complex and there are a LOT of coupon types. See the backend (secure.ultracart.com) coupon screens
// to get an idea of what functionality each coupon possesses. If you're not sure, contact UltraCart support.
coupon.AmountOffSubtotal = new CouponAmountOffSubtotal();
coupon.AmountOffSubtotal.DiscountAmount = 0.01m;
// Here are the different coupon types, but beware that new coupons are added frequently.
//CouponAmountOffItems
//CouponAmountOffShipping
//CouponAmountOffShippingWithItemsPurchase
//CouponAmountOffSubtotal
//CouponAmountOffSubtotalAndShipping
//CouponAmountOffSubtotalFreeShippingWithPurchase
//CouponAmountOffSubtotalWithBlockPurchase
//CouponAmountOffSubtotalWithItemsPurchase
//CouponAmountOffSubtotalWithPurchase
//CouponAmountShippingWithSubtotal
//CouponDiscountItems
//CouponDiscountItemWithItemPurchase
//CouponFreeItemAndShippingWithSubtotal
//CouponFreeItemsWithItemPurchase
//CouponFreeItemsWithMixMatchPurchase
//CouponFreeItemWithItemPurchase
//CouponFreeItemWithItemPurchaseAndFreeShipping
//CouponFreeItemWithSubtotal
//CouponFreeShipping
//CouponFreeShippingSpecificItems
//CouponFreeShippingWithItemsPurchase
//CouponFreeShippingWithSubtotal
//CouponMoreLoyaltyCashback
//CouponMoreLoyaltyPoints
//CouponMultipleAmountsOffItems
//CouponNoDiscount
//CouponPercentMoreLoyaltyCashback
//CouponPercentMoreLoyaltyPoints
//CouponPercentOffItems
//CouponPercentOffItemsAndFreeShipping
//CouponPercentOffItemsWithItemsPurchase
//CouponPercentOffItemWithItemsQuantityPurchase
//CouponPercentOffMsrpItems
//CouponPercentOffRetailPriceItems
//CouponPercentOffShipping
//CouponPercentOffSubtotal
//CouponPercentOffSubtotalAndFreeShipping
//CouponPercentOffSubtotalLimit
//CouponPercentOffSubtotalWithItemsPurchase
//CouponPercentOffSubtotalWithSubtotal
//CouponTieredAmountOffItems
//CouponTieredAmountOffSubtotal
//CouponTieredPercentOffItems
//CouponTieredPercentOffShipping
//CouponTieredPercentOffSubtotal
//CouponTieredPercentOffSubtotalBasedOnMSRP
//CouponTierItemDiscount
//CouponTierPercent
//CouponTierQuantityAmount
//CouponTierQuantityPercent
string expand = null; // coupons do not have expansions
var apiResponse = couponApi.InsertCoupon(coupon, expand);
coupon = apiResponse.Coupon;
Console.WriteLine("Created the following temporary coupon:");
Console.WriteLine($"Coupon OID: {coupon.CouponOid}");
Console.WriteLine($"Coupon Type: {coupon.CouponType}");
Console.WriteLine($"Coupon Description: {coupon.Description}");
Console.WriteLine("Deleting newly created coupon to clean up.");
couponApi.DeleteCoupon(coupon.CouponOid);
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
Console.WriteLine(ex.StackTrace);
}
}
}
}
package coupon;
import com.ultracart.admin.v2.CouponApi;
import com.ultracart.admin.v2.models.Coupon;
import com.ultracart.admin.v2.models.CouponAmountOffSubtotal;
import com.ultracart.admin.v2.models.CouponResponse;
import com.ultracart.admin.v2.util.ApiException;
import common.Constants;
import java.math.BigDecimal;
public class InsertCoupon {
public static void execute() {
try {
// Create coupon API instance using API key
CouponApi couponApi = new CouponApi(Constants.API_KEY);
// Create a new coupon
Coupon coupon = new Coupon();
coupon.setMerchantCode("InsertCouponSample");
coupon.setDescription("One penny off subtotal");
// Each coupon must have a 'type' defined by creating a child object directly beneath the main Coupon object.
// This is complex and there are a LOT of coupon types. See the backend (secure.ultracart.com) coupon screens
// to get an idea of what functionality each coupon possesses. If you're not sure, contact UltraCart support.
coupon.setAmountOffSubtotal(new CouponAmountOffSubtotal()); // one penny discount.
coupon.getAmountOffSubtotal().setDiscountAmount(BigDecimal.valueOf(.01));
coupon.getAmountOffSubtotal().setCurrencyCode("USD");
// Commented out list of coupon types from original code...
String expand = null; // coupons do not have expansions
CouponResponse apiResponse = couponApi.insertCoupon(coupon, expand);
coupon = apiResponse.getCoupon();
System.out.println("Created the following temporary coupon:");
System.out.println("Coupon OID: " + coupon.getCouponOid());
System.out.println("Coupon Type: " + coupon.getCouponType());
System.out.println("Coupon Description: " + coupon.getDescription());
System.out.println("Deleting newly created coupon to clean up.");
couponApi.deleteCoupon(coupon.getCouponOid());
}
catch (ApiException ex) {
System.out.println("Error: " + ex.getMessage());
ex.printStackTrace();
}
}
}
// Import API and UltraCart types
import { couponApi } from '../api.js';
// Namespace-like structure using a class
export class InsertCoupon {
static async execute() {
console.log(`--- InsertCoupon ---`);
try {
// Create a new coupon
const coupon = {
merchant_code: "InsertCouponSample",
description: "One penny off subtotal",
// Each coupon must have a 'type' defined by creating a child object directly beneath the main Coupon object.
// This is complex and there are a LOT of coupon types. See the backend (secure.ultracart.com) coupon screens
// to get an idea of what functionality each coupon possesses. If you're not sure, contact UltraCart support.
amount_off_subtotal: {
discount_amount: 0.01, // Decimal becomes number in TypeScript
},
};
// Here are the different coupon types, but beware that new coupons are added frequently.
// CouponAmountOffItems
// CouponAmountOffShipping
// CouponAmountOffShippingWithItemsPurchase
// CouponAmountOffSubtotal
// CouponAmountOffSubtotalAndShipping
// CouponAmountOffSubtotalFreeShippingWithPurchase
// CouponAmountOffSubtotalWithBlockPurchase
// CouponAmountOffSubtotalWithItemsPurchase
// CouponAmountOffSubtotalWithPurchase
// CouponAmountShippingWithSubtotal
// CouponDiscountItems
// CouponDiscountItemWithItemPurchase
// CouponFreeItemAndShippingWithSubtotal
// CouponFreeItemsWithItemPurchase
// CouponFreeItemsWithMixMatchPurchase
// CouponFreeItemWithItemPurchase
// CouponFreeItemWithItemPurchaseAndFreeShipping
// CouponFreeItemWithSubtotal
// CouponFreeShipping
// CouponFreeShippingSpecificItems
// CouponFreeShippingWithItemsPurchase
// CouponFreeShippingWithSubtotal
// CouponMoreLoyaltyCashback
// CouponMoreLoyaltyPoints
// CouponMultipleAmountsOffItems
// CouponNoDiscount
// CouponPercentMoreLoyaltyCashback
// CouponPercentMoreLoyaltyPoints
// CouponPercentOffItems
// CouponPercentOffItemsAndFreeShipping
// CouponPercentOffItemsWithItemsPurchase
// CouponPercentOffItemWithItemsQuantityPurchase
// CouponPercentOffMsrpItems
// CouponPercentOffRetailPriceItems
// CouponPercentOffShipping
// CouponPercentOffSubtotal
// CouponPercentOffSubtotalAndFreeShipping
// CouponPercentOffSubtotalLimit
// CouponPercentOffSubtotalWithItemsPurchase
// CouponPercentOffSubtotalWithSubtotal
// CouponTieredAmountOffItems
// CouponTieredAmountOffSubtotal
// CouponTieredPercentOffItems
// CouponTieredPercentOffShipping
// CouponTieredPercentOffSubtotal
// CouponTieredPercentOffSubtotalBasedOnMSRP
// CouponTierItemDiscount
// CouponTierPercent
// CouponTierQuantityAmount
// CouponTierQuantityPercent
const expand = undefined; // coupons do not have expansions
const apiResponse = await new Promise((resolve, reject) => {
couponApi.insertCoupon(coupon, {_expand: expand}, function (error, data, response) {
if (error) {
reject(error);
} else {
resolve(data, response);
}
});
});
const createdCoupon = apiResponse.coupon;
console.log("Created the following temporary coupon:");
console.log(`Coupon OID: ${createdCoupon?.coupon_oid}`);
console.log(`Coupon Type: ${createdCoupon?.coupon_type}`);
console.log(`Coupon Description: ${createdCoupon?.description}`);
console.log("Deleting newly created coupon to clean up.");
if (createdCoupon?.coupon_oid) {
await new Promise((resolve, reject) => {
couponApi.deleteCoupon(createdCoupon.coupon_oid, function (error, data, response) {
if (error) {
reject(error);
} else {
resolve(data, response);
}
});
});
}
} catch (ex) {
console.log(`Error: ${ex.message}`);
console.log(ex.stack);
}
}
}
<?php
use ultracart\v2\api\CouponApi;
use ultracart\v2\models\Coupon;
use ultracart\v2\models\CouponAmountOffSubtotal;
require_once '../vendor/autoload.php';
$coupon_api = CouponApi::usingApiKey(Constants::API_KEY);
$coupon = new Coupon();
$coupon->setMerchantCode('11OFF');
$coupon->setDescription("Eleven dollars off subtotal");
// each coupon must have a 'type' defined by creating a child object directly beneath the main Coupon object.
// this is complex and there are a LOT of coupon types. See the backend (secure.ultracart.com) coupon screens
// to get an idea of what functionality each coupon possesses. If you're not sure, contact UltraCart support.
$coupon->setAmountOffSubtotal(new CouponAmountOffSubtotal());
$coupon->getAmountOffSubtotal()->setDiscountAmount(11);
// Here are the different coupon types, but beware that new coupons are added frequently.
//CouponAmountOffItems
//CouponAmountOffShipping
//CouponAmountOffShippingWithItemsPurchase
//CouponAmountOffSubtotal
//CouponAmountOffSubtotalAndShipping
//CouponAmountOffSubtotalFreeShippingWithPurchase
//CouponAmountOffSubtotalWithBlockPurchase
//CouponAmountOffSubtotalWithItemsPurchase
//CouponAmountOffSubtotalWithPurchase
//CouponAmountShippingWithSubtotal
//CouponDiscountItems
//CouponDiscountItemWithItemPurchase
//CouponFreeItemAndShippingWithSubtotal
//CouponFreeItemsWithItemPurchase
//CouponFreeItemsWithMixMatchPurchase
//CouponFreeItemWithItemPurchase
//CouponFreeItemWithItemPurchaseAndFreeShipping
//CouponFreeItemWithSubtotal
//CouponFreeShipping
//CouponFreeShippingSpecificItems
//CouponFreeShippingWithItemsPurchase
//CouponFreeShippingWithSubtotal
//CouponMoreLoyaltyCashback
//CouponMoreLoyaltyPoints
//CouponMultipleAmountsOffItems
//CouponNoDiscount
//CouponPercentMoreLoyaltyCashback
//CouponPercentMoreLoyaltyPoints
//CouponPercentOffItems
//CouponPercentOffItemsAndFreeShipping
//CouponPercentOffItemsWithItemsPurchase
//CouponPercentOffItemWithItemsQuantityPurchase
//CouponPercentOffMsrpItems
//CouponPercentOffRetailPriceItems
//CouponPercentOffShipping
//CouponPercentOffSubtotal
//CouponPercentOffSubtotalAndFreeShipping
//CouponPercentOffSubtotalLimit
//CouponPercentOffSubtotalWithItemsPurchase
//CouponPercentOffSubtotalWithSubtotal
//CouponTieredAmountOffItems
//CouponTieredAmountOffSubtotal
//CouponTieredPercentOffItems
//CouponTieredPercentOffShipping
//CouponTieredPercentOffSubtotal
//CouponTieredPercentOffSubtotalBasedOnMSRP
//CouponTierItemDiscount
//CouponTierPercent
//CouponTierQuantityAmount
//CouponTierQuantityPercent
$_expand = null; // coupons do not have expansions
$api_response = $coupon_api->insertCoupon($coupon, $_expand);
echo '<html lang="en"><body><pre>';
var_dump($api_response);
echo '</pre></body></html>';
from ultracart.apis import CouponApi
from ultracart.models import Coupon, CouponAmountOffSubtotal
from samples import api_client
# Initialize the API
coupon_api = CouponApi(api_client())
# Create the main coupon object
coupon = Coupon()
coupon.merchant_code = '11OFF'
coupon.description = "Eleven dollars off subtotal"
# Each coupon must have a 'type' defined by creating a child object directly beneath the main Coupon object.
# This is complex and there are a LOT of coupon types. See the backend (secure.ultracart.com) coupon screens
# to get an idea of what functionality each coupon possesses. If you're not sure, contact UltraCart support.
coupon.amount_off_subtotal = CouponAmountOffSubtotal()
coupon.amount_off_subtotal.discount_amount = 11
# Here are the different coupon types, but beware that new coupons are added frequently.
# CouponAmountOffItems
# CouponAmountOffShipping
# CouponAmountOffShippingWithItemsPurchase
# CouponAmountOffSubtotal
# CouponAmountOffSubtotalAndShipping
# CouponAmountOffSubtotalFreeShippingWithPurchase
# CouponAmountOffSubtotalWithBlockPurchase
# CouponAmountOffSubtotalWithItemsPurchase
# CouponAmountOffSubtotalWithPurchase
# CouponAmountShippingWithSubtotal
# CouponDiscountItems
# CouponDiscountItemWithItemPurchase
# CouponFreeItemAndShippingWithSubtotal
# CouponFreeItemsWithItemPurchase
# CouponFreeItemsWithMixMatchPurchase
# CouponFreeItemWithItemPurchase
# CouponFreeItemWithItemPurchaseAndFreeShipping
# CouponFreeItemWithSubtotal
# CouponFreeShipping
# CouponFreeShippingSpecificItems
# CouponFreeShippingWithItemsPurchase
# CouponFreeShippingWithSubtotal
# CouponMoreLoyaltyCashback
# CouponMoreLoyaltyPoints
# CouponMultipleAmountsOffItems
# CouponNoDiscount
# CouponPercentMoreLoyaltyCashback
# CouponPercentMoreLoyaltyPoints
# CouponPercentOffItems
# CouponPercentOffItemsAndFreeShipping
# CouponPercentOffItemsWithItemsPurchase
# CouponPercentOffItemWithItemsQuantityPurchase
# CouponPercentOffMsrpItems
# CouponPercentOffRetailPriceItems
# CouponPercentOffShipping
# CouponPercentOffSubtotal
# CouponPercentOffSubtotalAndFreeShipping
# CouponPercentOffSubtotalLimit
# CouponPercentOffSubtotalWithItemsPurchase
# CouponPercentOffSubtotalWithSubtotal
# CouponTieredAmountOffItems
# CouponTieredAmountOffSubtotal
# CouponTieredPercentOffItems
# CouponTieredPercentOffShipping
# CouponTieredPercentOffSubtotal
# CouponTieredPercentOffSubtotalBasedOnMSRP
# CouponTierItemDiscount
# CouponTierPercent
# CouponTierQuantityAmount
# CouponTierQuantityPercent
expand = None # coupons do not have expansions
api_response = coupon_api.insert_coupon(coupon, expand=expand)
print(api_response)
require 'ultracart_api'
require_relative '../constants'
# Initialize the coupon API
coupon_api = UltracartClient::CouponApi.new_using_api_key(Constants::API_KEY)
# Create a new coupon
coupon = UltracartClient::Coupon.new
coupon.merchant_code = '11OFF'
coupon.description = 'Eleven dollars off subtotal'
# each coupon must have a 'type' defined by creating a child object directly beneath the main Coupon object.
# this is complex and there are a LOT of coupon types. See the backend (secure.ultracart.com) coupon screens
# to get an idea of what functionality each coupon possesses. If you're not sure, contact UltraCart support.
coupon.amount_off_subtotal = UltracartClient::CouponAmountOffSubtotal.new
coupon.amount_off_subtotal.discount_amount = 11
# Here are the different coupon types, but beware that new coupons are added frequently.
#CouponAmountOffItems
#CouponAmountOffShipping
#CouponAmountOffShippingWithItemsPurchase
#CouponAmountOffSubtotal
#CouponAmountOffSubtotalAndShipping
#CouponAmountOffSubtotalFreeShippingWithPurchase
#CouponAmountOffSubtotalWithBlockPurchase
#CouponAmountOffSubtotalWithItemsPurchase
#CouponAmountOffSubtotalWithPurchase
#CouponAmountShippingWithSubtotal
#CouponDiscountItems
#CouponDiscountItemWithItemPurchase
#CouponFreeItemAndShippingWithSubtotal
#CouponFreeItemsWithItemPurchase
#CouponFreeItemsWithMixMatchPurchase
#CouponFreeItemWithItemPurchase
#CouponFreeItemWithItemPurchaseAndFreeShipping
#CouponFreeItemWithSubtotal
#CouponFreeShipping
#CouponFreeShippingSpecificItems
#CouponFreeShippingWithItemsPurchase
#CouponFreeShippingWithSubtotal
#CouponMoreLoyaltyCashback
#CouponMoreLoyaltyPoints
#CouponMultipleAmountsOffItems
#CouponNoDiscount
#CouponPercentMoreLoyaltyCashback
#CouponPercentMoreLoyaltyPoints
#CouponPercentOffItems
#CouponPercentOffItemsAndFreeShipping
#CouponPercentOffItemsWithItemsPurchase
#CouponPercentOffItemWithItemsQuantityPurchase
#CouponPercentOffMsrpItems
#CouponPercentOffRetailPriceItems
#CouponPercentOffShipping
#CouponPercentOffSubtotal
#CouponPercentOffSubtotalAndFreeShipping
#CouponPercentOffSubtotalLimit
#CouponPercentOffSubtotalWithItemsPurchase
#CouponPercentOffSubtotalWithSubtotal
#CouponTieredAmountOffItems
#CouponTieredAmountOffSubtotal
#CouponTieredPercentOffItems
#CouponTieredPercentOffShipping
#CouponTieredPercentOffSubtotal
#CouponTieredPercentOffSubtotalBasedOnMSRP
#CouponTierItemDiscount
#CouponTierPercent
#CouponTierQuantityAmount
#CouponTierQuantityPercent
# coupons do not have expansions
api_response = coupon_api.insert_coupon(coupon, {_expand: nil})
puts api_response
// Import API and UltraCart types
import { couponApi } from '../api';
import { Coupon, CouponAmountOffSubtotal, CouponResponse } from 'ultracart_rest_api_v2_typescript';
// Namespace-like structure using a class
export class InsertCoupon {
public static async execute(): Promise<void> {
console.log(`--- InsertCoupon ---`);
try {
// Create a new coupon
const coupon: Coupon = {
merchant_code: "InsertCouponSample",
description: "One penny off subtotal",
// Each coupon must have a 'type' defined by creating a child object directly beneath the main Coupon object.
// This is complex and there are a LOT of coupon types. See the backend (secure.ultracart.com) coupon screens
// to get an idea of what functionality each coupon possesses. If you're not sure, contact UltraCart support.
amount_off_subtotal: {
discount_amount: 0.01, // Decimal becomes number in TypeScript
} as CouponAmountOffSubtotal,
};
// Here are the different coupon types, but beware that new coupons are added frequently.
// CouponAmountOffItems
// CouponAmountOffShipping
// CouponAmountOffShippingWithItemsPurchase
// CouponAmountOffSubtotal
// CouponAmountOffSubtotalAndShipping
// CouponAmountOffSubtotalFreeShippingWithPurchase
// CouponAmountOffSubtotalWithBlockPurchase
// CouponAmountOffSubtotalWithItemsPurchase
// CouponAmountOffSubtotalWithPurchase
// CouponAmountShippingWithSubtotal
// CouponDiscountItems
// CouponDiscountItemWithItemPurchase
// CouponFreeItemAndShippingWithSubtotal
// CouponFreeItemsWithItemPurchase
// CouponFreeItemsWithMixMatchPurchase
// CouponFreeItemWithItemPurchase
// CouponFreeItemWithItemPurchaseAndFreeShipping
// CouponFreeItemWithSubtotal
// CouponFreeShipping
// CouponFreeShippingSpecificItems
// CouponFreeShippingWithItemsPurchase
// CouponFreeShippingWithSubtotal
// CouponMoreLoyaltyCashback
// CouponMoreLoyaltyPoints
// CouponMultipleAmountsOffItems
// CouponNoDiscount
// CouponPercentMoreLoyaltyCashback
// CouponPercentMoreLoyaltyPoints
// CouponPercentOffItems
// CouponPercentOffItemsAndFreeShipping
// CouponPercentOffItemsWithItemsPurchase
// CouponPercentOffItemWithItemsQuantityPurchase
// CouponPercentOffMsrpItems
// CouponPercentOffRetailPriceItems
// CouponPercentOffShipping
// CouponPercentOffSubtotal
// CouponPercentOffSubtotalAndFreeShipping
// CouponPercentOffSubtotalLimit
// CouponPercentOffSubtotalWithItemsPurchase
// CouponPercentOffSubtotalWithSubtotal
// CouponTieredAmountOffItems
// CouponTieredAmountOffSubtotal
// CouponTieredPercentOffItems
// CouponTieredPercentOffShipping
// CouponTieredPercentOffSubtotal
// CouponTieredPercentOffSubtotalBasedOnMSRP
// CouponTierItemDiscount
// CouponTierPercent
// CouponTierQuantityAmount
// CouponTierQuantityPercent
const expand: string | undefined = undefined; // coupons do not have expansions
// UltraCart API call with parameters as an anonymous interface
const apiResponse = await couponApi.insertCoupon({
coupon: coupon,
expand: expand,
});
const createdCoupon = apiResponse.coupon;
console.log("Created the following temporary coupon:");
console.log(`Coupon OID: ${createdCoupon?.coupon_oid}`);
console.log(`Coupon Type: ${createdCoupon?.coupon_type}`);
console.log(`Coupon Description: ${createdCoupon?.description}`);
console.log("Deleting newly created coupon to clean up.");
if (createdCoupon?.coupon_oid) {
await couponApi.deleteCoupon({couponOid: createdCoupon.coupon_oid});
}
} catch (ex) {
console.log(`Error: ${(ex as Error).message}`);
console.log((ex as Error).stack);
}
}
}
Insert multiple coupon on the UltraCart account.
SDK Function Name: insertCoupons
Parameter | Description | Location | Data Type | Required |
---|---|---|---|---|
coupons_request | Coupons to insert (maximum 50) | body | CouponsRequest | required |
_expand | The object expansion to perform on the result. See documentation for examples | query | string | optional |
_placeholders | Whether or not placeholder values should be returned in the result. Useful for UIs that consume this REST API. | query | boolean | optional |
using System;
using System.Collections.Generic;
using System.Reflection;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;
namespace SdkSample.coupon
{
public class InsertCoupons
{
public static void Execute()
{
Console.WriteLine("--- " + MethodBase.GetCurrentMethod()?.DeclaringType?.Name + " ---");
try
{
// Create coupon API instance using API key
CouponApi couponApi = new CouponApi(Constants.ApiKey);
Coupon coupon1 = new Coupon();
coupon1.MerchantCode = "PennyOff";
coupon1.Description ="Test Coupon for InsertCoupons sample";
coupon1.AmountOffSubtotal = new CouponAmountOffSubtotal(); // see InsertCoupon for examples of types
coupon1.AmountOffSubtotal.DiscountAmount = 0.01m;
Coupon coupon2 = new Coupon();
coupon2.MerchantCode = "TwoPenniesOff";
coupon2.Description ="Test Coupon for InsertCoupons sample";
coupon2.AmountOffSubtotal = new CouponAmountOffSubtotal(); // see InsertCoupon for examples of types
coupon2.AmountOffSubtotal.DiscountAmount = 0.02m;
CouponsRequest couponsRequest = new CouponsRequest();
couponsRequest.Coupons = new List<Coupon> { coupon1, coupon2 };
var apiResponse = couponApi.InsertCoupons(couponsRequest);
Console.WriteLine(apiResponse);
foreach (Coupon coupon in apiResponse.Coupons)
{
Console.WriteLine($"Deleting newly created coupon (Coupon OID {coupon.CouponOid}) to clean up.");
couponApi.DeleteCoupon(coupon.CouponOid);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
Console.WriteLine(ex.StackTrace);
}
}
}
}
package coupon;
import com.ultracart.admin.v2.CouponApi;
import com.ultracart.admin.v2.models.Coupon;
import com.ultracart.admin.v2.models.CouponAmountOffSubtotal;
import com.ultracart.admin.v2.models.CouponsRequest;
import com.ultracart.admin.v2.models.CouponsResponse;
import com.ultracart.admin.v2.util.ApiException;
import common.Constants;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
public class InsertCoupons {
public static void Execute() {
System.out.println("--- " + InsertCoupons.class.getSimpleName() + " ---");
try {
// Create coupon API instance using API key
CouponApi couponApi = new CouponApi(Constants.API_KEY);
Coupon coupon1 = new Coupon();
coupon1.setMerchantCode("PennyOff");
coupon1.setDescription("Test Coupon for InsertCoupons sample");
coupon1.setAmountOffSubtotal(new CouponAmountOffSubtotal()); // see InsertCoupon for examples of types
coupon1.getAmountOffSubtotal().setDiscountAmount(new BigDecimal("0.01"));
Coupon coupon2 = new Coupon();
coupon2.setMerchantCode("TwoPenniesOff");
coupon2.setDescription("Test Coupon for InsertCoupons sample");
coupon2.setAmountOffSubtotal(new CouponAmountOffSubtotal()); // see InsertCoupon for examples of types
coupon2.getAmountOffSubtotal().setDiscountAmount(new BigDecimal("0.02"));
CouponsRequest couponsRequest = new CouponsRequest();
List<Coupon> couponList = new ArrayList<>();
couponList.add(coupon1);
couponList.add(coupon2);
couponsRequest.setCoupons(couponList);
CouponsResponse apiResponse = couponApi.insertCoupons(couponsRequest, null, false);
System.out.println(apiResponse);
for (Coupon coupon : apiResponse.getCoupons()) {
System.out.println("Deleting newly created coupon (Coupon OID " + coupon.getCouponOid() + ") to clean up.");
couponApi.deleteCoupon(coupon.getCouponOid());
}
}
catch (ApiException ex) {
System.out.println("Error: " + ex.getMessage());
ex.printStackTrace();
}
}
}
// Import API and UltraCart types
import { couponApi } from '../api.js';
// Namespace-like structure using a class
export class InsertCoupons {
static async execute() {
console.log(`--- InsertCoupons ---`);
try {
// Create coupon objects
const coupon1 = {
merchant_code: "PennyOff",
description: "Test Coupon for InsertCoupons sample",
amount_off_subtotal: {
discount_amount: 0.01, // Decimal becomes number in TypeScript
}, // See InsertCoupon for examples of types
};
const coupon2 = {
merchant_code: "TwoPenniesOff",
description: "Test Coupon for InsertCoupons sample",
amount_off_subtotal: {
discount_amount: 0.02, // Decimal becomes number in TypeScript
}, // See InsertCoupon for examples of types
};
// Create CouponsRequest object
const couponsRequest = {
coupons: [coupon1, coupon2],
};
const apiResponse = await new Promise((resolve, reject) => {
couponApi.insertCoupons(couponsRequest, function (error, data, response) {
if (error) {
reject(error);
} else {
resolve(data, response);
}
});
});
console.log(apiResponse);
// Clean up: delete newly created coupons
if (apiResponse.coupons) {
for (const coupon of apiResponse.coupons) {
console.log(`Deleting newly created coupon (Coupon OID ${coupon.coupon_oid}) to clean up.`);
if (coupon.coupon_oid) {
await new Promise((resolve, reject) => {
couponApi.deleteCoupon(coupon.coupon_oid, function (error, data, response) {
if (error) {
reject(error);
} else {
resolve(data, response);
}
});
});
}
}
}
} catch (ex) {
console.log(`Error: ${ex.message}`);
console.log(ex.stack);
}
}
}
// Example usage (optional, remove if not needed)
// InsertCoupons.execute().catch(console.error);
<?php
/*
Similar to insertCoupon except this method takes a request object containing up to 50 coupons. Please see
insertCoupon for a detailed example on creating a coupon. It is not repeated here.
*/
use ultracart\v2\api\CouponApi;
use ultracart\v2\models\Coupon;
use ultracart\v2\models\CouponsRequest;
require_once '../vendor/autoload.php';
$coupon_api = CouponApi::usingApiKey(Constants::API_KEY);
$couponsRequest = new CouponsRequest();
$coupons = [];
// TODO: add Coupons() to this array (see insertCoupon sample for help)
$couponsRequest->setCoupons($coupons);
$_expand = null; // coupons do not have expansions
$_placeholders = null; // coupons do not have placeholders.
$api_response = $coupon_api->insertCoupons($couponsRequest, $_expand, $_placeholders);
echo '<html lang="en"><body><pre>';
var_dump($api_response);
echo '</pre></body></html>';
from ultracart.apis import CouponApi
from ultracart.models import CouponsRequest
from samples import api_client
"""
Similar to insert_coupon except this method takes a request object containing up to 50 coupons.
Please see insert_coupon for a detailed example on creating a coupon. It is not repeated here.
"""
# Initialize the API
coupon_api = CouponApi(api_client())
# Create the request object
coupons_request = CouponsRequest()
coupons = []
# TODO: add Coupon() objects to this list (see insert_coupon sample for help)
coupons_request.coupons = coupons
expand = None # coupons do not have expansions
placeholders = None # coupons do not have placeholders
api_response = coupon_api.insert_coupons(coupons_request, expand=expand, placeholders=placeholders)
print(api_response)
require 'ultracart_api'
require_relative '../constants'
# Similar to insertCoupon except this method takes a request object containing up to 50 coupons. Please see
# insertCoupon for a detailed example on creating a coupon. It is not repeated here.
# Initialize the coupon API
coupon_api = UltracartClient::CouponApi.new_using_api_key(Constants::API_KEY)
coupons_request = UltracartClient::CouponsRequest.new
coupons = []
# TODO: add Coupons() to this array (see insertCoupon sample for help)
coupons_request.coupons = coupons
# coupons do not have expansions or placeholders
api_response = coupon_api.insert_coupons(coupons_request, {_expand: nil, _placeholders: nil})
puts api_response
// Import API and UltraCart types
import { couponApi } from '../api';
import { Coupon, CouponAmountOffSubtotal, CouponsRequest } from 'ultracart_rest_api_v2_typescript';
// Namespace-like structure using a class
export class InsertCoupons {
public static async execute(): Promise<void> {
console.log(`--- InsertCoupons ---`);
try {
// Create coupon objects
const coupon1: Coupon = {
merchant_code: "PennyOff",
description: "Test Coupon for InsertCoupons sample",
amount_off_subtotal: {
discount_amount: 0.01, // Decimal becomes number in TypeScript
} as CouponAmountOffSubtotal, // See InsertCoupon for examples of types
};
const coupon2: Coupon = {
merchant_code: "TwoPenniesOff",
description: "Test Coupon for InsertCoupons sample",
amount_off_subtotal: {
discount_amount: 0.02, // Decimal becomes number in TypeScript
} as CouponAmountOffSubtotal, // See InsertCoupon for examples of types
};
// Create CouponsRequest object
const couponsRequest: CouponsRequest = {
coupons: [coupon1, coupon2],
};
// UltraCart API call with parameters as an anonymous interface
const apiResponse = await couponApi.insertCoupons({
couponsRequest: couponsRequest,
});
console.log(apiResponse);
// Clean up: delete newly created coupons
if (apiResponse.coupons) {
for (const coupon of apiResponse.coupons) {
console.log(`Deleting newly created coupon (Coupon OID ${coupon.coupon_oid}) to clean up.`);
if (coupon.coupon_oid) {
await couponApi.deleteCoupon({couponOid: coupon.coupon_oid});
}
}
}
} catch (ex) {
console.log(`Error: ${(ex as Error).message}`);
console.log((ex as Error).stack);
}
}
}
// Example usage (optional, remove if not needed)
InsertCoupons.execute().catch(console.error);
Update multiple coupon on the UltraCart account.
SDK Function Name: updateCoupons
Parameter | Description | Location | Data Type | Required |
---|---|---|---|---|
coupons_request | Coupons to update (synchronous maximum 50 / asynchronous maximum 100) | body | CouponsRequest | required |
_expand | The object expansion to perform on the result. See documentation for examples | query | string | optional |
_placeholders | Whether or not placeholder values should be returned in the result. Useful for UIs that consume this REST API. | query | boolean | optional |
_async | True if the operation should be run async. No result returned | query | boolean | optional |
using System;
using System.Collections.Generic;
using System.Reflection;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;
namespace SdkSample.coupon
{
public class UpdateCoupons
{
public static void Execute()
{
Console.WriteLine("--- " + MethodBase.GetCurrentMethod()?.DeclaringType?.Name + " ---");
try
{
// Create coupon API instance using API key
CouponApi couponApi = new CouponApi(Constants.ApiKey);
String merchantCode = Guid.NewGuid().ToString("N").Substring(0, 8);
// Now create the coupon and ensure it exists.
Coupon coupon = new Coupon();
coupon.MerchantCode = merchantCode;
coupon.Description = "Test coupon for GetCoupon";
coupon.AmountOffSubtotal = new CouponAmountOffSubtotal("USD", 0.01m); // one penny discount.
CouponResponse couponResponse = couponApi.InsertCoupon(coupon);
coupon = couponResponse.Coupon;
// update the coupon. this can be difficult given the complexity of coupons. see insertCoupon sample for details.
coupon.ExpirationDts = DateTime.UtcNow.AddDays(90).ToString("yyyy-MM-ddTHH:mm:ssK");
// This example only has one coupon. But it's a trivial matter to add more coupons
CouponsRequest couponsRequest = new CouponsRequest();
couponsRequest.Coupons = new List<Coupon> { coupon };
var updatedResponse = couponApi.UpdateCoupons(couponsRequest);
List<Coupon> updatedCoupons = updatedResponse.Coupons;
// Display the updated coupons
foreach (var updatedCoupon in updatedCoupons)
{
Console.WriteLine(updatedCoupon);
}
// Delete the coupon
couponApi.DeleteCoupon(coupon.CouponOid);
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
Console.WriteLine(ex.StackTrace);
}
}
}
}
package coupon;
import com.ultracart.admin.v2.CouponApi;
import com.ultracart.admin.v2.models.*;
import com.ultracart.admin.v2.util.ApiException;
import common.Constants;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class UpdateCoupons {
public static void Execute() {
System.out.println("--- " + UpdateCoupons.class.getSimpleName() + " ---");
try {
// Create coupon API instance using API key
CouponApi couponApi = new CouponApi(Constants.API_KEY);
String merchantCode = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 8);
// Now create the coupon and ensure it exists.
Coupon coupon = new Coupon();
coupon.setMerchantCode(merchantCode);
coupon.setDescription("Test coupon for GetCoupon");
coupon.setAmountOffSubtotal(new CouponAmountOffSubtotal()); // one penny discount.
coupon.getAmountOffSubtotal().setDiscountAmount(BigDecimal.valueOf(.01));
coupon.getAmountOffSubtotal().setCurrencyCode("USD");
CouponResponse couponResponse = couponApi.insertCoupon(coupon, null);
coupon = couponResponse.getCoupon();
// update the coupon. this can be difficult given the complexity of coupons. see insertCoupon sample for details.
coupon.setExpirationDts(Instant.now().plus(90, ChronoUnit.DAYS).toString());
// This example only has one coupon. But it's a trivial matter to add more coupons
CouponsRequest couponsRequest = new CouponsRequest();
List<Coupon> couponList = new ArrayList<>();
couponList.add(coupon);
couponsRequest.setCoupons(couponList);
CouponsResponse updatedResponse = couponApi.updateCoupons(couponsRequest, null, false, false);
List<Coupon> updatedCoupons = updatedResponse.getCoupons();
// Display the updated coupons
for (Coupon updatedCoupon : updatedCoupons) {
System.out.println(updatedCoupon);
}
// Delete the coupon
couponApi.deleteCoupon(coupon.getCouponOid());
}
catch (ApiException ex) {
System.out.println("Error: " + ex.getMessage());
ex.printStackTrace();
}
}
}
// Import API and UltraCart types
import { couponApi } from '../api.js';
import { DateTime } from 'luxon';
// Namespace-like structure using a class
export class UpdateCoupons {
static async execute() {
console.log(`--- UpdateCoupons ---`);
try {
// Generate a random 8-character merchant code (replacing GUID)
const merchantCode = Math.random().toString(36).substring(2, 10);
// Create the coupon and ensure it exists
const coupon = {
merchant_code: merchantCode,
description: "Test coupon for GetCoupon",
amount_off_subtotal: {
currency: "USD",
discount_amount: 0.01, // one penny discount, decimal becomes number
},
};
// Insert the coupon
const couponResponse = await new Promise((resolve, reject) => {
couponApi.insertCoupon(coupon, function (error, data, response) {
if (error) {
reject(error);
} else {
resolve(data, response);
}
});
});
const createdCoupon = couponResponse.coupon;
if (!createdCoupon?.coupon_oid) {
throw new Error("Failed to create coupon; no OID returned");
}
// Update the coupon. This can be difficult given the complexity of coupons. See InsertCoupon sample for details.
const updatedCouponData = {
...createdCoupon,
expiration_dts: DateTime.now()
.setZone('America/New_York')
.plus({ days: 90 })
.toISO(), // 90 days from now in ISO8601 format
};
// This example only has one coupon. But it's a trivial matter to add more coupons
const couponsRequest = {
coupons: [updatedCouponData],
};
// Update the coupons
const updatedResponse = await new Promise((resolve, reject) => {
couponApi.updateCoupons(couponsRequest, function (error, data, response) {
if (error) {
reject(error);
} else {
resolve(data, response);
}
});
});
const updatedCoupons = updatedResponse.coupons ?? [];
// Display the updated coupons
for (const updatedCoupon of updatedCoupons) {
console.log(updatedCoupon);
}
// Delete the coupon
await new Promise((resolve, reject) => {
couponApi.deleteCoupon(createdCoupon.coupon_oid, function (error, data, response) {
if (error) {
reject(error);
} else {
resolve(data, response);
}
});
});
} catch (ex) {
console.log(`Error: ${ex.message}`);
console.log(ex.stack);
}
}
}
// Example usage (optional, remove if not needed)
// UpdateCoupons.execute().catch(console.error);
<?php
use ultracart\v2\api\CouponApi;
use ultracart\v2\models\CouponsRequest;
require_once '../vendor/autoload.php';
$coupon_api = CouponApi::usingApiKey(Constants::API_KEY);
$coupon_oid = 123456789;
$_expand = null; // coupons do not have expansions
$_placeholders = null; // coupons do not use placeholders
$api_response = $coupon_api->getCoupon($coupon_oid, $_expand);
$coupon = $api_response->getCoupon();
// update the coupon. this can be difficult given the complexity of coupons. see insertCoupon sample for details.
$coupon->setExpirationDts(date('Y-m-d', strtotime('90 days')) . "T00:00:00+00:00");
// This example only has one coupon. But it's a trivial matter to add more coupons
$coupons_request = new CouponsRequest();
$coupons_request->setCoupons([$coupon]);
$api_response = $coupon_api->updateCoupons($coupons_request, $_expand, $_placeholders);
$updated_coupons = $api_response->getCoupons();
echo '<html lang="en"><body><pre>';
var_dump($updated_coupons);
echo '</pre></body></html>';
from ultracart.apis import CouponApi
from ultracart.models import CouponsRequest
from samples import api_client
from datetime import datetime, timedelta
coupon_api = CouponApi(api_client())
coupon_oid = 123456789
expand = None # coupons do not have expansions
placeholders = None # coupons do not use placeholders
api_response = coupon_api.get_coupon(coupon_oid, expand=expand)
coupon = api_response.coupon
# update the coupon. this can be difficult given the complexity of coupons. see insertCoupon sample for details.
expiration_date = (datetime.now() + timedelta(days=90)).strftime('%Y-%m-%dT00:00:00+00:00')
coupon.expiration_dts = expiration_date
# This example only has one coupon. But it's a trivial matter to add more coupons
coupons_request = CouponsRequest()
coupons_request.coupons = [coupon]
api_response = coupon_api.update_coupons(coupons_request, expand=expand, placeholders=placeholders)
updated_coupons = api_response.coupons
print(updated_coupons)
require 'ultracart_api'
require_relative '../constants'
# Initialize the coupon API
coupon_api = UltracartClient::CouponApi.new_using_api_key(Constants::API_KEY)
coupon_oid = 123456789
# coupons do not have expansions or placeholders
api_response = coupon_api.get_coupon(coupon_oid, {_expand: nil})
coupon = api_response.coupon
# update the coupon. this can be difficult given the complexity of coupons. see insertCoupon sample for details.
coupon.expiration_dts = (Date.today + 90).strftime('%Y-%m-%d') + 'T00:00:00+00:00'
# This example only has one coupon. But it's a trivial matter to add more coupons
coupons_request = UltracartClient::CouponsRequest.new
coupons_request.coupons = [coupon]
api_response = coupon_api.update_coupons(coupons_request, {_expand: nil, _placeholders: nil})
updated_coupons = api_response.coupons
puts updated_coupons
// Import API and UltraCart types
import { couponApi } from '../api';
import { Coupon, CouponAmountOffSubtotal, CouponsRequest } from 'ultracart_rest_api_v2_typescript';
import { DateTime } from 'luxon';
// Namespace-like structure using a class
export class UpdateCoupons {
public static async execute(): Promise<void> {
console.log(`--- UpdateCoupons ---`);
try {
// Generate a random 8-character merchant code (replacing GUID)
const merchantCode = Math.random().toString(36).substring(2, 10);
// Create the coupon and ensure it exists
const coupon: Coupon = {
merchant_code: merchantCode,
description: "Test coupon for GetCoupon",
amount_off_subtotal: {
currency: "USD",
discount_amount: 0.01, // one penny discount, decimal becomes number
} as CouponAmountOffSubtotal,
};
// Insert the coupon
const couponResponse = await couponApi.insertCoupon({
coupon: coupon,
});
const createdCoupon = couponResponse.coupon;
if (!createdCoupon?.coupon_oid) {
throw new Error("Failed to create coupon; no OID returned");
}
// Update the coupon. This can be difficult given the complexity of coupons. See InsertCoupon sample for details.
const updatedCouponData: Coupon = {
...createdCoupon,
expiration_dts: DateTime.now()
.setZone('America/New_York')
.plus({ days: 90 })
.toISO(), // 90 days from now in ISO8601 format
};
// This example only has one coupon. But it's a trivial matter to add more coupons
const couponsRequest: CouponsRequest = {
coupons: [updatedCouponData],
};
// Update the coupons
const updatedResponse = await couponApi.updateCoupons({
couponsRequest: couponsRequest,
});
const updatedCoupons = updatedResponse.coupons ?? [];
// Display the updated coupons
for (const updatedCoupon of updatedCoupons) {
console.log(updatedCoupon);
}
// Delete the coupon
await couponApi.deleteCoupon({couponOid: createdCoupon.coupon_oid});
} catch (ex) {
console.log(`Error: ${(ex as Error).message}`);
console.log((ex as Error).stack);
}
}
}
// Example usage (optional, remove if not needed)
// UpdateCoupons.execute().catch(console.error);
Delete coupons on the UltraCart account.
SDK Function Name: deleteCouponsByCode
Parameter | Description | Location | Data Type | Required |
---|---|---|---|---|
coupon_delete_request | Coupon oids to delete | body | CouponDeletesRequest | required |
using System;
using System.Collections.Generic;
using System.Reflection;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;
namespace SdkSample.coupon
{
public class DeleteCouponsByCode
{
/// <summary>
/// Deletes a specific coupon using the UltraCart API
/// </summary>
public static void Execute()
{
Console.WriteLine("--- " + MethodBase.GetCurrentMethod()?.DeclaringType?.Name + " ---");
CouponApi couponApi = new CouponApi(Constants.ApiKey);
string expand = null; // coupons do not have expansions.
String merchantCode = Guid.NewGuid().ToString("N").Substring(0, 8);
Coupon coupon = new Coupon();
coupon.MerchantCode = merchantCode;
coupon.Description = "Test coupon for DeleteCouponsByCode";
coupon.AmountOffSubtotal = new CouponAmountOffSubtotal("USD", 0.01m); // one penny discount.
CouponResponse couponResponse = couponApi.InsertCoupon(coupon, expand);
coupon = couponResponse.Coupon;
Console.WriteLine("Created the following temporary coupon:");
Console.WriteLine($"Coupon OID: {coupon.MerchantCode}");
Console.WriteLine($"Coupon Type: {coupon.CouponType}");
Console.WriteLine($"Coupon Description: {coupon.Description}");
// Delete the coupon
CouponDeletesRequest deleteRequest = new CouponDeletesRequest();
deleteRequest.CouponCodes = new List<string> { merchantCode };
couponApi.DeleteCouponsByCode(deleteRequest);
Console.WriteLine($"Successfully deleted coupon with merchantCode: {merchantCode}");
}
}
}
package coupon;
import com.ultracart.admin.v2.CouponApi;
import com.ultracart.admin.v2.models.Coupon;
import com.ultracart.admin.v2.models.CouponAmountOffSubtotal;
import com.ultracart.admin.v2.models.CouponDeletesRequest;
import com.ultracart.admin.v2.models.CouponResponse;
import com.ultracart.admin.v2.util.ApiException;
import common.Constants;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.UUID;
public class DeleteCouponsByCode {
/**
* Deletes a specific coupon using the UltraCart API
*/
public static void execute() {
System.out.println("--- " + DeleteCouponsByCode.class.getSimpleName() + " ---");
CouponApi couponApi = new CouponApi(Constants.API_KEY);
String expand = null; // coupons do not have expansions.
String merchantCode = UUID.randomUUID().toString().substring(0, 8);
Coupon coupon = new Coupon();
coupon.setMerchantCode(merchantCode);
coupon.setDescription("Test coupon for DeleteCouponsByCode");
CouponAmountOffSubtotal amountOff = new CouponAmountOffSubtotal();
amountOff.setCurrencyCode("USD");
amountOff.setDiscountAmount(new BigDecimal("0.01")); // one penny discount
coupon.setAmountOffSubtotal(amountOff);
try {
CouponResponse couponResponse = couponApi.insertCoupon(coupon, expand);
coupon = couponResponse.getCoupon();
System.out.println("Created the following temporary coupon:");
System.out.println("Coupon OID: " + coupon.getMerchantCode());
System.out.println("Coupon Type: " + coupon.getCouponType());
System.out.println("Coupon Description: " + coupon.getDescription());
// Delete the coupon
CouponDeletesRequest deleteRequest = new CouponDeletesRequest();
deleteRequest.setCouponCodes(Collections.singletonList(merchantCode));
couponApi.deleteCouponsByCode(deleteRequest);
System.out.println("Successfully deleted coupon with merchantCode: " + merchantCode);
} catch (ApiException e) {
System.err.println("Error occurred: " + e.getMessage());
e.printStackTrace();
}
}
}
import {couponApi} from '../api.js';
export class DeleteCouponByCode {
/**
* Deletes a specific coupon using the UltraCart API
*/
static async execute() {
console.log("--- DeleteCouponByCode ---");
const expand = undefined; // coupons do not have expansions.
const merchant_code = this.generateGuid().substring(0, 8);
const coupon = {
merchant_code: merchant_code,
description: "Test coupon for sdk_sample.coupon.DeleteCoupon",
amount_off_subtotal: {currency_code: "USD", discount_amount: 0.01}
}; // one penny discount.
const couponResponse = await new Promise((resolve, reject) => {
couponApi.insertCoupon(coupon, {_expand: expand}, function (error, data, response) {
if (error) {
reject(error);
} else {
resolve(data, response);
}
});
});
const createdCoupon = couponResponse.coupon;
console.log("Created the following temporary coupon:");
console.log(`Coupon OID: ${createdCoupon.coupon_oid}`);
console.log(`Coupon Type: ${createdCoupon.coupon_type}`);
console.log(`Coupon Description: ${createdCoupon.description}`);
await new Promise((resolve, reject) => {
couponApi.deleteCouponsByCode({coupon_codes: [merchant_code]}, function (error, data, response) {
if (error) {
reject(error);
} else {
resolve(data, response);
}
});
});
console.log(`Successfully deleted coupon with merchant_code: ${merchant_code}`);
}
// Helper method to generate a GUID-like string since TypeScript doesn't have Guid.NewGuid()
static generateGuid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
const r = Math.random() * 16 | 0;
const v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
}).replace(/-/g, '');
}
}
<?php
use ultracart\v2\api\CouponApi;
use ultracart\v2\models\CouponDeletesRequest;
require_once '../vendor/autoload.php';
$coupon_api = CouponApi::usingApiKey(Constants::API_KEY);
$merchant_code = '10OFF';
$deleteRequest = new CouponDeletesRequest();
$deleteRequest->setCouponCodes([$merchant_code]);
$coupon_api->deleteCouponsByCode($deleteRequest);
from ultracart.apis import CouponApi
from ultracart.models import CouponDeletesRequest
from samples import api_client
coupon_api = CouponApi(api_client())
merchant_code = '10OFF'
delete_request = CouponDeletesRequest()
delete_request.coupon_codes = [merchant_code]
coupon_api.delete_coupons_by_code(delete_request)
require_relative '../constants'
require 'ultracart_api'
coupon_api = UltracartClient::CouponApi.new_using_api_key(Constants::API_KEY)
merchant_code = '10OFF'
delete_request = UltracartClient::CouponDeletesRequest.new
delete_request.coupon_codes = [merchant_code]
coupon_api.delete_coupons_by_code(delete_request)
import {couponApi} from '../api';
import {
Coupon,
CouponAmountOffSubtotal, CouponDeletesRequest,
CouponResponse, DeleteCouponsByCodeRequest
} from 'ultracart_rest_api_v2_typescript';
export class DeleteCouponByCode {
/**
* Deletes a specific coupon using the UltraCart API
*/
public static async execute(): Promise<void> {
console.log("--- DeleteCouponByCode ---");
const expand: string | undefined = undefined; // coupons do not have expansions.
const merchant_code: string = this.generateGuid().substring(0, 8);
const coupon: Coupon = {
merchant_code: merchant_code,
description: "Test coupon for sdk_sample.coupon.DeleteCoupon",
amount_off_subtotal: {currency_code: "USD", discount_amount: 0.01} as CouponAmountOffSubtotal
}; // one penny discount.
const couponResponse: CouponResponse = await couponApi.insertCoupon({coupon: coupon, expand: expand});
const createdCoupon: Coupon = couponResponse.coupon!;
console.log("Created the following temporary coupon:");
console.log(`Coupon OID: ${createdCoupon.coupon_oid}`);
console.log(`Coupon Type: ${createdCoupon.coupon_type}`);
console.log(`Coupon Description: ${createdCoupon.description}`);
await couponApi.deleteCouponsByCode({couponDeleteRequest: {coupon_codes: [merchant_code]}});
console.log(`Successfully deleted coupon with merchant_code: ${merchant_code}`);
}
// Helper method to generate a GUID-like string since TypeScript doesn't have Guid.NewGuid()
private static generateGuid(): string {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
const r = Math.random() * 16 | 0;
const v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
}).replace(/-/g, '');
}
}
Delete coupons on the UltraCart account.
SDK Function Name: deleteCouponsByOid
Parameter | Description | Location | Data Type | Required |
---|---|---|---|---|
coupon_delete_request | Coupon oids to delete | body | CouponDeletesRequest | required |
using System;
using System.Collections.Generic;
using System.Reflection;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;
namespace SdkSample.coupon
{
public class DeleteCouponsByOid
{
/// <summary>
/// Deletes a specific coupon using the UltraCart API
/// </summary>
public static void Execute()
{
Console.WriteLine("--- " + MethodBase.GetCurrentMethod()?.DeclaringType?.Name + " ---");
CouponApi couponApi = new CouponApi(Constants.ApiKey);
string expand = null; // coupons do not have expansions.
String merchantCode = Guid.NewGuid().ToString("N").Substring(0, 8);
Coupon coupon = new Coupon();
coupon.MerchantCode = merchantCode;
coupon.Description = "Test coupon for DeleteCouponsByCode";
coupon.AmountOffSubtotal = new CouponAmountOffSubtotal("USD", 0.01m); // one penny discount.
CouponResponse couponResponse = couponApi.InsertCoupon(coupon, expand);
coupon = couponResponse.Coupon;
Console.WriteLine("Created the following temporary coupon:");
Console.WriteLine($"Coupon OID: {coupon.MerchantCode}");
Console.WriteLine($"Coupon Type: {coupon.CouponType}");
Console.WriteLine($"Coupon Description: {coupon.Description}");
// Delete the coupon
CouponDeletesRequest deleteRequest = new CouponDeletesRequest();
deleteRequest.CouponOids = new List<int> { coupon.CouponOid };
couponApi.DeleteCouponsByCode(deleteRequest);
Console.WriteLine($"Successfully deleted coupon with merchantCode: {merchantCode}");
}
}
}
package coupon;
import com.ultracart.admin.v2.CouponApi;
import com.ultracart.admin.v2.models.Coupon;
import com.ultracart.admin.v2.models.CouponAmountOffSubtotal;
import com.ultracart.admin.v2.models.CouponDeletesRequest;
import com.ultracart.admin.v2.models.CouponResponse;
import com.ultracart.admin.v2.util.ApiException;
import common.Constants;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.UUID;
public class DeleteCouponsByOid {
/**
* Deletes a specific coupon using the UltraCart API
*/
public static void execute() {
System.out.println("--- " + DeleteCouponsByOid.class.getSimpleName() + " ---");
CouponApi couponApi = new CouponApi(Constants.API_KEY);
String expand = null; // coupons do not have expansions.
String merchantCode = UUID.randomUUID().toString().substring(0, 8);
Coupon coupon = new Coupon();
coupon.setMerchantCode(merchantCode);
coupon.setDescription("Test coupon for DeleteCouponsByCode");
CouponAmountOffSubtotal amountOff = new CouponAmountOffSubtotal();
amountOff.setCurrencyCode("USD");
amountOff.setDiscountAmount(new BigDecimal("0.01")); // one penny discount
coupon.setAmountOffSubtotal(amountOff);
try {
CouponResponse couponResponse = couponApi.insertCoupon(coupon, expand);
coupon = couponResponse.getCoupon();
System.out.println("Created the following temporary coupon:");
System.out.println("Coupon OID: " + coupon.getMerchantCode());
System.out.println("Coupon Type: " + coupon.getCouponType());
System.out.println("Coupon Description: " + coupon.getDescription());
// Delete the coupon
CouponDeletesRequest deleteRequest = new CouponDeletesRequest();
deleteRequest.setCouponOids(Collections.singletonList(coupon.getCouponOid()));
couponApi.deleteCouponsByOid(deleteRequest);
System.out.println("Successfully deleted coupon with merchantCode: " + merchantCode);
} catch (ApiException e) {
System.err.println("Error occurred: " + e.getMessage());
e.printStackTrace();
}
}
}
import {couponApi} from '../api.js';
export class DeleteCouponByOid {
/**
* Deletes a specific coupon using the UltraCart API
*/
static async execute() {
console.log("--- DeleteCouponByOid ---");
const expand = undefined; // coupons do not have expansions.
const merchant_code = this.generateGuid().substring(0, 8);
const coupon = {
merchant_code: merchant_code,
description: "Test coupon for sdk_sample.coupon.DeleteCoupon",
amount_off_subtotal: {currency_code: "USD", discount_amount: 0.01}
}; // one penny discount.
const couponResponse = await new Promise((resolve, reject) => {
couponApi.insertCoupon(coupon, {_expand: expand}, function (error, data, response) {
if (error) {
reject(error);
} else {
resolve(data, response);
}
});
});
const createdCoupon = couponResponse.coupon;
console.log("Created the following temporary coupon:");
console.log(`Coupon OID: ${createdCoupon.coupon_oid}`);
console.log(`Coupon Type: ${createdCoupon.coupon_type}`);
console.log(`Coupon Description: ${createdCoupon.description}`);
const couponOid = createdCoupon.coupon_oid;
await new Promise((resolve, reject) => {
couponApi.deleteCouponsByOid({coupon_oids: [couponOid]}, function (error, data, response) {
if (error) {
reject(error);
} else {
resolve(data, response);
}
});
});
console.log(`Successfully deleted coupon with ID: ${couponOid}`);
}
// Helper method to generate a GUID-like string since TypeScript doesn't have Guid.NewGuid()
static generateGuid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
const r = Math.random() * 16 | 0;
const v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
}).replace(/-/g, '');
}
}
<?php
use ultracart\v2\api\CouponApi;
use ultracart\v2\models\CouponDeletesRequest;
require_once '../vendor/autoload.php';
// This method is useful if you have the coupons stored in your own system along with their coupon_oids. If not,
// just use deleteCouponsByCode()
$coupon_api = CouponApi::usingApiKey(Constants::API_KEY);
$deleteRequest = new CouponDeletesRequest();
$deleteRequest->setCouponOids([1234567, 2345678, 3456789]);
$coupon_api->deleteCouponsByOid($deleteRequest);
from ultracart.apis import CouponApi
from ultracart.models import CouponDeletesRequest
from samples import api_client
# This method is useful if you have the coupons stored in your own system along with their coupon_oids. If not,
# just use delete_coupons_by_code()
coupon_api = CouponApi(api_client())
delete_request = CouponDeletesRequest()
delete_request.coupon_oids = [1234567, 2345678, 3456789]
coupon_api.delete_coupons_by_oid(delete_request)
require_relative '../constants'
require 'ultracart_api'
# This method is useful if you have the coupons stored in your own system along with their coupon_oids. If not,
# just use delete_coupons_by_code()
coupon_api = UltracartClient::CouponApi.new_using_api_key(Constants::API_KEY)
delete_request = UltracartClient::CouponDeletesRequest.new
delete_request.coupon_oids = [1234567, 2345678, 3456789]
coupon_api.delete_coupons_by_oid(delete_request)
import {couponApi} from '../api';
import {
Coupon,
CouponAmountOffSubtotal, CouponDeletesRequest,
CouponResponse, DeleteCouponsByCodeRequest
} from 'ultracart_rest_api_v2_typescript';
export class DeleteCouponByOid {
/**
* Deletes a specific coupon using the UltraCart API
*/
public static async execute(): Promise<void> {
console.log("--- DeleteCouponByOid ---");
const expand: string | undefined = undefined; // coupons do not have expansions.
const merchant_code: string = this.generateGuid().substring(0, 8);
const coupon: Coupon = {
merchant_code: merchant_code,
description: "Test coupon for sdk_sample.coupon.DeleteCoupon",
amount_off_subtotal: {currency_code: "USD", discount_amount: 0.01} as CouponAmountOffSubtotal
}; // one penny discount.
const couponResponse: CouponResponse = await couponApi.insertCoupon({coupon: coupon, expand: expand});
const createdCoupon: Coupon = couponResponse.coupon!;
console.log("Created the following temporary coupon:");
console.log(`Coupon OID: ${createdCoupon.coupon_oid}`);
console.log(`Coupon Type: ${createdCoupon.coupon_type}`);
console.log(`Coupon Description: ${createdCoupon.description}`);
const couponOid: number = createdCoupon.coupon_oid!;
await couponApi.deleteCouponsByOid({couponDeleteRequest: {coupon_oids: [couponOid]}});
console.log(`Successfully deleted coupon with ID: ${couponOid}`);
}
// Helper method to generate a GUID-like string since TypeScript doesn't have Guid.NewGuid()
private static generateGuid(): string {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
const r = Math.random() * 16 | 0;
const v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
}).replace(/-/g, '');
}
}
Retrieves a single coupon using the specified merchant code.
SDK Function Name: getCouponByMerchantCode
Parameter | Description | Location | Data Type | Required |
---|---|---|---|---|
merchant_code | The coupon merchant code to retrieve. | path | string | required |
_expand | The object expansion to perform on the result. See documentation for examples | query | string | optional |
using System;
using System.Reflection;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;
namespace SdkSample.coupon
{
public class GetCouponByMerchantCode
{
public static void Execute()
{
Console.WriteLine("--- " + MethodBase.GetCurrentMethod()?.DeclaringType?.Name + " ---");
try
{
CouponApi couponApi = new CouponApi(Constants.ApiKey);
String merchantCode = Guid.NewGuid().ToString("N").Substring(0, 8);
// Now create the coupon and ensure it exists.
Coupon coupon = new Coupon();
coupon.MerchantCode = merchantCode;
coupon.Description = "Test coupon for GetCoupon";
coupon.AmountOffSubtotal = new CouponAmountOffSubtotal("USD", 0.01m); // one penny discount.
CouponResponse couponResponse = couponApi.InsertCoupon(coupon);
coupon = couponResponse.Coupon;
Console.WriteLine("Created the following temporary coupon:");
Console.WriteLine($"Coupon OID: {coupon.MerchantCode}");
Console.WriteLine($"Coupon Type: {coupon.CouponType}");
Console.WriteLine($"Coupon Description: {coupon.Description}");
couponResponse = couponApi.GetCouponByMerchantCode(merchantCode);
Coupon copyOfCoupon = couponResponse.Coupon;
Console.WriteLine("GetCoupon returned the following coupon:");
Console.WriteLine($"Coupon OID: {copyOfCoupon.MerchantCode}");
Console.WriteLine($"Coupon Type: {copyOfCoupon.CouponType}");
Console.WriteLine($"Coupon Description: {copyOfCoupon.Description}");
// Delete the coupon
couponApi.DeleteCoupon(coupon.CouponOid);
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
Console.WriteLine(ex.StackTrace);
}
}
}
}
package coupon;
import com.ultracart.admin.v2.CouponApi;
import com.ultracart.admin.v2.models.Coupon;
import com.ultracart.admin.v2.models.CouponAmountOffSubtotal;
import com.ultracart.admin.v2.models.CouponResponse;
import com.ultracart.admin.v2.util.ApiException;
import common.Constants;
import java.math.BigDecimal;
import java.util.UUID;
public class GetCouponByMerchantCode {
public static void execute() {
try {
CouponApi couponApi = new CouponApi(Constants.API_KEY);
String merchantCode = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 8);
// Now create the coupon and ensure it exists.
Coupon coupon = new Coupon();
coupon.setMerchantCode(merchantCode);
coupon.setDescription("Test coupon for GetCoupon");
coupon.setAmountOffSubtotal(new CouponAmountOffSubtotal()); // one penny discount.
coupon.getAmountOffSubtotal().setDiscountAmount(BigDecimal.valueOf(.01));
coupon.getAmountOffSubtotal().setCurrencyCode("USD");
CouponResponse couponResponse = couponApi.insertCoupon(coupon, null);
coupon = couponResponse.getCoupon();
System.out.println("Created the following temporary coupon:");
System.out.println("Coupon OID: " + coupon.getMerchantCode());
System.out.println("Coupon Type: " + coupon.getCouponType());
System.out.println("Coupon Description: " + coupon.getDescription());
couponResponse = couponApi.getCouponByMerchantCode(merchantCode, null);
Coupon copyOfCoupon = couponResponse.getCoupon();
System.out.println("GetCoupon returned the following coupon:");
System.out.println("Coupon OID: " + copyOfCoupon.getMerchantCode());
System.out.println("Coupon Type: " + copyOfCoupon.getCouponType());
System.out.println("Coupon Description: " + copyOfCoupon.getDescription());
// Delete the coupon
couponApi.deleteCoupon(coupon.getCouponOid());
}
catch (ApiException ex) {
System.out.println("Error: " + ex.getMessage());
ex.printStackTrace();
}
}
}
import { couponApi } from '../api.js';
export class GetCouponByMerchantCode {
static async execute() {
console.log("--- GetCouponByMerchantCode ---");
try {
const merchantCode = this.generateGuid().substring(0, 8);
// Now create the coupon and ensure it exists.
const coupon = {
merchant_code: merchantCode,
description: "Test coupon for GetCoupon",
amount_off_subtotal: { currency_code: "USD", discount_amount: 0.01 }
}; // one penny discount.
const couponResponse = await new Promise((resolve, reject) => {
couponApi.insertCoupon(coupon, function (error, data, response) {
if (error) {
reject(error);
} else {
resolve(data, response);
}
});
});
const createdCoupon = couponResponse.coupon;
console.log("Created the following temporary coupon:");
console.log(`Coupon OID: ${createdCoupon.coupon_oid}`);
console.log(`Coupon Type: ${createdCoupon.coupon_type}`);
console.log(`Coupon Description: ${createdCoupon.description}`);
const retrievedResponse = await new Promise((resolve, reject) => {
couponApi.getCouponByMerchantCode(merchantCode, function (error, data, response) {
if (error) {
reject(error);
} else {
resolve(data, response);
}
});
});
const copyOfCoupon = retrievedResponse.coupon;
console.log("GetCoupon returned the following coupon:");
console.log(`Coupon OID: ${copyOfCoupon.coupon_oid}`);
console.log(`Coupon Type: ${copyOfCoupon.coupon_type}`);
console.log(`Coupon Description: ${copyOfCoupon.description}`);
// Delete the coupon
await new Promise((resolve, reject) => {
couponApi.deleteCoupon(createdCoupon.coupon_oid, function (error, data, response) {
if (error) {
reject(error);
} else {
resolve(data, response);
}
});
});
} catch (ex) {
console.log(`Error: ${ex.message}`);
console.log(ex.stack);
}
}
// Helper method to generate a GUID-like string since TypeScript doesn't have Guid.NewGuid()
static generateGuid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
const r = Math.random() * 16 | 0;
const v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
}).replace(/-/g, '');
}
}
<?php
use ultracart\v2\api\CouponApi;
require_once '../vendor/autoload.php';
$coupon_api = CouponApi::usingApiKey(Constants::API_KEY);
$api_response = $coupon_api->getCouponByMerchantCode('10OFF');
echo '<html lang="en"><body><pre>';
var_dump($api_response);
echo '</pre></body></html>';
from ultracart.apis import CouponApi
from samples import api_client
coupon_api = CouponApi(api_client())
api_response = coupon_api.get_coupon_by_merchant_code('10OFF')
print(api_response)
require_relative '../constants'
require 'ultracart_api'
coupon_api = UltracartClient::CouponApi.new_using_api_key(Constants::API_KEY)
api_response = coupon_api.get_coupon_by_merchant_code('10OFF')
puts api_response.inspect
import { couponApi } from '../api';
import { Coupon, CouponAmountOffSubtotal, CouponResponse } from 'ultracart_rest_api_v2_typescript';
export class GetCouponByMerchantCode {
public static async execute(): Promise<void> {
console.log("--- GetCouponByMerchantCode ---");
try {
const merchantCode: string = this.generateGuid().substring(0, 8);
// Now create the coupon and ensure it exists.
const coupon: Coupon = {
merchant_code: merchantCode,
description: "Test coupon for GetCoupon",
amount_off_subtotal: { currency_code: "USD", discount_amount: 0.01 } as CouponAmountOffSubtotal
}; // one penny discount.
const couponResponse: CouponResponse = await couponApi.insertCoupon({coupon: coupon});
const createdCoupon: Coupon = couponResponse.coupon!;
console.log("Created the following temporary coupon:");
console.log(`Coupon OID: ${createdCoupon.coupon_oid}`);
console.log(`Coupon Type: ${createdCoupon.coupon_type}`);
console.log(`Coupon Description: ${createdCoupon.description}`);
const retrievedResponse: CouponResponse = await couponApi.getCouponByMerchantCode({merchantCode: merchantCode});
const copyOfCoupon: Coupon = retrievedResponse.coupon!;
console.log("GetCoupon returned the following coupon:");
console.log(`Coupon OID: ${copyOfCoupon.coupon_oid}`);
console.log(`Coupon Type: ${copyOfCoupon.coupon_type}`);
console.log(`Coupon Description: ${copyOfCoupon.description}`);
// Delete the coupon
await couponApi.deleteCoupon({couponOid: createdCoupon.coupon_oid!});
} catch (ex: any) {
console.log(`Error: ${ex.message}`);
console.log(ex.stack);
}
}
// Helper method to generate a GUID-like string since TypeScript doesn't have Guid.NewGuid()
private static generateGuid(): string {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
const r = Math.random() * 16 | 0;
const v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
}).replace(/-/g, '');
}
}
Determines if a coupon merchant code already exists.
SDK Function Name: doesCouponCodeExist
Parameter | Description | Location | Data Type | Required |
---|---|---|---|---|
merchant_code | The coupon merchant code to examine. | path | string | required |
using System;
using System.Reflection;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;
namespace SdkSample.coupon
{
public class DoesCouponCodeExist
{
public static void Execute()
{
Console.WriteLine("--- " + MethodBase.GetCurrentMethod()?.DeclaringType?.Name + " ---");
try
{
CouponApi couponApi = new CouponApi(Constants.ApiKey);
String merchantCode = Guid.NewGuid().ToString("N").Substring(0, 8);
CouponExistsResponse couponExistsResponse = couponApi.DoesCouponCodeExist(merchantCode);
// The response should be false.
if (couponExistsResponse.Exists)
{
throw new Exception("CouponApi.DoesCouponCodeExist should have returned false.");
}
// Now create the coupon and ensure it exists.
Coupon coupon = new Coupon();
coupon.MerchantCode = merchantCode;
coupon.Description = "Test coupon for DoesCouponCodeExist";
coupon.AmountOffSubtotal = new CouponAmountOffSubtotal("USD", 0.01m); // one penny discount.
CouponResponse couponResponse = couponApi.InsertCoupon(coupon);
coupon = couponResponse.Coupon;
Console.WriteLine("Created the following temporary coupon:");
Console.WriteLine($"Coupon OID: {coupon.MerchantCode}");
Console.WriteLine($"Coupon Type: {coupon.CouponType}");
Console.WriteLine($"Coupon Description: {coupon.Description}");
couponExistsResponse = couponApi.DoesCouponCodeExist(merchantCode);
if (!couponExistsResponse.Exists)
{
throw new Exception(
"CouponApi.DoesCouponCodeExist should have returned true after creating the coupon.");
}
// Delete the coupon
couponApi.DeleteCoupon(coupon.CouponOid);
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
Console.WriteLine(ex.StackTrace);
}
}
}
}
package coupon;
import com.ultracart.admin.v2.CouponApi;
import com.ultracart.admin.v2.models.Coupon;
import com.ultracart.admin.v2.models.CouponAmountOffSubtotal;
import com.ultracart.admin.v2.models.CouponExistsResponse;
import com.ultracart.admin.v2.models.CouponResponse;
import common.Constants;
import java.math.BigDecimal;
import java.util.UUID;
public class DoesCouponCodeExist {
public static void execute() {
System.out.println("--- " + DoesCouponCodeExist.class.getSimpleName() + " ---");
try {
CouponApi couponApi = new CouponApi(Constants.API_KEY);
String merchantCode = UUID.randomUUID().toString().substring(0, 8);
CouponExistsResponse couponExistsResponse = couponApi.doesCouponCodeExist(merchantCode);
// The response should be false.
if (couponExistsResponse.getExists()) {
throw new Exception("CouponApi.doesCouponCodeExist should have returned false.");
}
// Now create the coupon and ensure it exists.
Coupon coupon = new Coupon();
coupon.setMerchantCode(merchantCode);
coupon.setDescription("Test coupon for DoesCouponCodeExist");
CouponAmountOffSubtotal amountOff = new CouponAmountOffSubtotal();
amountOff.setCurrencyCode("USD");
amountOff.setDiscountAmount(new BigDecimal("0.01")); // one penny discount
coupon.setAmountOffSubtotal(amountOff);
CouponResponse couponResponse = couponApi.insertCoupon(coupon, null);
coupon = couponResponse.getCoupon();
System.out.println("Created the following temporary coupon:");
System.out.println("Coupon OID: " + coupon.getMerchantCode());
System.out.println("Coupon Type: " + coupon.getCouponType());
System.out.println("Coupon Description: " + coupon.getDescription());
couponExistsResponse = couponApi.doesCouponCodeExist(merchantCode);
if (!couponExistsResponse.getExists()) {
throw new Exception(
"CouponApi.doesCouponCodeExist should have returned true after creating the coupon.");
}
// Delete the coupon
couponApi.deleteCoupon(coupon.getCouponOid());
} catch (Exception ex) {
System.out.println("Error: " + ex.getMessage());
ex.printStackTrace();
}
}
}
import { couponApi } from '../api.js';
export class DoesCouponCodeExist {
static async execute() {
console.log("--- DoesCouponCodeExist ---");
try {
const api = couponApi;
const merchantCode = this.generateGuid().substring(0, 8);
const couponExistsResponse = await new Promise((resolve, reject) => {
api.doesCouponCodeExist(merchantCode, function (error, data, response) {
if (error) {
reject(error);
} else {
resolve(data, response);
}
});
});
// The response should be false.
if (couponExistsResponse._exists) {
throw new Error("CouponApi.doesCouponCodeExist should have returned false since we are checking for a fake coupon.");
}
// Now create the coupon and ensure it exists.
const coupon = {
merchant_code: merchantCode,
description: "Test coupon for DoesCouponCodeExist",
amount_off_subtotal: { currency_code: "USD", discount_amount: 0.01 }
}; // one penny discount.
const couponResponse = await new Promise((resolve, reject) => {
api.insertCoupon(coupon, function (error, data, response) {
if (error) {
reject(error);
} else {
resolve(data, response);
}
});
});
const createdCoupon = couponResponse.coupon;
console.log("Created the following temporary coupon:");
console.log(`Coupon OID: ${createdCoupon.merchant_code}`);
console.log(`Coupon Type: ${createdCoupon.coupon_type}`);
console.log(`Coupon Description: ${createdCoupon.description}`);
const secondExistsResponse = await new Promise((resolve, reject) => {
api.doesCouponCodeExist(merchantCode, function (error, data, response) {
if (error) {
reject(error);
} else {
resolve(data, response);
}
});
});
if (!secondExistsResponse._exists) {
throw new Error(
"CouponApi.doesCouponCodeExist should have returned true after creating the coupon."
);
}
// Delete the coupon
await new Promise((resolve, reject) => {
api.deleteCoupon(createdCoupon.coupon_oid, function (error, data, response) {
if (error) {
reject(error);
} else {
resolve(data, response);
}
});
});
} catch (ex) {
console.log(`Error: ${ex.message}`);
console.log(ex.stack);
}
}
// Helper method to generate a GUID-like string since TypeScript doesn't have Guid.NewGuid()
static generateGuid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
const r = Math.random() * 16 | 0;
const v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
}).replace(/-/g, '');
}
}
<?php
use ultracart\v2\api\CouponApi;
require_once '../vendor/autoload.php';
$coupon_api = CouponApi::usingApiKey(Constants::API_KEY);
$merchant_code = '10OFF';
$api_response = $coupon_api->doesCouponCodeExist($merchant_code);
$coupon_exists = $api_response->getExists();
echo '<html lang="en"><body><pre>';
var_dump($api_response);
echo '</pre></body></html>';
from ultracart.apis import CouponApi
from samples import api_client
coupon_api = CouponApi(api_client())
merchant_code = '10OFF'
api_response = coupon_api.does_coupon_code_exist(merchant_code)
coupon_exists = api_response.exists
print(api_response)
require_relative '../constants'
require 'ultracart_api'
coupon_api = UltracartClient::CouponApi.new_using_api_key(Constants::API_KEY)
merchant_code = '10OFF'
api_response = coupon_api.does_coupon_code_exist(merchant_code)
coupon_exists = api_response.exists
puts api_response.inspect
import { couponApi } from '../api';
import {
Coupon,
CouponAmountOffSubtotal,
CouponResponse,
CouponExistsResponse,
DoesCouponCodeExistRequest
} from 'ultracart_rest_api_v2_typescript';
export class DoesCouponCodeExist {
public static async execute(): Promise<void> {
console.log("--- DoesCouponCodeExist ---");
try {
const api = couponApi;
const merchantCode: string = this.generateGuid().substring(0, 8);
const couponExistsResponse: CouponExistsResponse = await api.doesCouponCodeExist({merchantCode: merchantCode});
// The response should be false.
if (couponExistsResponse._exists) {
throw new Error("CouponApi.doesCouponCodeExist should have returned false since we are checking for a fake coupon.");
}
// Now create the coupon and ensure it exists.
const coupon: Coupon = {
merchant_code: merchantCode,
description: "Test coupon for DoesCouponCodeExist",
amount_off_subtotal: { currency_code: "USD", discount_amount: 0.01 } as CouponAmountOffSubtotal
}; // one penny discount.
const couponResponse: CouponResponse = await api.insertCoupon({coupon: coupon});
const createdCoupon: Coupon = couponResponse.coupon!;
console.log("Created the following temporary coupon:");
console.log(`Coupon OID: ${createdCoupon.merchant_code}`);
console.log(`Coupon Type: ${createdCoupon.coupon_type}`);
console.log(`Coupon Description: ${createdCoupon.description}`);
const secondExistsResponse: CouponExistsResponse = await api.doesCouponCodeExist({merchantCode: merchantCode});
if (!secondExistsResponse._exists) {
throw new Error(
"CouponApi.doesCouponCodeExist should have returned true after creating the coupon."
);
}
// Delete the coupon
await api.deleteCoupon({couponOid: createdCoupon.coupon_oid!});
} catch (ex: any) {
console.log(`Error: ${ex.message}`);
console.log(ex.stack);
}
}
// Helper method to generate a GUID-like string since TypeScript doesn't have Guid.NewGuid()
private static generateGuid(): string {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
const r = Math.random() * 16 | 0;
const v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
}).replace(/-/g, '');
}
}
Generate one time codes by merchant code
SDK Function Name: generateOneTimeCodesByMerchantCode
Parameter | Description | Location | Data Type | Required |
---|---|---|---|---|
merchant_code | The merchant code to generate one time codes. | path | string | required |
coupon_codes_request | Coupon code generation parameters | body | CouponCodesRequest | required |
using System;
using System.Reflection;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;
namespace SdkSample.coupon
{
public class GenerateOneTimeCodesByMerchantCode
{
public static void Execute()
{
Console.WriteLine("--- " + MethodBase.GetCurrentMethod()?.DeclaringType?.Name + " ---");
try
{
// Create coupon API instance using API key
CouponApi couponApi = new CouponApi(Constants.ApiKey);
String merchantCode = Guid.NewGuid().ToString("N").Substring(0, 8);
// Now create the coupon and ensure it exists.
Coupon coupon = new Coupon();
coupon.MerchantCode = merchantCode;
coupon.Description = "Test coupon for GetCoupon";
coupon.AmountOffSubtotal = new CouponAmountOffSubtotal("USD", 0.01m); // one penny discount.
CouponResponse couponResponse = couponApi.InsertCoupon(coupon);
coupon = couponResponse.Coupon;
Console.WriteLine("Created the following temporary coupon:");
Console.WriteLine($"Coupon OID: {coupon.MerchantCode}");
Console.WriteLine($"Coupon Type: {coupon.CouponType}");
Console.WriteLine($"Coupon Description: {coupon.Description}");
CouponCodesRequest codesRequest = new CouponCodesRequest();
codesRequest.Quantity = 5; // give me 5 codes.
codesRequest.ExpirationDts = DateTime.UtcNow.AddDays(90).ToString("yyyy-MM-ddTHH:mm:ssK"); // do you want the codes to expire?
// codesRequest.ExpirationSeconds = null; // also an option for short-lived coupons
var apiResponse = couponApi.GenerateOneTimeCodesByMerchantCode(merchantCode, codesRequest);
var couponCodes = apiResponse.CouponCodes;
// Display generated coupon codes
Console.WriteLine($"Generated {couponCodes.Count} one-time coupon codes for merchant code '{merchantCode}':");
foreach (var code in couponCodes)
{
Console.WriteLine(code);
}
// Delete the coupon
couponApi.DeleteCoupon(coupon.CouponOid);
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
Console.WriteLine(ex.StackTrace);
}
}
}
}
package coupon;
import com.ultracart.admin.v2.CouponApi;
import com.ultracart.admin.v2.models.*;
import com.ultracart.admin.v2.util.ApiException;
import common.Constants;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.UUID;
public class GenerateOneTimeCodesByMerchantCode {
public static void execute() {
System.out.println("--- " + GenerateOneTimeCodesByMerchantCode.class.getSimpleName() + " ---");
try {
// Create coupon API instance using API key
CouponApi couponApi = new CouponApi(Constants.API_KEY);
String merchantCode = UUID.randomUUID().toString().substring(0, 8);
// Now create the coupon and ensure it exists.
Coupon coupon = new Coupon();
coupon.setMerchantCode(merchantCode);
coupon.setDescription("Test coupon for GetCoupon");
CouponAmountOffSubtotal amountOff = new CouponAmountOffSubtotal();
amountOff.setCurrencyCode("USD");
amountOff.setDiscountAmount(new BigDecimal("0.01")); // one penny discount
coupon.setAmountOffSubtotal(amountOff);
CouponResponse couponResponse = couponApi.insertCoupon(coupon, null);
coupon = couponResponse.getCoupon();
System.out.println("Created the following temporary coupon:");
System.out.println("Coupon OID: " + coupon.getMerchantCode());
System.out.println("Coupon Type: " + coupon.getCouponType());
System.out.println("Coupon Description: " + coupon.getDescription());
CouponCodesRequest codesRequest = new CouponCodesRequest();
codesRequest.setQuantity(5); // give me 5 codes.
codesRequest.setExpirationDts(Instant.now().plus(90, ChronoUnit.DAYS).toString()); // do you want the codes to expire?
// codesRequest.setExpirationSeconds(null); // also an option for short-lived coupons
CouponCodesResponse apiResponse = couponApi.generateOneTimeCodesByMerchantCode(merchantCode, codesRequest);
List<String> couponCodes = apiResponse.getCouponCodes();
// Display generated coupon codes
System.out.println("Generated " + couponCodes.size() + " one-time coupon codes for merchant code '" + merchantCode + "':");
for (String code : couponCodes) {
System.out.println(code);
}
// Delete the coupon
couponApi.deleteCoupon(coupon.getCouponOid());
} catch (ApiException ex) {
System.out.println("Error: " + ex.getMessage());
ex.printStackTrace();
}
}
}
import { couponApi } from '../api.js';
import { DateTime } from 'luxon';
export class GenerateOneTimeCodesByMerchantCode {
static async execute() {
console.log("--- GenerateOneTimeCodesByMerchantCode ---");
try {
const merchantCode = this.generateGuid().substring(0, 8);
// Now create the coupon and ensure it exists.
const coupon = {
merchant_code: merchantCode,
description: "Test coupon for GetCoupon",
amount_off_subtotal: { currencyCode: "USD", discountAmount: 0.01 }
}; // one penny discount.
const couponResponse = await new Promise((resolve, reject) => {
couponApi.insertCoupon(coupon, function (error, data, response) {
if (error) {
reject(error);
} else {
resolve(data, response);
}
});
});
const createdCoupon = couponResponse.coupon;
console.log("Created the following temporary coupon:");
console.log(`Coupon Code: ${createdCoupon.merchant_code}`);
console.log(`Coupon Type: ${createdCoupon.coupon_type}`);
console.log(`Coupon Description: ${createdCoupon.description}`);
const codesRequest = {
quantity: 5, // give me 5 codes.
expiration_dts: DateTime.utc().plus({ days: 90 }).toISO() // do you want the codes to expire?
// expirationSeconds: null // also an option for short-lived coupons
};
const apiResponse = await new Promise((resolve, reject) => {
couponApi.generateOneTimeCodesByMerchantCode(merchantCode, codesRequest, function (error, data, response) {
if (error) {
reject(error);
} else {
resolve(data, response);
}
});
});
const couponCodes = apiResponse.coupon_codes;
// Display generated coupon codes
console.log(`Generated ${couponCodes.length} one-time coupon codes for merchant code '${merchantCode}':`);
for (const code of couponCodes) {
console.log(code);
}
// Delete the coupon
await new Promise((resolve, reject) => {
couponApi.deleteCoupon(createdCoupon.coupon_oid, function (error, data, response) {
if (error) {
reject(error);
} else {
resolve(data, response);
}
});
});
} catch (ex) {
console.log(`Error: ${ex.message}`);
console.log(ex.stack);
}
}
// Helper method to generate a GUID-like string since TypeScript doesn't have Guid.NewGuid()
static generateGuid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
const r = Math.random() * 16 | 0;
const v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
}).replace(/-/g, '');
}
}
<?php
use ultracart\v2\api\CouponApi;
use ultracart\v2\models\CouponCodesRequest;
require_once '../vendor/autoload.php';
$coupon_api = CouponApi::usingApiKey(Constants::API_KEY);
$merchant_code = '10OFF';
$codesRequest = new CouponCodesRequest();
$codesRequest->setQuantity(100); // give me 100 codes.
$codesRequest->setExpirationDts(date('Y-m-d', strtotime('90 days')) . "T00:00:00+00:00"); // do you want the codes to expire?
// $codesRequest->setExpirationSeconds(); // also an option for short-lived coupons
$api_response = $coupon_api->generateOneTimeCodesByMerchantCode($merchant_code, $codesRequest);
$coupon_codes = $api_response->getCouponCodes();
from ultracart.apis import CouponApi
from ultracart.models import CouponCodesRequest
from samples import api_client
from datetime import datetime, timedelta
coupon_api = CouponApi(api_client())
merchant_code = '10OFF'
codes_request = CouponCodesRequest()
codes_request.quantity = 100 # give me 100 codes.
expiration_date = (datetime.now() + timedelta(days=90)).strftime('%Y-%m-%dT00:00:00+00:00')
codes_request.expiration_dts = expiration_date # do you want the codes to expire?
# codes_request.expiration_seconds = None # also an option for short-lived coupons
api_response = coupon_api.generate_one_time_codes_by_merchant_code(merchant_code, codes_request)
coupon_codes = api_response.coupon_codes
require_relative '../constants'
require 'ultracart_api'
coupon_api = UltracartClient::CouponApi.new_using_api_key(Constants::API_KEY)
coupon_oid = 12345678 # if you don't know your coupon_oid, use generate_one_time_codes_by_merchant_code. same results
codes_request = UltracartClient::CouponCodesRequest.new
codes_request.quantity = 100 # give me 100 codes.
codes_request.expiration_dts = (Date.today + 90).strftime('%Y-%m-%d') + 'T00:00:00+00:00' # do you want the codes to expire?
# codes_request.expiration_seconds # also an option for short-lived coupons
api_response = coupon_api.generate_coupon_codes(coupon_oid, codes_request)
coupon_codes = api_response.coupon_codes
import { couponApi } from '../api';
import { Coupon, CouponAmountOffSubtotal, CouponResponse, CouponCodesRequest, CouponCodesResponse } from 'ultracart_rest_api_v2_typescript';
import { DateTime } from 'luxon';
export class GenerateOneTimeCodesByMerchantCode {
public static async execute(): Promise<void> {
console.log("--- GenerateOneTimeCodesByMerchantCode ---");
try {
const merchantCode: string = this.generateGuid().substring(0, 8);
// Now create the coupon and ensure it exists.
const coupon: Coupon = {
merchant_code: merchantCode,
description: "Test coupon for GetCoupon",
amount_off_subtotal: { currencyCode: "USD", discountAmount: 0.01 } as CouponAmountOffSubtotal
}; // one penny discount.
const couponResponse: CouponResponse = await couponApi.insertCoupon({coupon: coupon});
const createdCoupon: Coupon = couponResponse.coupon!;
console.log("Created the following temporary coupon:");
console.log(`Coupon Code: ${createdCoupon.merchant_code}`);
console.log(`Coupon Type: ${createdCoupon.coupon_type}`);
console.log(`Coupon Description: ${createdCoupon.description}`);
const codesRequest: CouponCodesRequest = {
quantity: 5, // give me 5 codes.
expiration_dts: DateTime.utc().plus({ days: 90 }).toISO() // do you want the codes to expire?
// expirationSeconds: null // also an option for short-lived coupons
};
const apiResponse: CouponCodesResponse = await couponApi.generateOneTimeCodesByMerchantCode({merchantCode: merchantCode, couponCodesRequest: codesRequest});
const couponCodes: string[] = apiResponse.coupon_codes!;
// Display generated coupon codes
console.log(`Generated ${couponCodes.length} one-time coupon codes for merchant code '${merchantCode}':`);
for (const code of couponCodes) {
console.log(code);
}
// Delete the coupon
await couponApi.deleteCoupon({couponOid: createdCoupon.coupon_oid!});
} catch (ex: any) {
console.log(`Error: ${ex.message}`);
console.log(ex.stack);
}
}
// Helper method to generate a GUID-like string since TypeScript doesn't have Guid.NewGuid()
private static generateGuid(): string {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
const r = Math.random() * 16 | 0;
const v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
}).replace(/-/g, '');
}
}
Retrieves coupons from the account. If no parameters are specified, all coupons will be returned. You will need to make multiple API calls in order to retrieve the entire result set since this API performs result set pagination.
SDK Function Name: getCouponsByQuery
Parameter | Description | Location | Data Type | Required |
---|---|---|---|---|
coupon_query | Coupon query | body | CouponQuery | required |
_limit | The maximum number of records to return on this one API call. (Max 200)
Default: 100 |
query | integer | optional |
_offset | Pagination of the record set. Offset is a zero based index.
Default: 0 |
query | integer | optional |
_sort | The sort order of the coupons. See Sorting documentation for examples of using multiple values and sorting by ascending and descending.
Allowed Values
|
query | string | optional |
_expand | The object expansion to perform on the result. See documentation for examples | query | string | optional |
using System;
using System.Collections.Generic;
using System.Reflection;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;
namespace SdkSample.coupon
{
public class GetCouponsByQuery
{
/*
retrieves coupons by query. Can filter on specific coupons or return back all coupons. Support pagination.
A note about the coupon type below. Those are string literals representing coupons. This method is used UltraCart's
backend, and it uses a dropdown box for that value showing friendly descriptions of them.
It's not anticipated a merchant would need to query by coupon type, but in the event you do, here's the list of constants:
"BOGO limit L"
"Free shipping method Y"
"Free shipping method Y with purchase of items Z"
"Free shipping method Y with subtotal Z"
"Free shipping on item Z"
"Free X with purchase of Y dollars limit L"
"Free X with purchase of Y dollars limit L and shipping Z"
"Free X with purchase of Y limit L"
"Free X with purchase of Y limit L and free shipping"
"I Free X with every J purchase of Y limit L"
"I Free X with every J purchase of Y mix and match group limit L"
"Item X for Y with purchase of Z limit L"
"multiple X $ off item Z limit L"
"No discount"
"Tiered Dollar Off Subtotal"
"Tiered % off items Z limit L"
"Tiered $ off item Z limit L"
"Tiered Percent off shipping methods Y with subtotal Z"
"Tiered Percent Off Subtotal"
"X dollars off shipping method Y with purchase of items Z"
"X dollars off subtotal with purchase Y items"
"X $ for item Z limit L"
"X more loyalty cashback"
"X more loyalty points"
"X % off item Z and free shipping"
"X $ off item Z limit L"
"X % off item Z limit L"
"X % off msrp item Z limit L"
"X % off retail item Z limit L"
"X $ off shipping method Y"
"X % off shipping method Y"
"X $ off subtotal"
"X % off subtotal"
"X $ off subtotal and shipping"
"X % off subtotal free shipping method Y"
"X % off subtotal limit L"
"X off subtotal with purchase block of L item Y"
"X % off subtotal with purchase of item Y"
"X % off subtotal with purchase of Y"
"X $ off subtotal with Y $ purchase"
"X $ off subtotal with Y $ purchase and free shipping"
"X % off Y with purchase Z limit L"
"X % off Y with T purchase Z limit L"
"X percent more loyalty points"
"X $ shipping method Y with subtotal Z"
"X ? subtotal"
*/
public static void Execute()
{
Console.WriteLine("--- " + MethodBase.GetCurrentMethod()?.DeclaringType?.Name + " ---");
try
{
List<Coupon> coupons = new List<Coupon>();
int iteration = 1;
int offset = 0;
int limit = 200;
bool moreRecordsToFetch = true;
while (moreRecordsToFetch)
{
Console.WriteLine($"executing iteration {iteration}");
List<Coupon> chunkOfCoupons = GetCouponChunk(offset, limit);
coupons.AddRange(chunkOfCoupons);
offset += limit;
moreRecordsToFetch = chunkOfCoupons.Count == limit;
iteration++;
}
// Display the coupons
foreach (var coupon in coupons)
{
Console.WriteLine(coupon);
}
Console.WriteLine($"Total coupons retrieved: {coupons.Count}");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
Console.WriteLine(ex.StackTrace);
}
}
/// <summary>
/// Returns a chunk of coupons based on query parameters
/// </summary>
/// <param name="offset">Pagination offset</param>
/// <param name="limit">Maximum number of records to return</param>
/// <returns>List of matching coupons</returns>
public static List<Coupon> GetCouponChunk(int offset, int limit)
{
// Create coupon API instance using API key
CouponApi couponApi = new CouponApi(Constants.ApiKey);
CouponQuery query = new CouponQuery();
query.MerchantCode = "10OFF"; // supports partial matching
query.Description = "Saturday"; // supports partial matching
// query.CouponType = null; // see the note at the top of this sample.
// query.StartDtsBegin = DateTime.UtcNow.AddDays(-2000).ToString("yyyy-MM-ddTHH:mm:ssK"); // yes, that 2,000 days.
// query.StartDtsEnd = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssK");
// query.ExpirationDtsBegin = null;
// query.ExpirationDtsEnd = null;
// query.AffiliateOid = 0; // this requires an affiliate_oid. If you need help finding an affiliate's oid, contact support.
query.ExcludeExpired = true;
string expand = null; // coupons do not have expansions
string sort = "merchant_code"; // Possible sorts: "coupon_type", "merchant_code", "description", "start_dts", "expiration_dts", "quickbooks_code"
var apiResponse = couponApi.GetCouponsByQuery(query, limit, offset, sort, expand);
if (apiResponse.Coupons != null)
{
return apiResponse.Coupons;
}
return new List<Coupon>();
}
}
}
package coupon;
import com.ultracart.admin.v2.CouponApi;
import com.ultracart.admin.v2.models.Coupon;
import com.ultracart.admin.v2.models.CouponQuery;
import com.ultracart.admin.v2.models.CouponsResponse;
import com.ultracart.admin.v2.util.ApiException;
import common.Constants;
import java.util.ArrayList;
import java.util.List;
public class GetCouponsByQuery {
/*
retrieves coupons by query. Can filter on specific coupons or return back all coupons. Support pagination.
A note about the coupon type below. Those are string literals representing coupons. This method is used UltraCart's
backend, and it uses a dropdown box for that value showing friendly descriptions of them.
It's not anticipated a merchant would need to query by coupon type, but in the event you do, here's the list of constants:
(Full list of coupon type constants from original C# comment)
*/
public static void execute() {
try {
List<Coupon> coupons = new ArrayList<>();
int iteration = 1;
int offset = 0;
int limit = 200;
boolean moreRecordsToFetch = true;
while (moreRecordsToFetch) {
System.out.println("executing iteration " + iteration);
List<Coupon> chunkOfCoupons = getCouponChunk(offset, limit);
coupons.addAll(chunkOfCoupons);
offset += limit;
moreRecordsToFetch = chunkOfCoupons.size() == limit;
iteration++;
}
// Display the coupons
for (Coupon coupon : coupons) {
System.out.println(coupon);
}
System.out.println("Total coupons retrieved: " + coupons.size());
}
catch (ApiException ex) {
System.out.println("Error: " + ex.getMessage());
ex.printStackTrace();
}
}
/**
* Returns a chunk of coupons based on query parameters
*
* @param offset Pagination offset
* @param limit Maximum number of records to return
* @return List of matching coupons
*/
public static List<Coupon> getCouponChunk(int offset, int limit) throws ApiException {
// Create coupon API instance using API key
CouponApi couponApi = new CouponApi(Constants.API_KEY);
CouponQuery query = new CouponQuery();
query.setMerchantCode("10OFF"); // supports partial matching
query.setDescription("Saturday"); // supports partial matching
// query.setCouponType(null); // see the note at the top of this sample.
// query.setStartDtsBegin(Instant.now().minus(2000, ChronoUnit.DAYS).toString()); // yes, that 2,000 days.
// query.setStartDtsEnd(Instant.now().toString());
// query.setExpirationDtsBegin(null);
// query.setExpirationDtsEnd(null);
// query.setAffiliateOid(0); // this requires an affiliate_oid. If you need help finding an affiliate's oid, contact support.
query.setExcludeExpired(true);
String expand = null; // coupons do not have expansions
String sort = "merchant_code"; // Possible sorts: "coupon_type", "merchant_code", "description", "start_dts", "expiration_dts", "quickbooks_code"
CouponsResponse apiResponse = couponApi.getCouponsByQuery(query, limit, offset, sort, expand);
return apiResponse.getCoupons() != null ? apiResponse.getCoupons() : new ArrayList<>();
}
}
// Import API and UltraCart types
import { couponApi } from '../api.js';
import { DateTime } from 'luxon';
// Namespace-like structure using a class (TypeScript doesn't have namespaces like C#, but this mimics it)
export class GetCouponsByQuery {
/*
* Retrieves coupons by query. Can filter on specific coupons or return back all coupons. Supports pagination.
* A note about the coupon type below. Those are string literals representing coupons. This method is used in UltraCart's
* backend, and it uses a dropdown box for that value showing friendly descriptions of them.
*
* It's not anticipated a merchant would need to query by coupon type, but in the event you do, here's the list of constants:
* "BOGO limit L"
* "Free shipping method Y"
* "Free shipping method Y with purchase of items Z"
* "Free shipping method Y with subtotal Z"
* "Free shipping on item Z"
* "Free X with purchase of Y dollars limit L"
* "Free X with purchase of Y dollars limit L and shipping Z"
* "Free X with purchase of Y limit L"
* "Free X with purchase of Y limit L and free shipping"
* "I Free X with every J purchase of Y limit L"
* "I Free X with every J purchase of Y mix and match group limit L"
* "Item X for Y with purchase of Z limit L"
* "multiple X $ off item Z limit L"
* "No discount"
* "Tiered Dollar Off Subtotal"
* "Tiered % off items Z limit L"
* "Tiered $ off item Z limit L"
* "Tiered Percent off shipping methods Y with subtotal Z"
* "Tiered Percent Off Subtotal"
* "X dollars off shipping method Y with purchase of items Z"
* "X dollars off subtotal with purchase Y items"
* "X $ for item Z limit L"
* "X more loyalty cashback"
* "X more loyalty points"
* "X % off item Z and free shipping"
* "X $ off item Z limit L"
* "X % off item Z limit L"
* "X % off msrp item Z limit L"
* "X % off retail item Z limit L"
* "X $ off shipping method Y"
* "X % off shipping method Y"
* "X $ off subtotal"
* "X % off subtotal"
* "X $ off subtotal and shipping"
* "X % off subtotal free shipping method Y"
* "X % off subtotal limit L"
* "X off subtotal with purchase block of L item Y"
* "X % off subtotal with purchase of item Y"
* "X % off subtotal with purchase of Y"
* "X $ off subtotal with Y $ purchase"
* "X $ off subtotal with Y $ purchase and free shipping"
* "X % off Y with purchase Z limit L"
* "X % off Y with T purchase Z limit L"
* "X percent more loyalty points"
* "X $ shipping method Y with subtotal Z"
* "X ? subtotal"
*/
static async execute() {
console.log(`--- GetCouponsByQuery ---`);
try {
const coupons = [];
let iteration = 1;
let offset = 0;
const limit = 200;
let moreRecordsToFetch = true;
while (moreRecordsToFetch) {
console.log(`executing iteration ${iteration}`);
const chunkOfCoupons = await this.getCouponChunk(offset, limit);
coupons.push(...chunkOfCoupons);
offset += limit;
moreRecordsToFetch = chunkOfCoupons.length === limit;
iteration++;
}
// Display the coupons
for (const coupon of coupons) {
console.log(coupon);
}
console.log(`Total coupons retrieved: ${coupons.length}`);
} catch (ex) {
console.log(`Error: ${ex.message}`);
console.log(ex.stack);
}
}
/**
* Returns a chunk of coupons based on query parameters
* @param offset Pagination offset
* @param limit Maximum number of records to return
* @returns List of matching coupons
*/
static async getCouponChunk(offset, limit) {
// Create coupon API instance (assuming API key is handled in '../api')
const apiInstance = couponApi;
const query = {
merchant_code: "10OFF", // supports partial matching
description: "Saturday", // supports partial matching
// couponType: null, // see the note at the top of this sample
// startDtsBegin: DateTime.now().setZone('America/New_York').minus({ days: 2000 }).toISO(), // 2,000 days ago
// startDtsEnd: DateTime.now().setZone('America/New_York').toISO(),
// expirationDtsBegin: null,
// expirationDtsEnd: null,
// affiliateOid: 0, // this requires an affiliate_oid. If you need help finding an affiliate's oid, contact support
exclude_expired: true,
};
const expand = undefined; // coupons do not have expansions
const sort = "merchant_code"; // Possible sorts: "coupon_type", "merchant_code", "description", "start_dts", "expiration_dts", "quickbooks_code"
// UltraCart API call with parameters as an anonymous interface
const opts = {
_limit: limit,
_offset: offset,
_sort: sort,
_expand: expand,
};
const apiResponse = await new Promise((resolve, reject) => {
apiInstance.getCouponsByQuery(query, opts, function (error, data, response) {
if (error) {
reject(error);
} else {
resolve(data, response);
}
});
});
if (apiResponse.coupons) {
return apiResponse.coupons;
}
return [];
}
}
<?php
set_time_limit(3000); // pull all orders could take a long time.
ini_set('max_execution_time', 3000);
ini_set('display_errors', 1);
/*
retrieves coupons by query. Can filter on specific coupons or return back all coupons. Support pagination.
A note about the coupon type below. Those are string literals representing coupons. This method is used UltraCart's
backend, and it uses a dropdown box for that value showing friendly descriptions of them.
It's not anticipated a merchant would need to query by coupon type, but in the event you do, here's the list of constants:
"BOGO limit L"
"Free shipping method Y"
"Free shipping method Y with purchase of items Z"
"Free shipping method Y with subtotal Z"
"Free shipping on item Z"
"Free X with purchase of Y dollars limit L"
"Free X with purchase of Y dollars limit L and shipping Z"
"Free X with purchase of Y limit L"
"Free X with purchase of Y limit L and free shipping"
"I Free X with every J purchase of Y limit L"
"I Free X with every J purchase of Y mix and match group limit L"
"Item X for Y with purchase of Z limit L"
"multiple X $ off item Z limit L"
"No discount"
"Tiered Dollar Off Subtotal"
"Tiered % off items Z limit L"
"Tiered $ off item Z limit L"
"Tiered Percent off shipping methods Y with subtotal Z"
"Tiered Percent Off Subtotal"
"X dollars off shipping method Y with purchase of items Z"
"X dollars off subtotal with purchase Y items"
"X $ for item Z limit L"
"X more loyalty cashback"
"X more loyalty points"
"X % off item Z and free shipping"
"X $ off item Z limit L"
"X % off item Z limit L"
"X % off msrp item Z limit L"
"X % off retail item Z limit L"
"X $ off shipping method Y"
"X % off shipping method Y"
"X $ off subtotal"
"X % off subtotal"
"X $ off subtotal and shipping"
"X % off subtotal free shipping method Y"
"X % off subtotal limit L"
"X off subtotal with purchase block of L item Y"
"X % off subtotal with purchase of item Y"
"X % off subtotal with purchase of Y"
"X $ off subtotal with Y $ purchase"
"X $ off subtotal with Y $ purchase and free shipping"
"X % off Y with purchase Z limit L"
"X % off Y with T purchase Z limit L"
"X percent more loyalty points"
"X $ shipping method Y with subtotal Z"
"X ? subtotal"
*/
use ultracart\v2\api\CouponApi;
use ultracart\v2\models\CouponQuery;
require_once '../vendor/autoload.php';
require_once '../constants.php';
$coupon_api = CouponApi::usingApiKey(Constants::API_KEY);
function getCouponChunk(CouponApi $coupon_api, int $offset, int $limit): array
{
$query = new CouponQuery();
$query->setMerchantCode('10OFF'); // supports partial matching
$query->setDescription('Saturday'); // supports partial matching
// $query->setCouponType(null); // see the note at the top of this sample.
// $query->setStartDtsBegin(date('Y-m-d', strtotime('-2000 days')) . "T00:00:00+00:00"); // yes, that 2,000 days.
// $query->setStartDtsEnd(date('Y-m-d', time()) . "T00:00:00+00:00");
// $query->setExpirationDtsBegin(null);
// $query->setExpirationDtsEnd(null);
// $query->setAffiliateOid(0); // this requires an affiliate_oid. If you need help finding an affiliate's oid, contact support.
$query->setExcludeExpired(true);
$_expand = null; // coupons do not have expansions
$_sort = "merchant_code"; // Possible sorts: "coupon_type", "merchant_code", "description", "start_dts", "expiration_dts", "quickbooks_code"
$api_response = $coupon_api->getCouponsByQuery($query, $limit, $offset, $_sort, $_expand);
if($api_response->getCoupons() != null){
return $api_response->getCoupons();
}
return [];
}
$coupons = [];
$iteration = 1;
$offset = 0;
$limit = 200;
$more_records_to_fetch = true;
while( $more_records_to_fetch ){
echo "executing iteration " . $iteration . '<br>';
$chunk_of_coupons = getCouponChunk($coupon_api, $offset, $limit);
$coupons = array_merge($coupons, $chunk_of_coupons);
$offset = $offset + $limit;
$more_records_to_fetch = count($chunk_of_coupons) == $limit;
$iteration++;
}
// this could get verbose...
echo '<html lang="en"><body><pre>';
var_dump($coupons);
echo '</pre></body></html>';
from ultracart.apis import CouponApi
from ultracart.models import CouponQuery
from samples import api_client
# Initialize the API
coupon_api = CouponApi(api_client())
def get_coupon_chunk(coupon_api: CouponApi, offset: int, limit: int) -> list:
"""
Retrieve a chunk of coupons based on the specified query parameters.
Args:
coupon_api: The CouponApi instance
offset: Starting position for the query
limit: Maximum number of records to return
Returns:
List of coupon objects
"""
query = CouponQuery()
query.merchant_code = '10OFF' # supports partial matching
query.description = 'Saturday' # supports partial matching
# query.coupon_type = None # see the note at the top of the sample
# query.start_dts_begin = (datetime.now() - timedelta(days=2000)).strftime('%Y-%m-%dT00:00:00+00:00')
# query.start_dts_end = datetime.now().strftime('%Y-%m-%dT00:00:00+00:00')
# query.expiration_dts_begin = None
# query.expiration_dts_end = None
# query.affiliate_oid = 0 # this requires an affiliate_oid. Contact support for help finding an affiliate's oid
query.exclude_expired = True
expand = None # coupons do not have expansions
sort = "merchant_code" # Possible sorts: "coupon_type", "merchant_code", "description", "start_dts", "expiration_dts", "quickbooks_code"
api_response = coupon_api.get_coupons_by_query(query, limit=limit, offset=offset, sort=sort, expand=expand)
return api_response.coupons if api_response.coupons is not None else []
def main():
coupons = []
iteration = 1
offset = 0
limit = 200
more_records_to_fetch = True
while more_records_to_fetch:
print(f"executing iteration {iteration}")
chunk_of_coupons = get_coupon_chunk(coupon_api, offset, limit)
coupons.extend(chunk_of_coupons)
offset += limit
more_records_to_fetch = len(chunk_of_coupons) == limit
iteration += 1
print(coupons) # This could get verbose...
if __name__ == "__main__":
main()
require_relative '../constants'
require 'ultracart_api'
=begin
retrieves coupons by query. Can filter on specific coupons or return back all coupons. Support pagination.
A note about the coupon type below. Those are string literals representing coupons. This method is used UltraCart's
backend, and it uses a dropdown box for that value showing friendly descriptions of them.
It's not anticipated a merchant would need to query by coupon type, but in the event you do, here's the list of constants:
"BOGO limit L"
"Free shipping method Y"
"Free shipping method Y with purchase of items Z"
"Free shipping method Y with subtotal Z"
"Free shipping on item Z"
"Free X with purchase of Y dollars limit L"
"Free X with purchase of Y dollars limit L and shipping Z"
"Free X with purchase of Y limit L"
"Free X with purchase of Y limit L and free shipping"
"I Free X with every J purchase of Y limit L"
"I Free X with every J purchase of Y mix and match group limit L"
"Item X for Y with purchase of Z limit L"
"multiple X $ off item Z limit L"
"No discount"
"Tiered Dollar Off Subtotal"
"Tiered % off items Z limit L"
"Tiered $ off item Z limit L"
"Tiered Percent off shipping methods Y with subtotal Z"
"Tiered Percent Off Subtotal"
"X dollars off shipping method Y with purchase of items Z"
"X dollars off subtotal with purchase Y items"
"X $ for item Z limit L"
"X more loyalty cashback"
"X more loyalty points"
"X % off item Z and free shipping"
"X $ off item Z limit L"
"X % off item Z limit L"
"X % off msrp item Z limit L"
"X % off retail item Z limit L"
"X $ off shipping method Y"
"X % off shipping method Y"
"X $ off subtotal"
"X % off subtotal"
"X $ off subtotal and shipping"
"X % off subtotal free shipping method Y"
"X % off subtotal limit L"
"X off subtotal with purchase block of L item Y"
"X % off subtotal with purchase of item Y"
"X % off subtotal with purchase of Y"
"X $ off subtotal with Y $ purchase"
"X $ off subtotal with Y $ purchase and free shipping"
"X % off Y with purchase Z limit L"
"X % off Y with T purchase Z limit L"
"X percent more loyalty points"
"X $ shipping method Y with subtotal Z"
"X ? subtotal"
=end
def get_coupon_chunk(coupon_api, offset, limit)
query = UltracartClient::CouponQuery.new
query.merchant_code = '10OFF' # supports partial matching
query.description = 'Saturday' # supports partial matching
# query.coupon_type = nil # see the note at the top of this sample.
# query.start_dts_begin = (Date.today - 2000).strftime('%Y-%m-%d') + 'T00:00:00+00:00' # yes, that 2,000 days.
# query.start_dts_end = Date.today.strftime('%Y-%m-%d') + 'T00:00:00+00:00'
# query.expiration_dts_begin = nil
# query.expiration_dts_end = nil
# query.affiliate_oid = 0 # this requires an affiliate_oid. If you need help finding an affiliate's oid, contact support.
query.exclude_expired = true
# coupons do not have expansions
# Possible sorts: "coupon_type", "merchant_code", "description", "start_dts", "expiration_dts", "quickbooks_code"
opts = {
_expand: nil,
_sort: 'merchant_code'
}
api_response = coupon_api.get_coupons_by_query(query, limit, offset, opts)
return api_response.coupons if api_response.coupons
[]
end
coupon_api = UltracartClient::CouponApi.new_using_api_key(Constants::API_KEY)
coupons = []
iteration = 1
offset = 0
limit = 200
more_records_to_fetch = true
while more_records_to_fetch
puts "executing iteration #{iteration}"
chunk_of_coupons = get_coupon_chunk(coupon_api, offset, limit)
coupons.concat(chunk_of_coupons)
offset += limit
more_records_to_fetch = chunk_of_coupons.length == limit
iteration += 1
end
puts coupons.inspect
// Import API and UltraCart types
import { couponApi } from '../api';
import { Coupon, CouponQuery } from 'ultracart_rest_api_v2_typescript';
import { DateTime } from 'luxon';
// Namespace-like structure using a class (TypeScript doesn't have namespaces like C#, but this mimics it)
export class GetCouponsByQuery {
/*
* Retrieves coupons by query. Can filter on specific coupons or return back all coupons. Supports pagination.
* A note about the coupon type below. Those are string literals representing coupons. This method is used in UltraCart's
* backend, and it uses a dropdown box for that value showing friendly descriptions of them.
*
* It's not anticipated a merchant would need to query by coupon type, but in the event you do, here's the list of constants:
* "BOGO limit L"
* "Free shipping method Y"
* "Free shipping method Y with purchase of items Z"
* "Free shipping method Y with subtotal Z"
* "Free shipping on item Z"
* "Free X with purchase of Y dollars limit L"
* "Free X with purchase of Y dollars limit L and shipping Z"
* "Free X with purchase of Y limit L"
* "Free X with purchase of Y limit L and free shipping"
* "I Free X with every J purchase of Y limit L"
* "I Free X with every J purchase of Y mix and match group limit L"
* "Item X for Y with purchase of Z limit L"
* "multiple X $ off item Z limit L"
* "No discount"
* "Tiered Dollar Off Subtotal"
* "Tiered % off items Z limit L"
* "Tiered $ off item Z limit L"
* "Tiered Percent off shipping methods Y with subtotal Z"
* "Tiered Percent Off Subtotal"
* "X dollars off shipping method Y with purchase of items Z"
* "X dollars off subtotal with purchase Y items"
* "X $ for item Z limit L"
* "X more loyalty cashback"
* "X more loyalty points"
* "X % off item Z and free shipping"
* "X $ off item Z limit L"
* "X % off item Z limit L"
* "X % off msrp item Z limit L"
* "X % off retail item Z limit L"
* "X $ off shipping method Y"
* "X % off shipping method Y"
* "X $ off subtotal"
* "X % off subtotal"
* "X $ off subtotal and shipping"
* "X % off subtotal free shipping method Y"
* "X % off subtotal limit L"
* "X off subtotal with purchase block of L item Y"
* "X % off subtotal with purchase of item Y"
* "X % off subtotal with purchase of Y"
* "X $ off subtotal with Y $ purchase"
* "X $ off subtotal with Y $ purchase and free shipping"
* "X % off Y with purchase Z limit L"
* "X % off Y with T purchase Z limit L"
* "X percent more loyalty points"
* "X $ shipping method Y with subtotal Z"
* "X ? subtotal"
*/
public static async execute(): Promise<void> {
console.log(`--- GetCouponsByQuery ---`);
try {
const coupons: Coupon[] = [];
let iteration = 1;
let offset = 0;
const limit = 200;
let moreRecordsToFetch = true;
while (moreRecordsToFetch) {
console.log(`executing iteration ${iteration}`);
const chunkOfCoupons = await this.getCouponChunk(offset, limit);
coupons.push(...chunkOfCoupons);
offset += limit;
moreRecordsToFetch = chunkOfCoupons.length === limit;
iteration++;
}
// Display the coupons
for (const coupon of coupons) {
console.log(coupon);
}
console.log(`Total coupons retrieved: ${coupons.length}`);
} catch (ex) {
console.log(`Error: ${(ex as Error).message}`);
console.log((ex as Error).stack);
}
}
/**
* Returns a chunk of coupons based on query parameters
* @param offset Pagination offset
* @param limit Maximum number of records to return
* @returns List of matching coupons
*/
private static async getCouponChunk(offset: number, limit: number): Promise<Coupon[]> {
// Create coupon API instance (assuming API key is handled in '../api')
const apiInstance = couponApi;
const query: CouponQuery = {
merchant_code: "10OFF", // supports partial matching
description: "Saturday", // supports partial matching
// couponType: null, // see the note at the top of this sample
// startDtsBegin: DateTime.now().setZone('America/New_York').minus({ days: 2000 }).toISO(), // 2,000 days ago
// startDtsEnd: DateTime.now().setZone('America/New_York').toISO(),
// expirationDtsBegin: null,
// expirationDtsEnd: null,
// affiliateOid: 0, // this requires an affiliate_oid. If you need help finding an affiliate's oid, contact support
exclude_expired: true,
};
const expand: string | undefined = undefined; // coupons do not have expansions
const sort = "merchant_code"; // Possible sorts: "coupon_type", "merchant_code", "description", "start_dts", "expiration_dts", "quickbooks_code"
// UltraCart API call with parameters as an anonymous interface
const apiResponse = await apiInstance.getCouponsByQuery({
couponQuery: query,
limit: limit,
offset: offset,
sort: sort,
expand: expand,
});
if (apiResponse.coupons) {
return apiResponse.coupons;
}
return [];
}
}
Delete a coupon on the UltraCart account.
SDK Function Name: deleteCoupon
Parameter | Description | Location | Data Type | Required |
---|---|---|---|---|
coupon_oid | The coupon_oid to delete. | path | integer (int32) | required |
using System;
using System.Reflection;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;
namespace SdkSample.coupon
{
public class DeleteCoupon
{
/// <summary>
/// Deletes a specific coupon using the UltraCart API
/// </summary>
public static void Execute()
{
Console.WriteLine("--- " + MethodBase.GetCurrentMethod()?.DeclaringType?.Name + " ---");
CouponApi couponApi = new CouponApi(Constants.ApiKey);
string expand = null; // coupons do not have expansions.
Coupon coupon = new Coupon();
coupon.MerchantCode = Guid.NewGuid().ToString("N").Substring(0, 8);
coupon.Description = "Test coupon for sdk_sample.coupon.DeleteCoupon";
coupon.AmountOffSubtotal = new CouponAmountOffSubtotal("USD", 0.01m); // one penny discount.
CouponResponse couponResponse = couponApi.InsertCoupon(coupon, expand);
coupon = couponResponse.Coupon;
Console.WriteLine("Created the following temporary coupon:");
Console.WriteLine($"Coupon OID: {coupon.CouponOid}");
Console.WriteLine($"Coupon Type: {coupon.CouponType}");
Console.WriteLine($"Coupon Description: {coupon.Description}");
int couponOid = coupon.CouponOid;
// Delete the coupon
couponApi.DeleteCoupon(couponOid);
Console.WriteLine($"Successfully deleted coupon with ID: {couponOid}");
}
}
}
package coupon;
import com.ultracart.admin.v2.CouponApi;
import com.ultracart.admin.v2.models.Coupon;
import com.ultracart.admin.v2.models.CouponAmountOffSubtotal;
import com.ultracart.admin.v2.models.CouponResponse;
import com.ultracart.admin.v2.util.ApiException;
import common.Constants;
import java.math.BigDecimal;
import java.util.UUID;
public class DeleteCoupon {
/**
* Deletes a specific coupon using the UltraCart API
*/
public static void execute() {
System.out.println("--- " + DeleteCoupon.class.getSimpleName() + " ---");
CouponApi couponApi = new CouponApi(Constants.API_KEY);
String expand = null; // coupons do not have expansions.
Coupon coupon = new Coupon();
coupon.setMerchantCode(UUID.randomUUID().toString().substring(0, 8));
coupon.setDescription("Test coupon for sdk_sample.coupon.DeleteCoupon");
CouponAmountOffSubtotal amountOff = new CouponAmountOffSubtotal();
amountOff.setCurrencyCode("USD");
amountOff.setDiscountAmount(new BigDecimal("0.01")); // one penny discount
coupon.setAmountOffSubtotal(amountOff);
try {
CouponResponse couponResponse = couponApi.insertCoupon(coupon, expand);
coupon = couponResponse.getCoupon();
System.out.println("Created the following temporary coupon:");
System.out.println("Coupon OID: " + coupon.getCouponOid());
System.out.println("Coupon Type: " + coupon.getCouponType());
System.out.println("Coupon Description: " + coupon.getDescription());
int couponOid = coupon.getCouponOid();
// Delete the coupon
couponApi.deleteCoupon(couponOid);
System.out.println("Successfully deleted coupon with ID: " + couponOid);
} catch (ApiException e) {
System.err.println("Error occurred: " + e.getMessage());
e.printStackTrace();
}
}
}
import {couponApi} from '../api.js';
export class DeleteCoupon {
/**
* Deletes a specific coupon using the UltraCart API
*/
static async execute() {
console.log("--- DeleteCoupon ---");
const expand = undefined; // coupons do not have expansions.
const coupon = {
merchant_code: this.generateGuid().substring(0, 8),
description: "Test coupon for sdk_sample.coupon.DeleteCoupon",
amount_off_subtotal: {currency_code: "USD", discount_amount: 0.01}
}; // one penny discount.
const couponResponse = await new Promise((resolve, reject) => {
couponApi.insertCoupon(coupon, {_expand: expand}, function (error, data, response) {
if (error) {
reject(error);
} else {
resolve(data, response);
}
});
});
const createdCoupon = couponResponse.coupon;
console.log("Created the following temporary coupon:");
console.log(`Coupon OID: ${createdCoupon.coupon_oid}`);
console.log(`Coupon Type: ${createdCoupon.coupon_type}`);
console.log(`Coupon Description: ${createdCoupon.description}`);
const couponOid = createdCoupon.coupon_oid;
// Delete the coupon
await new Promise((resolve, reject) => {
couponApi.deleteCoupon(couponOid, function (error, data, response) {
if (error) {
reject(error);
} else {
resolve(data, response);
}
});
});
console.log(`Successfully deleted coupon with ID: ${couponOid}`);
}
// Helper method to generate a GUID-like string since TypeScript doesn't have Guid.NewGuid()
static generateGuid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
const r = Math.random() * 16 | 0;
const v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
}).replace(/-/g, '');
}
}
<?php
use ultracart\v2\api\CouponApi;
require_once '../vendor/autoload.php';
$coupon_api = CouponApi::usingApiKey(Constants::API_KEY);
$coupon_oid = 123456789;
$coupon_api->deleteCoupon($coupon_oid);
from ultracart.apis import CouponApi
from samples import api_client
coupon_api = CouponApi(api_client())
coupon_oid = 123456789
coupon_api.delete_coupon(coupon_oid)
require_relative '../constants'
require 'ultracart_api'
coupon_api = UltracartClient::CouponApi.new_using_api_key(Constants::API_KEY)
coupon_oid = 123456789
coupon_api.delete_coupon(coupon_oid)
import {couponApi} from '../api';
import {
Coupon,
CouponAmountOffSubtotal,
CouponResponse
} from 'ultracart_rest_api_v2_typescript';
export class DeleteCoupon {
/**
* Deletes a specific coupon using the UltraCart API
*/
public static async execute(): Promise<void> {
console.log("--- DeleteCoupon ---");
const expand: string | undefined = undefined; // coupons do not have expansions.
const coupon: Coupon = {
merchant_code: this.generateGuid().substring(0, 8),
description: "Test coupon for sdk_sample.coupon.DeleteCoupon",
amount_off_subtotal: {currency_code: "USD", discount_amount: 0.01} as CouponAmountOffSubtotal
}; // one penny discount.
const couponResponse: CouponResponse = await couponApi.insertCoupon({coupon: coupon, expand: expand});
const createdCoupon: Coupon = couponResponse.coupon!;
console.log("Created the following temporary coupon:");
console.log(`Coupon OID: ${createdCoupon.coupon_oid}`);
console.log(`Coupon Type: ${createdCoupon.coupon_type}`);
console.log(`Coupon Description: ${createdCoupon.description}`);
const couponOid: number = createdCoupon.coupon_oid!;
// Delete the coupon
await couponApi.deleteCoupon({couponOid: couponOid});
console.log(`Successfully deleted coupon with ID: ${couponOid}`);
}
// Helper method to generate a GUID-like string since TypeScript doesn't have Guid.NewGuid()
private static generateGuid(): string {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
const r = Math.random() * 16 | 0;
const v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
}).replace(/-/g, '');
}
}
Retrieves a single coupon using the specified coupon profile oid.
SDK Function Name: getCoupon
Parameter | Description | Location | Data Type | Required |
---|---|---|---|---|
coupon_oid | The coupon oid to retrieve. | path | integer (int32) | required |
_expand | The object expansion to perform on the result. See documentation for examples | query | string | optional |
using System;
using System.Reflection;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;
namespace SdkSample.coupon
{
public class GetCoupon
{
public static void Execute()
{
Console.WriteLine("--- " + MethodBase.GetCurrentMethod()?.DeclaringType?.Name + " ---");
try
{
CouponApi couponApi = new CouponApi(Constants.ApiKey);
String merchantCode = Guid.NewGuid().ToString("N").Substring(0, 8);
// Now create the coupon and ensure it exists.
Coupon coupon = new Coupon();
coupon.MerchantCode = merchantCode;
coupon.Description = "Test coupon for GetCoupon";
coupon.AmountOffSubtotal = new CouponAmountOffSubtotal("USD", 0.01m); // one penny discount.
CouponResponse couponResponse = couponApi.InsertCoupon(coupon);
coupon = couponResponse.Coupon;
Console.WriteLine("Created the following temporary coupon:");
Console.WriteLine($"Coupon OID: {coupon.MerchantCode}");
Console.WriteLine($"Coupon Type: {coupon.CouponType}");
Console.WriteLine($"Coupon Description: {coupon.Description}");
couponResponse = couponApi.GetCoupon(coupon.CouponOid);
Coupon copyOfCoupon = couponResponse.Coupon;
Console.WriteLine("GetCoupon returned the following coupon:");
Console.WriteLine($"Coupon OID: {copyOfCoupon.MerchantCode}");
Console.WriteLine($"Coupon Type: {copyOfCoupon.CouponType}");
Console.WriteLine($"Coupon Description: {copyOfCoupon.Description}");
// Delete the coupon
couponApi.DeleteCoupon(coupon.CouponOid);
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
Console.WriteLine(ex.StackTrace);
}
}
}
}
package coupon;
import com.ultracart.admin.v2.CouponApi;
import com.ultracart.admin.v2.models.Coupon;
import com.ultracart.admin.v2.models.CouponAmountOffSubtotal;
import com.ultracart.admin.v2.models.CouponResponse;
import com.ultracart.admin.v2.util.ApiException;
import common.Constants;
import java.math.BigDecimal;
import java.util.UUID;
public class GetCoupon {
public static void execute() {
try {
CouponApi couponApi = new CouponApi(Constants.API_KEY);
String merchantCode = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 8);
// Now create the coupon and ensure it exists.
Coupon coupon = new Coupon();
coupon.setMerchantCode(merchantCode);
coupon.setDescription("Test coupon for GetCoupon");
coupon.setAmountOffSubtotal(new CouponAmountOffSubtotal()); // one penny discount.
coupon.getAmountOffSubtotal().setDiscountAmount(BigDecimal.valueOf(.01));
coupon.getAmountOffSubtotal().setCurrencyCode("USD");
CouponResponse couponResponse = couponApi.insertCoupon(coupon, null);
coupon = couponResponse.getCoupon();
System.out.println("Created the following temporary coupon:");
System.out.println("Coupon OID: " + coupon.getMerchantCode());
System.out.println("Coupon Type: " + coupon.getCouponType());
System.out.println("Coupon Description: " + coupon.getDescription());
couponResponse = couponApi.getCoupon(coupon.getCouponOid(), null);
Coupon copyOfCoupon = couponResponse.getCoupon();
System.out.println("GetCoupon returned the following coupon:");
System.out.println("Coupon OID: " + copyOfCoupon.getMerchantCode());
System.out.println("Coupon Type: " + copyOfCoupon.getCouponType());
System.out.println("Coupon Description: " + copyOfCoupon.getDescription());
// Delete the coupon
couponApi.deleteCoupon(coupon.getCouponOid());
}
catch (ApiException ex) {
System.out.println("Error: " + ex.getMessage());
ex.printStackTrace();
}
}
}
import { couponApi } from '../api.js';
export class GetCoupon {
static async execute() {
console.log("--- GetCoupon ---");
try {
const merchantCode = this.generateGuid().substring(0, 8);
// Now create the coupon and ensure it exists.
const coupon = {
merchant_code: merchantCode,
description: "Test coupon for GetCoupon",
amount_off_subtotal: { currency_code: "USD", discount_amount: 0.01 }
}; // one penny discount.
const couponResponse = await new Promise((resolve, reject) => {
couponApi.insertCoupon(coupon, function (error, data, response) {
if (error) {
reject(error);
} else {
resolve(data, response);
}
});
});
const createdCoupon = couponResponse.coupon;
console.log("Created the following temporary coupon:");
console.log(`Coupon OID: ${createdCoupon.coupon_oid}`);
console.log(`Coupon Type: ${createdCoupon.coupon_type}`);
console.log(`Coupon Description: ${createdCoupon.description}`);
const retrievedResponse = await new Promise((resolve, reject) => {
couponApi.getCoupon(createdCoupon.coupon_oid, function (error, data, response) {
if (error) {
reject(error);
} else {
resolve(data, response);
}
});
});
const copyOfCoupon = retrievedResponse.coupon;
console.log("GetCoupon returned the following coupon:");
console.log(`Coupon OID: ${copyOfCoupon.coupon_oid}`);
console.log(`Coupon Type: ${copyOfCoupon.coupon_type}`);
console.log(`Coupon Description: ${copyOfCoupon.description}`);
// Delete the coupon
await new Promise((resolve, reject) => {
couponApi.deleteCoupon(createdCoupon.coupon_oid, function (error, data, response) {
if (error) {
reject(error);
} else {
resolve(data, response);
}
});
});
} catch (ex) {
console.log(`Error: ${ex.message}`);
console.log(ex.stack);
}
}
// Helper method to generate a GUID-like string since TypeScript doesn't have Guid.NewGuid()
static generateGuid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
const r = Math.random() * 16 | 0;
const v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
}).replace(/-/g, '');
}
}
<?php
use ultracart\v2\api\CouponApi;
require_once '../vendor/autoload.php';
$coupon_api = CouponApi::usingApiKey(Constants::API_KEY);
$coupon_oid = 123456789;
$_expand = null; // coupons do not have expansions
$api_response = $coupon_api->getCoupon($coupon_oid, $_expand);
echo '<html lang="en"><body><pre>';
var_dump($api_response);
echo '</pre></body></html>';
from ultracart.apis import CouponApi
from samples import api_client
coupon_api = CouponApi(api_client())
coupon_oid = 123456789
expand = None # coupons do not have expansions
api_response = coupon_api.get_coupon(coupon_oid, expand=expand)
print(api_response)
require_relative '../constants'
require 'ultracart_api'
coupon_api = UltracartClient::CouponApi.new_using_api_key(Constants::API_KEY)
coupon_oid = 123456789
# coupons do not have expansions
api_response = coupon_api.get_coupon(coupon_oid, { _expand: nil })
puts api_response.inspect
import { couponApi } from '../api';
import { Coupon, CouponAmountOffSubtotal, CouponResponse } from 'ultracart_rest_api_v2_typescript';
export class GetCoupon {
public static async execute(): Promise<void> {
console.log("--- GetCoupon ---");
try {
const merchantCode: string = this.generateGuid().substring(0, 8);
// Now create the coupon and ensure it exists.
const coupon: Coupon = {
merchant_code: merchantCode,
description: "Test coupon for GetCoupon",
amount_off_subtotal: { currency_code: "USD", discount_amount: 0.01 } as CouponAmountOffSubtotal
}; // one penny discount.
const couponResponse: CouponResponse = await couponApi.insertCoupon({coupon: coupon});
const createdCoupon: Coupon = couponResponse.coupon!;
console.log("Created the following temporary coupon:");
console.log(`Coupon OID: ${createdCoupon.coupon_oid}`);
console.log(`Coupon Type: ${createdCoupon.coupon_type}`);
console.log(`Coupon Description: ${createdCoupon.description}`);
const retrievedResponse: CouponResponse = await couponApi.getCoupon({couponOid: createdCoupon.coupon_oid!});
const copyOfCoupon: Coupon = retrievedResponse.coupon!;
console.log("GetCoupon returned the following coupon:");
console.log(`Coupon OID: ${copyOfCoupon.coupon_oid}`);
console.log(`Coupon Type: ${copyOfCoupon.coupon_type}`);
console.log(`Coupon Description: ${copyOfCoupon.description}`);
// Delete the coupon
await couponApi.deleteCoupon({couponOid: createdCoupon.coupon_oid!});
} catch (ex: any) {
console.log(`Error: ${ex.message}`);
console.log(ex.stack);
}
}
// Helper method to generate a GUID-like string since TypeScript doesn't have Guid.NewGuid()
private static generateGuid(): string {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
const r = Math.random() * 16 | 0;
const v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
}).replace(/-/g, '');
}
}
Update a coupon on the UltraCart account.
SDK Function Name: updateCoupon
Parameter | Description | Location | Data Type | Required |
---|---|---|---|---|
coupon | Coupon to update | body | Coupon | required |
coupon_oid | The coupon_oid to update. | path | integer (int32) | required |
_expand | The object expansion to perform on the result. See documentation for examples | query | string | optional |
using System;
using System.Reflection;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;
namespace SdkSample.coupon
{
public class UpdateCoupon
{
public static void Execute()
{
Console.WriteLine("--- " + MethodBase.GetCurrentMethod()?.DeclaringType?.Name + " ---");
try
{
// Create coupon API instance using API key
CouponApi couponApi = new CouponApi(Constants.ApiKey);
String merchantCode = Guid.NewGuid().ToString("N").Substring(0, 8);
// Now create the coupon and ensure it exists.
Coupon coupon = new Coupon();
coupon.MerchantCode = merchantCode;
coupon.Description = "Test coupon for GetCoupon";
coupon.AmountOffSubtotal = new CouponAmountOffSubtotal("USD", 0.01m); // one penny discount.
CouponResponse couponResponse = couponApi.InsertCoupon(coupon);
coupon = couponResponse.Coupon;
// update the coupon. this can be difficult given the complexity of coupons. see insertCoupon sample for details.
coupon.ExpirationDts = DateTime.UtcNow.AddDays(90).ToString("yyyy-MM-ddTHH:mm:ssK");
var updatedResponse = couponApi.UpdateCoupon(coupon.CouponOid, coupon);
Coupon updatedCoupon = updatedResponse.Coupon;
// Display the updated coupon
Console.WriteLine(updatedCoupon);
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
Console.WriteLine(ex.StackTrace);
}
}
}
}
package coupon;
import com.ultracart.admin.v2.CouponApi;
import com.ultracart.admin.v2.models.Coupon;
import com.ultracart.admin.v2.models.CouponAmountOffSubtotal;
import com.ultracart.admin.v2.models.CouponResponse;
import com.ultracart.admin.v2.util.ApiException;
import common.Constants;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.UUID;
public class UpdateCoupon {
public static void Execute() {
System.out.println("--- " + UpdateCoupon.class.getSimpleName() + " ---");
try {
// Create coupon API instance using API key
CouponApi couponApi = new CouponApi(Constants.API_KEY);
String merchantCode = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 8);
// Now create the coupon and ensure it exists.
Coupon coupon = new Coupon();
coupon.setMerchantCode(merchantCode);
coupon.setDescription("Test coupon for GetCoupon");
coupon.setAmountOffSubtotal(new CouponAmountOffSubtotal()); // one penny discount.
coupon.getAmountOffSubtotal().setDiscountAmount(BigDecimal.valueOf(.01));
coupon.getAmountOffSubtotal().setCurrencyCode("USD");
CouponResponse couponResponse = couponApi.insertCoupon(coupon, null);
coupon = couponResponse.getCoupon();
// update the coupon. this can be difficult given the complexity of coupons. see insertCoupon sample for details.
coupon.setExpirationDts(Instant.now().plus(90, ChronoUnit.DAYS).toString());
CouponResponse updatedResponse = couponApi.updateCoupon(coupon.getCouponOid(), coupon, null);
Coupon updatedCoupon = updatedResponse.getCoupon();
// Display the updated coupon
System.out.println(updatedCoupon);
}
catch (ApiException ex) {
System.out.println("Error: " + ex.getMessage());
ex.printStackTrace();
}
}
}
// Import API and UltraCart types
import { couponApi } from '../api.js';
import { DateTime } from 'luxon';
// Namespace-like structure using a class
export class UpdateCoupon {
static async execute() {
console.log(`--- UpdateCoupon ---`);
try {
// Generate a random 8-character merchant code (replacing GUID)
const merchantCode = Math.random().toString(36).substring(2, 10);
// Create the coupon and ensure it exists
const coupon = {
merchant_code: merchantCode,
description: "Test coupon for GetCoupon",
amount_off_subtotal: {
currency: "USD",
discountAmount: 0.01, // one penny discount, decimal becomes number
},
};
// Insert the coupon
const couponResponse = await new Promise((resolve, reject) => {
couponApi.insertCoupon(coupon, function (error, data, response) {
if (error) {
reject(error);
} else {
resolve(data, response);
}
});
});
const createdCoupon = couponResponse.coupon;
if (!createdCoupon?.coupon_oid) {
throw new Error("Failed to create coupon; no OID returned");
}
// Update the coupon. This can be difficult given the complexity of coupons. See InsertCoupon sample for details.
const updatedCouponData = {
...createdCoupon,
expiration_dts: DateTime.now()
.setZone('America/New_York')
.plus({ days: 90 })
.toISO(), // 90 days from now in ISO8601 format
};
// Update the coupon
const updatedResponse = await new Promise((resolve, reject) => {
couponApi.updateCoupon(createdCoupon.coupon_oid, updatedCouponData, function (error, data, response) {
if (error) {
reject(error);
} else {
resolve(data, response);
}
});
});
const updatedCoupon = updatedResponse.coupon;
// Display the updated coupon
console.log(updatedCoupon);
} catch (ex) {
console.log(`Error: ${ex.message}`);
console.log(ex.stack);
}
}
}
<?php
use ultracart\v2\api\CouponApi;
require_once '../vendor/autoload.php';
$coupon_api = CouponApi::usingApiKey(Constants::API_KEY);
$coupon_oid = 123456789;
$_expand = null; // coupons do not have expansions
$api_response = $coupon_api->getCoupon($coupon_oid, $_expand);
$coupon = $api_response->getCoupon();
// update the coupon. this can be difficult given the complexity of coupons. see insertCoupon sample for details.
$coupon->setExpirationDts(date('Y-m-d', strtotime('90 days')) . "T00:00:00+00:00");
$api_response = $coupon_api->updateCoupon($coupon_oid, $coupon, $_expand);
$updated_coupon = $api_response->getCoupon();
echo '<html lang="en"><body><pre>';
var_dump($updated_coupon);
echo '</pre></body></html>';
from ultracart.apis import CouponApi
from samples import api_client
from datetime import datetime, timedelta
coupon_api = CouponApi(api_client())
coupon_oid = 123456789
expand = None # coupons do not have expansions
api_response = coupon_api.get_coupon(coupon_oid, expand=expand)
coupon = api_response.coupon
# update the coupon. this can be difficult given the complexity of coupons. see insertCoupon sample for details.
expiration_date = (datetime.now() + timedelta(days=90)).strftime('%Y-%m-%dT00:00:00+00:00')
coupon.expiration_dts = expiration_date
api_response = coupon_api.update_coupon(coupon_oid, coupon, expand=expand)
updated_coupon = api_response.coupon
print(updated_coupon)
require 'ultracart_api'
require_relative '../constants'
# Initialize the coupon API
coupon_api = UltracartClient::CouponApi.new_using_api_key(Constants::API_KEY)
coupon_oid = 123456789
# coupons do not have expansions
api_response = coupon_api.get_coupon(coupon_oid, {_expand: nil})
coupon = api_response.coupon
# update the coupon. this can be difficult given the complexity of coupons. see insertCoupon sample for details.
coupon.expiration_dts = (Date.today + 90).strftime('%Y-%m-%d') + 'T00:00:00+00:00'
api_response = coupon_api.update_coupon(coupon_oid, coupon, {_expand: nil})
updated_coupon = api_response.coupon
puts updated_coupon
// Import API and UltraCart types
import { couponApi } from '../api';
import { Coupon, CouponAmountOffSubtotal, CouponResponse } from 'ultracart_rest_api_v2_typescript';
import { DateTime } from 'luxon';
// Namespace-like structure using a class
export class UpdateCoupon {
public static async execute(): Promise<void> {
console.log(`--- UpdateCoupon ---`);
try {
// Generate a random 8-character merchant code (replacing GUID)
const merchantCode = Math.random().toString(36).substring(2, 10);
// Create the coupon and ensure it exists
const coupon: Coupon = {
merchant_code: merchantCode,
description: "Test coupon for GetCoupon",
amount_off_subtotal: {
currency: "USD",
discountAmount: 0.01, // one penny discount, decimal becomes number
} as CouponAmountOffSubtotal,
};
// Insert the coupon
const couponResponse = await couponApi.insertCoupon({
coupon: coupon,
});
const createdCoupon = couponResponse.coupon;
if (!createdCoupon?.coupon_oid) {
throw new Error("Failed to create coupon; no OID returned");
}
// Update the coupon. This can be difficult given the complexity of coupons. See InsertCoupon sample for details.
const updatedCouponData: Coupon = {
...createdCoupon,
expiration_dts: DateTime.now()
.setZone('America/New_York')
.plus({ days: 90 })
.toISO(), // 90 days from now in ISO8601 format
};
// Update the coupon
const updatedResponse = await couponApi.updateCoupon({
couponOid: createdCoupon.coupon_oid,
coupon: updatedCouponData,
});
const updatedCoupon = updatedResponse.coupon;
// Display the updated coupon
console.log(updatedCoupon);
} catch (ex) {
console.log(`Error: ${(ex as Error).message}`);
console.log((ex as Error).stack);
}
}
}
Generate one time codes for a coupon
SDK Function Name: generateCouponCodes
Parameter | Description | Location | Data Type | Required |
---|---|---|---|---|
coupon_oid | The coupon oid to generate codes. | path | integer (int32) | required |
coupon_codes_request | Coupon code generation parameters | body | CouponCodesRequest | required |
using System;
using System.Reflection;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;
namespace SdkSample.coupon
{
public class GenerateCouponCodes
{
public static void Execute()
{
Console.WriteLine("--- " + MethodBase.GetCurrentMethod()?.DeclaringType?.Name + " ---");
try
{
// Create coupon API instance using API key
CouponApi couponApi = new CouponApi(Constants.ApiKey);
String merchantCode = Guid.NewGuid().ToString("N").Substring(0, 8);
// Now create the coupon and ensure it exists.
Coupon coupon = new Coupon();
coupon.MerchantCode = merchantCode;
coupon.Description = "Test coupon for GetCoupon";
coupon.AmountOffSubtotal = new CouponAmountOffSubtotal("USD", 0.01m); // one penny discount.
CouponResponse couponResponse = couponApi.InsertCoupon(coupon);
coupon = couponResponse.Coupon;
CouponCodesRequest codesRequest = new CouponCodesRequest();
codesRequest.Quantity = 5; // give me 5 codes.
codesRequest.ExpirationDts = DateTime.UtcNow.AddDays(90).ToString("yyyy-MM-ddTHH:mm:ssK"); // do you want the codes to expire?
// codesRequest.ExpirationSeconds = null; // also an option for short-lived coupons
var apiResponse = couponApi.GenerateCouponCodes(coupon.CouponOid, codesRequest);
var couponCodes = apiResponse.CouponCodes;
// Display generated coupon codes
Console.WriteLine($"Generated {couponCodes.Count} coupon codes:");
foreach (var code in couponCodes)
{
Console.WriteLine(code);
}
// Delete the coupon
couponApi.DeleteCoupon(coupon.CouponOid);
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
Console.WriteLine(ex.StackTrace);
}
}
}
}
package coupon;
import com.ultracart.admin.v2.CouponApi;
import com.ultracart.admin.v2.models.*;
import com.ultracart.admin.v2.util.ApiException;
import common.Constants;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.UUID;
public class GenerateCouponCodes {
public static void execute() {
System.out.println("--- " + GenerateCouponCodes.class.getSimpleName() + " ---");
try {
// Create coupon API instance using API key
CouponApi couponApi = new CouponApi(Constants.API_KEY);
String merchantCode = UUID.randomUUID().toString().substring(0, 8);
// Now create the coupon and ensure it exists.
Coupon coupon = new Coupon();
coupon.setMerchantCode(merchantCode);
coupon.setDescription("Test coupon for GetCoupon");
CouponAmountOffSubtotal amountOff = new CouponAmountOffSubtotal();
amountOff.setCurrencyCode("USD");
amountOff.setDiscountAmount(new BigDecimal("0.01")); // one penny discount
coupon.setAmountOffSubtotal(amountOff);
CouponResponse couponResponse = couponApi.insertCoupon(coupon, null);
coupon = couponResponse.getCoupon();
CouponCodesRequest codesRequest = new CouponCodesRequest();
codesRequest.setQuantity(5); // give me 5 codes.
codesRequest.setExpirationDts(Instant.now().plus(90, ChronoUnit.DAYS).toString()); // do you want the codes to expire?
// codesRequest.setExpirationSeconds(null); // also an option for short-lived coupons
CouponCodesResponse apiResponse = couponApi.generateCouponCodes(coupon.getCouponOid(), codesRequest);
List<String> couponCodes = apiResponse.getCouponCodes();
// Display generated coupon codes
System.out.println("Generated " + couponCodes.size() + " coupon codes:");
for (String code : couponCodes) {
System.out.println(code);
}
// Delete the coupon
couponApi.deleteCoupon(coupon.getCouponOid());
} catch (ApiException ex) {
System.out.println("Error: " + ex.getMessage());
ex.printStackTrace();
}
}
}
import { couponApi } from '../api.js';
import { DateTime } from 'luxon';
export class GenerateCouponCodes {
static async execute() {
console.log("--- GenerateCouponCodes ---");
try {
const merchantCode = this.generateGuid().substring(0, 8);
// Now create the coupon and ensure it exists.
const coupon = {
merchant_code: merchantCode,
description: "Test coupon for GetCoupon",
amount_off_subtotal: { currency_code: "USD", discount_amount: 0.01 }
}; // one penny discount.
const couponResponse = await new Promise((resolve, reject) => {
couponApi.insertCoupon(coupon, function (error, data, response) {
if (error) {
reject(error);
} else {
resolve(data, response);
}
});
});
const createdCoupon = couponResponse.coupon;
const codesRequest = {
quantity: 5, // give me 5 codes.
expiration_dts: DateTime.utc().plus({ days: 90 }).toISO() // do you want the codes to expire?
// expirationSeconds: null // also an option for short-lived coupons
};
const apiResponse = await new Promise((resolve, reject) => {
couponApi.generateCouponCodes(createdCoupon.coupon_oid, codesRequest, function (error, data, response) {
if (error) {
reject(error);
} else {
resolve(data, response);
}
});
});
const couponCodes = apiResponse.coupon_codes;
// Display generated coupon codes
console.log(`Generated ${couponCodes.length} coupon codes:`);
for (const code of couponCodes) {
console.log(code);
}
// Delete the coupon
await new Promise((resolve, reject) => {
couponApi.deleteCoupon(createdCoupon.coupon_oid, function (error, data, response) {
if (error) {
reject(error);
} else {
resolve(data, response);
}
});
});
} catch (ex) {
console.log(`Error: ${ex.message}`);
console.log(ex.stack);
}
}
// Helper method to generate a GUID-like string since TypeScript doesn't have Guid.NewGuid()
static generateGuid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
const r = Math.random() * 16 | 0;
const v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
}).replace(/-/g, '');
}
}
<?php
use ultracart\v2\api\CouponApi;
use ultracart\v2\models\CouponCodesRequest;
require_once '../vendor/autoload.php';
$coupon_api = CouponApi::usingApiKey(Constants::API_KEY);
$coupon_oid = 12345678; // if you don't know your coupon_oid, use generateOneTimeCodesByMerchantCode. same results
$codesRequest = new CouponCodesRequest();
$codesRequest->setQuantity(100); // give me 100 codes.
$codesRequest->setExpirationDts(date('Y-m-d', strtotime('90 days')) . "T00:00:00+00:00"); // do you want the codes to expire?
// $codesRequest->setExpirationSeconds(); // also an option for short-lived coupons
$api_response = $coupon_api->generateCouponCodes($coupon_oid, $codesRequest);
$coupon_codes = $api_response->getCouponCodes();
from ultracart.apis import CouponApi
from ultracart.models import CouponCodesRequest
from samples import api_client
from datetime import datetime, timedelta
coupon_api = CouponApi(api_client())
coupon_oid = 12345678 # if you don't know your coupon_oid, use generate_one_time_codes_by_merchant_code. same results
codes_request = CouponCodesRequest()
codes_request.quantity = 100 # give me 100 codes.
expiration_date = (datetime.now() + timedelta(days=90)).strftime('%Y-%m-%dT00:00:00+00:00')
codes_request.expiration_dts = expiration_date # do you want the codes to expire?
# codes_request.expiration_seconds = None # also an option for short-lived coupons
api_response = coupon_api.generate_coupon_codes(coupon_oid, codes_request)
coupon_codes = api_response.coupon_codes
require_relative '../constants'
require 'ultracart_api'
coupon_api = UltracartClient::CouponApi.new_using_api_key(Constants::API_KEY)
coupon_oid = 12345678 # if you don't know your coupon_oid, use generate_one_time_codes_by_merchant_code. same results
codes_request = UltracartClient::CouponCodesRequest.new
codes_request.quantity = 100 # give me 100 codes.
codes_request.expiration_dts = (Date.today + 90).strftime('%Y-%m-%d') + 'T00:00:00+00:00' # do you want the codes to expire?
# codes_request.expiration_seconds # also an option for short-lived coupons
api_response = coupon_api.generate_coupon_codes(coupon_oid, codes_request)
coupon_codes = api_response.coupon_codes
import { couponApi } from '../api';
import { Coupon, CouponAmountOffSubtotal, CouponResponse, CouponCodesRequest, CouponCodesResponse } from 'ultracart_rest_api_v2_typescript';
import { DateTime } from 'luxon';
export class GenerateCouponCodes {
public static async execute(): Promise<void> {
console.log("--- GenerateCouponCodes ---");
try {
const merchantCode: string = this.generateGuid().substring(0, 8);
// Now create the coupon and ensure it exists.
const coupon: Coupon = {
merchant_code: merchantCode,
description: "Test coupon for GetCoupon",
amount_off_subtotal: { currency_code: "USD", discount_amount: 0.01 } as CouponAmountOffSubtotal
}; // one penny discount.
const couponResponse: CouponResponse = await couponApi.insertCoupon({coupon:coupon});
const createdCoupon: Coupon = couponResponse.coupon!;
const codesRequest: CouponCodesRequest = {
quantity: 5, // give me 5 codes.
expiration_dts: DateTime.utc().plus({ days: 90 }).toISO() // do you want the codes to expire?
// expirationSeconds: null // also an option for short-lived coupons
};
const apiResponse: CouponCodesResponse = await couponApi.generateCouponCodes({couponOid: createdCoupon.coupon_oid!, couponCodesRequest: codesRequest});
const couponCodes: string[] = apiResponse.coupon_codes!;
// Display generated coupon codes
console.log(`Generated ${couponCodes.length} coupon codes:`);
for (const code of couponCodes) {
console.log(code);
}
// Delete the coupon
await couponApi.deleteCoupon({couponOid: createdCoupon.coupon_oid!});
} catch (ex: any) {
console.log(`Error: ${ex.message}`);
console.log(ex.stack);
}
}
// Helper method to generate a GUID-like string since TypeScript doesn't have Guid.NewGuid()
private static generateGuid(): string {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
const r = Math.random() * 16 | 0;
const v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
}).replace(/-/g, '');
}
}
Upload one-time codes for a coupon
SDK Function Name: uploadCouponCodes
Parameter | Description | Location | Data Type | Required |
---|---|---|---|---|
coupon_oid | The coupon oid to associate with the provided one-time codes. | path | integer (int32) | required |
upload_coupon_codes_request | One-time coupon codes | body | UploadCouponCodesRequest | required |
using System;
using System.Collections.Generic;
using System.Reflection;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;
namespace SdkSample.coupon
{
public class UploadCouponCodes
{
/*
uploadCouponCodes allows a merchant to upload one-time use codes and associate them with a merchant code (i.e. a coupon).
UltraCart has methods for generating one-time codes, and they work well, but this method exists when the merchant generates
them themselves. This frequently occurs when a merchant sends out a mailer with unique coupon codes on the mailer. The
merchant can then upload those codes with this method.
*/
public static void Execute()
{
Console.WriteLine("--- " + MethodBase.GetCurrentMethod()?.DeclaringType?.Name + " ---");
try
{
// Create coupon API instance using API key
CouponApi couponApi = new CouponApi(Constants.ApiKey);
String merchantCode = Guid.NewGuid().ToString("N").Substring(0, 8);
// Now create the coupon and ensure it exists.
Coupon coupon = new Coupon();
coupon.MerchantCode = merchantCode;
coupon.Description = "Test coupon for GetCoupon";
coupon.AmountOffSubtotal = new CouponAmountOffSubtotal("USD", 0.01m); // one penny discount.
CouponResponse couponResponse = couponApi.InsertCoupon(coupon);
coupon = couponResponse.Coupon;
// Create request for uploading coupon codes
UploadCouponCodesRequest codesRequest = new UploadCouponCodesRequest();
codesRequest.CouponCodes = new List<string> { "code1", "code2", "code3" };
// Upload the coupon codes
var apiResponse = couponApi.UploadCouponCodes(coupon.CouponOid, codesRequest);
// Display results
Console.WriteLine("Uploaded codes:");
foreach (var code in apiResponse.UploadedCodes)
{
Console.WriteLine(code);
}
Console.WriteLine("Duplicated codes:");
foreach (var code in apiResponse.DuplicateCodes)
{
Console.WriteLine(code);
}
Console.WriteLine("Rejected codes:");
foreach (var code in apiResponse.RejectedCodes)
{
Console.WriteLine(code);
}
// Delete the coupon
couponApi.DeleteCoupon(coupon.CouponOid);
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
Console.WriteLine(ex.StackTrace);
}
}
}
}
package coupon;
import com.ultracart.admin.v2.CouponApi;
import com.ultracart.admin.v2.models.*;
import com.ultracart.admin.v2.util.ApiException;
import common.Constants;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class UploadCouponCodes {
/*
uploadCouponCodes allows a merchant to upload one-time use codes and associate them with a merchant code (i.e. a coupon).
UltraCart has methods for generating one-time codes, and they work well, but this method exists when the merchant generates
them themselves. This frequently occurs when a merchant sends out a mailer with unique coupon codes on the mailer. The
merchant can then upload those codes with this method.
*/
public static void Execute() {
System.out.println("--- " + UploadCouponCodes.class.getSimpleName() + " ---");
try {
// Create coupon API instance using API key
CouponApi couponApi = new CouponApi(Constants.API_KEY);
String merchantCode = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 8);
// Now create the coupon and ensure it exists.
Coupon coupon = new Coupon();
coupon.setMerchantCode(merchantCode);
coupon.setDescription("Test coupon for GetCoupon");
coupon.setAmountOffSubtotal(new CouponAmountOffSubtotal()); // one penny discount.
coupon.getAmountOffSubtotal().setDiscountAmount(BigDecimal.valueOf(.01));
coupon.getAmountOffSubtotal().setCurrencyCode("USD");
CouponResponse couponResponse = couponApi.insertCoupon(coupon, null);
coupon = couponResponse.getCoupon();
// Create request for uploading coupon codes
UploadCouponCodesRequest codesRequest = new UploadCouponCodesRequest();
List<String> codes = new ArrayList<>();
codes.add("code1");
codes.add("code2");
codes.add("code3");
codesRequest.setCouponCodes(codes);
// Upload the coupon codes
UploadCouponCodesResponse apiResponse = couponApi.uploadCouponCodes(coupon.getCouponOid(), codesRequest);
// Display results
System.out.println("Uploaded codes:");
for (String code : apiResponse.getUploadedCodes()) {
System.out.println(code);
}
System.out.println("Duplicated codes:");
for (String code : apiResponse.getDuplicateCodes()) {
System.out.println(code);
}
System.out.println("Rejected codes:");
for (String code : apiResponse.getRejectedCodes()) {
System.out.println(code);
}
// Delete the coupon
couponApi.deleteCoupon(coupon.getCouponOid());
}
catch (ApiException ex) {
System.out.println("Error: " + ex.getMessage());
ex.printStackTrace();
}
}
}
// Import API and UltraCart types
import { couponApi } from '../api.js';
// Namespace-like structure using a class
export class UploadCouponCodes {
/*
* uploadCouponCodes allows a merchant to upload one-time use codes and associate them with a merchant code (i.e. a coupon).
* UltraCart has methods for generating one-time codes, and they work well, but this method exists when the merchant generates
* them themselves. This frequently occurs when a merchant sends out a mailer with unique coupon codes on the mailer. The
* merchant can then upload those codes with this method.
*/
static async execute() {
console.log(`--- UploadCouponCodes ---`);
try {
// Generate a random 8-character merchant code (replacing GUID)
const merchantCode = Math.random().toString(36).substring(2, 10);
// Create the coupon and ensure it exists
const coupon = {
merchant_code: merchantCode,
description: "Test coupon for GetCoupon",
amount_off_subtotal: {
currency: "USD",
discount_amount: 0.01, // one penny discount, decimal becomes number
},
};
// Insert the coupon
const couponResponse = await new Promise((resolve, reject) => {
couponApi.insertCoupon(coupon, function (error, data, response) {
if (error) {
reject(error);
} else {
resolve(data, response);
}
});
});
const createdCoupon = couponResponse.coupon;
if (!createdCoupon?.coupon_oid) {
throw new Error("Failed to create coupon; no OID returned");
}
// Create request for uploading coupon codes
const codesRequest = {
coupon_codes: ["code1", "code2", "code3"],
};
// Upload the coupon codes
const apiResponse = await new Promise((resolve, reject) => {
couponApi.uploadCouponCodes(createdCoupon.coupon_oid, codesRequest, function (error, data, response) {
if (error) {
reject(error);
} else {
resolve(data, response);
}
});
});
// Display results
console.log("Uploaded codes:");
for (const code of apiResponse.uploaded_codes ?? []) {
console.log(code);
}
console.log("Duplicated codes:");
for (const code of apiResponse.duplicate_codes ?? []) {
console.log(code);
}
console.log("Rejected codes:");
for (const code of apiResponse.rejected_codes ?? []) {
console.log(code);
}
// Delete the coupon
await new Promise((resolve, reject) => {
couponApi.deleteCoupon(createdCoupon.coupon_oid, function (error, data, response) {
if (error) {
reject(error);
} else {
resolve(data, response);
}
});
});
} catch (ex) {
console.log(`Error: ${ex.message}`);
console.log(ex.stack);
}
}
}
// Example usage (optional, remove if not needed)
// UploadCouponCodes.execute().catch(console.error);
<?php
/*
uploadCouponCodes allows a merchant to upload one-time use codes and associate them with a merchant code (i.e. a coupon).
UltraCart has methods for generating one-time codes, and they work well, but this method exists when the merchant generates
them themselves. This frequently occurs when a merchant sends out a mailer with unique coupon codes on the mailer. The
merchant can then upload those codes with this method.
*/
use ultracart\v2\api\CouponApi;
use ultracart\v2\models\UploadCouponCodesRequest;
require_once '../vendor/autoload.php';
$coupon_api = CouponApi::usingApiKey(Constants::API_KEY);
$coupon_oid = 12345678; // if you don't know your coupon_oid, use generateOneTimeCodesByMerchantCode. same results
$codesRequest = new UploadCouponCodesRequest();
$codesRequest->setCouponCodes(['code1', 'code2', 'code3']);
$api_response = $coupon_api->uploadCouponCodes($coupon_oid, $codesRequest);
echo 'Uploaded codes:<br>';
var_dump($api_response->getUploadedCodes());
echo 'Duplicated codes:<br>';
var_dump($api_response->getDuplicateCodes());
echo 'Rejected codes:<br>';
var_dump($api_response->getRejectedCodes());
from ultracart.apis import CouponApi
from ultracart.models import UploadCouponCodesRequest
from samples import api_client
"""
uploadCouponCodes allows a merchant to upload one-time use codes and associate them with a merchant code (i.e. a coupon).
UltraCart has methods for generating one-time codes, and they work well, but this method exists when the merchant generates
them themselves. This frequently occurs when a merchant sends out a mailer with unique coupon codes on the mailer. The
merchant can then upload those codes with this method.
"""
coupon_api = CouponApi(api_client())
coupon_oid = 12345678 # if you don't know your coupon_oid, use generateOneTimeCodesByMerchantCode. same results
codes_request = UploadCouponCodesRequest()
codes_request.coupon_codes = ['code1', 'code2', 'code3']
api_response = coupon_api.upload_coupon_codes(coupon_oid, codes_request)
print('Uploaded codes:')
print(api_response.uploaded_codes)
print('Duplicated codes:')
print(api_response.duplicate_codes)
print('Rejected codes:')
print(api_response.rejected_codes)
require 'ultracart_api'
require_relative '../constants'
# uploadCouponCodes allows a merchant to upload one-time use codes and associate them with a merchant code (i.e. a coupon).
# UltraCart has methods for generating one-time codes, and they work well, but this method exists when the merchant generates
# them themselves. This frequently occurs when a merchant sends out a mailer with unique coupon codes on the mailer. The
# merchant can then upload those codes with this method.
# Initialize the coupon API
coupon_api = UltracartClient::CouponApi.new_using_api_key(Constants::API_KEY)
coupon_oid = 12345678 # if you don't know your coupon_oid, use generateOneTimeCodesByMerchantCode. same results
codes_request = UltracartClient::UploadCouponCodesRequest.new
codes_request.coupon_codes = ['code1', 'code2', 'code3']
api_response = coupon_api.upload_coupon_codes(coupon_oid, codes_request)
puts 'Uploaded codes:'
puts api_response.uploaded_codes
puts 'Duplicated codes:'
puts api_response.duplicate_codes
puts 'Rejected codes:'
puts api_response.rejected_codes
// Import API and UltraCart types
import { couponApi } from '../api';
import { Coupon, CouponAmountOffSubtotal, UploadCouponCodesRequest } from 'ultracart_rest_api_v2_typescript';
// Namespace-like structure using a class
export class UploadCouponCodes {
/*
* uploadCouponCodes allows a merchant to upload one-time use codes and associate them with a merchant code (i.e. a coupon).
* UltraCart has methods for generating one-time codes, and they work well, but this method exists when the merchant generates
* them themselves. This frequently occurs when a merchant sends out a mailer with unique coupon codes on the mailer. The
* merchant can then upload those codes with this method.
*/
public static async execute(): Promise<void> {
console.log(`--- UploadCouponCodes ---`);
try {
// Generate a random 8-character merchant code (replacing GUID)
const merchantCode = Math.random().toString(36).substring(2, 10);
// Create the coupon and ensure it exists
const coupon: Coupon = {
merchant_code: merchantCode,
description: "Test coupon for GetCoupon",
amount_off_subtotal: {
currency: "USD",
discount_amount: 0.01, // one penny discount, decimal becomes number
} as CouponAmountOffSubtotal,
};
// Insert the coupon
const couponResponse = await couponApi.insertCoupon({
coupon: coupon,
});
const createdCoupon = couponResponse.coupon;
if (!createdCoupon?.coupon_oid) {
throw new Error("Failed to create coupon; no OID returned");
}
// Create request for uploading coupon codes
const codesRequest: UploadCouponCodesRequest = {
coupon_codes: ["code1", "code2", "code3"],
};
// Upload the coupon codes
const apiResponse = await couponApi.uploadCouponCodes({
couponOid: createdCoupon.coupon_oid,
uploadCouponCodesRequest: codesRequest,
});
// Display results
console.log("Uploaded codes:");
for (const code of apiResponse.uploaded_codes ?? []) {
console.log(code);
}
console.log("Duplicated codes:");
for (const code of apiResponse.duplicate_codes ?? []) {
console.log(code);
}
console.log("Rejected codes:");
for (const code of apiResponse.rejected_codes ?? []) {
console.log(code);
}
// Delete the coupon
await couponApi.deleteCoupon({couponOid: createdCoupon.coupon_oid});
} catch (ex) {
console.log(`Error: ${(ex as Error).message}`);
console.log((ex as Error).stack);
}
}
}
// Example usage (optional, remove if not needed)
// UploadCouponCodes.execute().catch(console.error);
namespace SdkSample.coupon
{
public class GetEditorValues
{
public static void Execute()
{
// This is an internal method used by our Coupon management screen. It returns back all the static data needed
// for our dropdown lists, such as coupon constants. You can call it if you like, but the data won't be
// of much use.
}
}
}
// This is an internal method used by our Coupon management screen. It returns back all the static data needed
// for our dropdown lists, such as coupon constants. You can call it if you like, but the data won't be
// of much use.
// This is an internal method used by our Coupon management screen. It returns back all the static data needed
// for our dropdown lists, such as coupon constants. You can call it if you like, but the data won't be
// of much use.
<?php
// This is an internal method used by our Coupon management screen. It returns back all the static data needed
// for our dropdown lists, such as coupon constants. You can call it if you like, but the data won't be
// of much use.
# This is an internal method used by our Coupon management screen. It returns back all the static data needed
# for our dropdown lists, such as coupon constants. You can call it if you like, but the data won't be
# of much use.
# This is an internal method used by our Coupon management screen. It returns back all the static data needed
# for our dropdown lists, such as coupon constants. You can call it if you like, but the data won't be
# of much use.
// This is an internal method used by our Coupon management screen. It returns back all the static data needed
// for our dropdown lists, such as coupon constants. You can call it if you like, but the data won't be
// of much use.
Searches for items to display within a coupon editor and assign to coupons
SDK Function Name: searchItems
Parameter | Description | Location | Data Type | Required |
---|---|---|---|---|
s | query | string | optional | |
m | query | integer (int32) | optional |
using System;
namespace SdkSample.coupon
{
public class SearchItems
{
public static void Execute()
{
// This is an internal method used by our Coupon management screen. It searches merchant items to display in
// some of the coupon editor dropdowns. See ItemApi.getItemsByQuery if you need to search items. This method
// is inflexible and geared toward our UI.
}
}
}
// This is an internal method used by our Coupon management screen. It searches merchant items to display in
// some of the coupon editor dropdowns. See ItemApi.getItemsByQuery if you need to search items. This method
// is inflexible and geared toward our UI.
// This is an internal method used by our Coupon management screen. It searches merchant items to display in
// some of the coupon editor dropdowns. See ItemApi.getItemsByQuery if you need to search items. This method
// is inflexible and geared toward our UI.
<?php
// This is an internal method used by our Coupon management screen. It searches merchant items to display in
// some of the coupon editor dropdowns. See ItemApi.getItemsByQuery if you need to search items. This method
// is inflexible and geared toward our UI.
# This is an internal method used by our Coupon management screen. It searches merchant items to display in
# some of the coupon editor dropdowns. See ItemApi.getItemsByQuery if you need to search items. This method
# is inflexible and geared toward our UI.
# This is an internal method used by our Coupon management screen. It searches merchant items to display in
# some of the coupon editor dropdowns. See ItemApi.getItemsByQuery if you need to search items. This method
# is inflexible and geared toward our UI.
// This is an internal method used by our Coupon management screen. It searches merchant items to display in
// some of the coupon editor dropdowns. See ItemApi.getItemsByQuery if you need to search items. This method
// is inflexible and geared toward our UI.
Name | Data Type | Description |
---|---|---|
affiliate_oid | integer (int32) | Associates an order with an affiliate when this value is set. |
allow_multiple_one_time_codes | boolean | True if multiple one time codes for this coupon can be used on a cart at the same time. |
amount_off_items | CouponAmountOffItems | Amount off items |
amount_off_shipping | CouponAmountOffShipping | Amount off shipping |
amount_off_shipping_with_items_purchase | CouponAmountOffShippingWithItemsPurchase | Amount off shipping with items purchase |
amount_off_subtotal | CouponAmountOffSubtotal | Amount off subtotal |
amount_off_subtotal_and_free_shipping | CouponAmountOffSubtotalFreeShippingWithPurchase | Amount off subtotal and free shipping with purchase |
amount_off_subtotal_and_shipping | CouponAmountOffSubtotalAndShipping | Amount off subtotal and shipping |
amount_off_subtotal_with_block_purchase | CouponAmountOffSubtotalWithBlockPurchase | Amount off subtotal with block purchase |
amount_off_subtotal_with_items_purchase | CouponAmountOffSubtotalWithItemsPurchase | Amount off subtotal with items purchase |
amount_off_subtotal_with_purchase | CouponAmountOffSubtotalWithPurchase | Amount off subtotal with purchase |
amount_shipping_with_subtotal | CouponAmountShippingWithSubtotal | Amount shipping with subtotal |
automatically_apply_coupon_codes | CouponAutomaticallyApplyCouponCodes | Additional coupon codes to automatically apply |
buy_one_get_one | CouponBuyOneGetOneLimit | Buy one get one free |
calculated_description | (read only) string | Calculated description displayed to the customer if no description is specified. |
can_be_used_with_other_coupons | boolean | True if this coupon can be used with other coupons in a single order. |
coupon_oid | integer (int32) | Coupon oid. |
coupon_type | string(65) | Coupon type. |
description | string(50) | Description of the coupon up to 50 characters. |
discount_item_with_item_purchase | CouponDiscountItemWithItemPurchase | Discount item with item purchase |
discount_items | CouponDiscountItems | Discount items |
expiration_dts | string (dateTime) | Date/time when coupon expires |
free_item_and_shipping_with_subtotal | CouponFreeItemAndShippingWithSubtotal | Free items and shipping with subtotal |
free_item_with_item_purchase | CouponFreeItemWithItemPurchase | Free item with item purchase |
free_item_with_item_purchase_and_free_shipping | CouponFreeItemWithItemPurchaseAndFreeShipping | Free item with item purchase and free shipping |
free_item_with_subtotal | CouponFreeItemWithSubtotal | Free items with subtotal |
free_items_with_item_purchase | CouponFreeItemsWithItemPurchase | Free items with item purchase |
free_items_with_mixmatch_purchase | CouponFreeItemsWithMixMatchPurchase | Free items with Mix and Match purchase |
free_shipping | CouponFreeShipping | Free shipping |
free_shipping_specific_items | CouponFreeShippingSpecificItems | Free shipping specific items |
free_shipping_with_items_purchase | CouponFreeShippingWithItemsPurchase | Free shipping with items purchase |
free_shipping_with_subtotal | CouponFreeShippingWithSubtotal | Free shipping with subtotal |
hide_from_customer | boolean | Hide coupon from customer during checkout. Often used when coupons are automatic discounting mechanisms. |
merchant_code | string(20) | Merchant code of coupon up to 20 characters. |
merchant_notes | string(250) | Internal notes about this coupon. These are not visible to customer. |
more_loyalty_cashback | CouponMoreLoyaltyCashback | More loyalty cashback |
more_loyalty_points | CouponMoreLoyaltyPoints | More loyalty points |
multiple_amounts_off_items | CouponMultipleAmountsOffItems | Multiple amounts off items |
no_discount | CouponNoDiscount | No discount |
percent_more_loyalty_cashback | CouponPercentMoreLoyaltyCashback | Percent more loyalty cashback |
percent_more_loyalty_points | CouponPercentMoreLoyaltyPoints | Percent more loyalty points |
percent_off_item_with_items_quantity_purchase | CouponPercentOffItemWithItemsQuantityPurchase | Percent off item with items quantity purchase |
percent_off_items | CouponPercentOffItems | Percent off items |
percent_off_items_and_free_shipping | CouponPercentOffItemsAndFreeShipping | Percent off items and free shipping |
percent_off_items_with_items_purchase | CouponPercentOffItemsWithItemsPurchase | Percent off items with items purchase |
percent_off_msrp_items | CouponPercentOffMsrpItems | Percent off MSRP items |
percent_off_retail_price_items | CouponPercentOffRetailPriceItems | Percent off retail price items |
percent_off_shipping | CouponPercentOffShipping | Percent off shipping |
percent_off_subtotal | CouponPercentOffSubtotal | Percent off subtotal |
percent_off_subtotal_and_free_shipping | CouponPercentOffSubtotalAndFreeShipping | Percent off subtotal and free shipping |
percent_off_subtotal_limit | CouponPercentOffSubtotalLimit | Percent off subtotal with limit |
percent_off_subtotal_with_items_purchase | CouponPercentOffSubtotalWithItemsPurchase | Percent off subtotal with items purchase |
percent_off_subtotal_with_subtotal | CouponPercentOffSubtotalWithSubtotal | Percent off subtotal with subtotal |
quickbooks_code | string(20) | Quickbooks accounting code. |
restrict_by_postal_codes | array of string | Optional list of postal codes which restrict a coupon to within these postal codes. |
restrict_by_screen_branding_theme_codes | array of CouponRestriction | Optional list of legacy screen branding theme codes to limit coupon use to only those themes. |
restrict_by_storefronts | array of CouponRestriction | Optional list of storefronts to limit coupon use to only those storefronts. |
skip_on_rebill | boolean | Skip this coupon when it is on a rebill of an auto order. |
start_dts | string (dateTime) | Date/time when coupon is valid |
super_coupon | boolean | If true, this coupon can be used with ANY other coupon regardless of the other coupons configuration |
tiered_amount_off_items | CouponTieredAmountOffItems | Tiered amount off items |
tiered_amount_off_subtotal | CouponTieredAmountOffSubtotal | Tiered amount off subtotal |
tiered_percent_off_items | CouponTieredPercentOffItems | Tiered percent off items |
tiered_percent_off_shipping | CouponTieredPercentOffShipping | Tiered percent off shipping |
tiered_percent_off_subtotal | CouponTieredPercentOffSubtotal | Tiered percent off subtotal |
tiered_percent_off_subtotal_based_on_msrp | CouponTieredPercentOffSubtotalBasedOnMSRP | Tiered percent off subtotal based on MSRP |
usable_by | string(50) | Who may use this coupon.
Allowed Values
|
Name | Data Type | Description |
---|---|---|
currency_code | string(3) | The ISO-4217 three letter currency code the customer is viewing prices in |
discount_amount | number | The amount of shipping discount |
item_tags | array of string | An optional list of item tags which will receive a discount. |
items | array of string | A list of items which are eligible for the discount amount. |
limit | integer (int32) | The limit of items which are eligible for the discount amount. |
Name | Data Type | Description |
---|---|---|
currency_code | string(3) | The ISO-4217 three letter currency code the customer is viewing prices in |
discount_amount | number | The amount of subtotal discount |
shipping_methods | array of string | One or more shipping methods that may be used with this coupon |
Name | Data Type | Description |
---|---|---|
currency_code | string(3) | The ISO-4217 three letter currency code the customer is viewing prices in |
discount_amount | number | The amount of shipping discount |
items | array of string | A list of items of which at least one must be purchased for coupon to be valid. |
shipping_methods | array of string | One or more shipping methods that may receive this discount |
Name | Data Type | Description |
---|---|---|
currency_code | string(3) | The ISO-4217 three letter currency code the customer is viewing prices in |
discount_amount | number | The amount of subtotal discount |
Name | Data Type | Description |
---|---|---|
currency_code | string(3) | The ISO-4217 three letter currency code the customer is viewing prices in |
discount_amount | number | The amount of subtotal discount |
Name | Data Type | Description |
---|---|---|
currency_code | string(3) | The ISO-4217 three letter currency code the customer is viewing prices in |
discount_amount | number | The amount of subtotal discount |
purchase_amount | number | The purchase amount to qualify for subtotal discount and free shipping |
shipping_methods | array of string | One or more shipping methods that may be free |
Name | Data Type | Description |
---|---|---|
currency_code | string(3) | The ISO-4217 three letter currency code the customer is viewing prices in |
discount_amount | number | The amount of subtotal discount |
required_purchase_item | string | Required item that must be purchased for coupon to be valid |
required_purchase_quantity | integer (int32) | Discount amount is multiplied by the number of blocks. A block is this many quantity of the required item. |
Name | Data Type | Description |
---|---|---|
currency_code | string(3) | The ISO-4217 three letter currency code the customer is viewing prices in |
discount_amount | number | The amount of shipping discount |
items | array of string | A list of items of which a quantity of one or many must be purchased for coupon to be valid. |
required_purchase_quantity | integer (int32) | The quantity of items that must be purchased for the discount to be applied. |
Name | Data Type | Description |
---|---|---|
currency_code | string(3) | The ISO-4217 three letter currency code the customer is viewing prices in |
discount_amount | number | The amount of subtotal discount |
purchase_amount | number | The purchase amount to qualify for subtotal discount and free shipping |
Name | Data Type | Description |
---|---|---|
currency_code | string(3) | The ISO-4217 three letter currency code the customer is viewing prices in |
purchase_amount | number | The purchase amount to qualify for subtotal discount and free shipping |
shipping_amount | number | The amount of the shipping cost (this is not a discount, this is the actual cost of shipping) |
shipping_methods | array of string | One or more shipping methods that may be used with this coupon |
Name | Data Type | Description |
---|---|---|
coupon_code | string | |
minimum_subtotal | number | The minimum subtotal that must be purchased to receive this coupon. Item and subtotal are exclusive. Only one can be populated. |
required_item_id | string | The item that must be purchased to receive this coupon. Item and subtotal are exclusive. Only one can be populated. |
Name | Data Type | Description |
---|---|---|
error | Error | Error object if unsuccessful |
metadata | ResponseMetadata | Meta-data about the response such as payload or paging information |
required_items | array of CouponAutoApplyCondition | |
subtotal_levels | array of CouponAutoApplyCondition | |
success | boolean | Indicates if API call was successful |
warning | Warning | Warning object if a non-fatal issue or side-effect occurs |
Name | Data Type | Description |
---|---|---|
coupon_codes | array of string | The coupon codes to automatically apply if this coupon is applied |
Name | Data Type | Description |
---|---|---|
item_tags | array of string | An optional list of item tags which will receive a discount. |
items | array of string | An optional list of items of which one must be purchased to receive free quantity of the same item. |
limit | integer (int32) | The limit of free items that may be received when purchasing multiple items |
Name | Data Type | Description |
---|---|---|
error | Error | Error object if unsuccessful |
expiration_dts | string | Expiration Date |
expiration_seconds | integer (int32) | Expiration seconds |
metadata | ResponseMetadata | Meta-data about the response such as payload or paging information |
quantity | integer (int32) | Quantity |
success | boolean | Indicates if API call was successful |
warning | Warning | Warning object if a non-fatal issue or side-effect occurs |
Name | Data Type | Description |
---|---|---|
coupon_codes | array of string | Coupon codes |
error | Error | Error object if unsuccessful |
expiration_dts | string (dateTime) | Expiration date |
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 |
Name | Data Type | Description |
---|---|---|
coupon_codes | array of string | Coupon codes |
coupon_oids | array of integer (int32) | Coupon oids |
Name | Data Type | Description |
---|---|---|
currency_code | string(3) | The ISO-4217 three letter currency code the customer is viewing prices in |
discount_price | number | The price (unit cost) of the discounted item |
items | array of string | A list of items that are eligible for this discount_price. |
limit | integer (int32) | The (optional) maximum quantity of discounted items. |
Name | Data Type | Description |
---|---|---|
currency_code | string(3) | The ISO-4217 three letter currency code the customer is viewing prices in |
discount_item | string | The item that will be sold at the discount_price when required_purchase_item is purchased. |
discount_item_tags | array of string | An optional list of item tags which will receive a discount of one of the required purchased items is purchased. |
discount_price | number | The price (unit cost) of the discounted item |
limit | integer (int32) | The (optional) maximum quantity of discounted items. |
required_purchase_item | string | The item that must be purchased for the discount to be applied to the discount item. |
required_purchase_items_tags | array of string | An optional list of item tags which are required to be purchased. |
Name | Data Type | Description |
---|---|---|
affiliates | (read only) array of SimpleValue | affiliates |
coupon_types | (read only) array of string | coupon_types |
coupon_types_for_display | (read only) array of CouponType | coupon_types_for_display |
currency_codes | (read only) array of string | currency_codes |
deprecated_themes | (read only) array of SimpleValue | deprecated_themes |
item_tags | (read only) array of string | Item tags |
mix_and_match_names | (read only) array of string | mix_and_match_names |
shipping_methods | (read only) array of string | shipping_methods |
storefronts | (read only) array of SimpleValue | storefronts |
usable_by | (read only) array of SimpleValue | usable_by |
valid_with_other_coupons | (read only) array of string | valid_with_other_coupons |
Name | Data Type | Description |
---|---|---|
coupon_code | string | Coupon Code |
error | Error | Error object if unsuccessful |
exists | boolean | Exists |
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 |
Name | Data Type | Description |
---|---|---|
currency_code | string(3) | The ISO-4217 three letter currency code the customer is viewing prices in |
items | array of string | A list of items that are eligible for this discount_price. |
limit | integer (int32) | The limit of free items that may be received when purchasing multiple items |
shipping_methods | array of string | One or more shipping methods that may be free |
subtotal_amount | number | The amount of subtotal required to receive the discount percent |
Name | Data Type | Description |
---|---|---|
free_item | string | The item id of the free item that will be received when the required mix and match group quantity is purchased. |
free_quantity | integer (int32) | The quantity of free item that will be received. |
limit | integer (int32) | The limit of free items that may be received when purchasing multiple items |
required_purchase_item | string | Required item that must be purchased for coupon to be valid |
required_purchase_quantity | integer (int32) | Required quantity of mix and match group items that must be purchased for coupon to be valid |
Name | Data Type | Description |
---|---|---|
free_item | string | The item id of the free item that will be received when the required mix and match group quantity is purchased. |
free_quantity | integer (int32) | The quantity of free item that will be received. |
limit | integer (int32) | The limit of free items that may be received when purchasing multiple mix and match group items |
required_purchase_mix_and_match_group | string | Required mix and match group that must be purchased for coupon to be valid |
required_purchase_quantity | integer (int32) | Required quantity of mix and match group items that must be purchased for coupon to be valid |
Name | Data Type | Description |
---|---|---|
item_tags | array of string | An optional list of item tags which will receive a discount of one of the required purchased items is purchased. |
items | array of string | A list of free items which will receive a discount if one of the required purchase items is purchased. |
limit | integer (int32) | The (optional) maximum quantity of discounted items. |
match_required_purchase_item_to_free_item | boolean | If true then the free item is matched 1:1 with the free item in the list. |
required_purchase_items | array of string | Required items (at least one from the list) that must be purchased for coupon to be valid |
required_purchase_items_tags | array of string | An optional list of item tags which are required to be purchased. |
Name | Data Type | Description |
---|---|---|
items | array of string | A list of free items which will receive a discount if one of the required purchase items is purchased. |
limit | integer (int32) | The (optional) maximum quantity of discounted items. Free shipping will apply to all units of the free item ids though. |
match_required_purchase_item_to_free_item | boolean | If true then the free item is matched 1:1 with the free item in the list. |
required_purchase_items | array of string | Required items (at least one from the list) that must be purchased for coupon to be valid |
Name | Data Type | Description |
---|---|---|
currency_code | string(3) | The ISO-4217 three letter currency code the customer is viewing prices in |
items | array of string | A list of items that are eligible for this discount_price. |
limit | integer (int32) | The limit of free items that may be received when purchasing multiple items |
subtotal_amount | number | The amount of subtotal required to receive the discount percent |
Name | Data Type | Description |
---|---|---|
shipping_methods | array of string | One or more shipping methods that may be used with this coupon |
Name | Data Type | Description |
---|---|---|
items | array of string | A list of items of which at least one must be purchased for coupon to be valid. |
Name | Data Type | Description |
---|---|---|
items | array of string | A list of items of which at least one must be purchased for coupon to be valid. |
shipping_methods | array of string | One or more shipping methods that may receive this discount |
Name | Data Type | Description |
---|---|---|
currency_code | string(3) | The ISO-4217 three letter currency code the customer is viewing prices in |
purchase_amount | number | The purchase amount to qualify for subtotal discount and free shipping |
shipping_methods | array of string | One or more shipping methods that may be used with this coupon |
Name | Data Type | Description |
---|---|---|
cost | (read only) string | The cost of this item. |
description | (read only) string | A human readable description of this item. |
manufacturer_name | (read only) string | The manufacturer of this item. |
manufacturer_sku | (read only) string | The manufacturer sku of this item. |
merchant_item_id | (read only) string | The merchant item identifier, which is unique for this merchant, but not across all of UltraCart. |
merchant_item_oid | (read only) integer (int32) | The unique internal identifier used by UltraCart to manage this item. |
score | (read only) string | The search score of this item. Larger scores mean more accurate matches against the search term. |
thumbnail_url | (read only) string | A url for displaying a thumbnail of this item |
Name | Data Type | Description |
---|---|---|
error | Error | Error object if unsuccessful |
metadata | ResponseMetadata | Meta-data about the response such as payload or paging information |
search_results | array of CouponItemSearchResult | search_results |
success | boolean | Indicates if API call was successful |
warning | Warning | Warning object if a non-fatal issue or side-effect occurs |
Name | Data Type | Description |
---|---|---|
loyalty_cashback | number | The additional loyalty cashback |
Name | Data Type | Description |
---|---|---|
loyalty_points | number | The additional loyalty points |
Name | Data Type | Description |
---|---|---|
discounts | array of CouponTierItemDiscount | A list of item discounts. |
limit | integer (int32) | The (optional) maximum quantity of items that may receive a discount. |
Name | Data Type | Description |
---|---|---|
ignore_this_property | (read only) boolean | This property does nothing but is included in this object to ensure the object is generated by our sdk builders. |
Name | Data Type | Description |
---|---|---|
percent_more_loyalty_cashback | number | The percentage of additional loyalty cashback |
Name | Data Type | Description |
---|---|---|
percent_more_loyalty_points | number | The percentage of additional loyalty points |
Name | Data Type | Description |
---|---|---|
discount_percent | number | The percentage of subtotal discount |
excluded_item_tags | array of string | A list of item tags which cannot be discounted. |
excluded_items | array of string | A list of items which cannot be discounted. |
item_tags | array of string | An optional list of item tags which will receive a discount. If blank, discount applies to all items except excluded items. |
items | array of string | An optional list of items which will receive a discount. If blank, discount applies to all items except excluded items. |
limit | integer (int32) | The (optional) maximum quantity of discounted items. |
Name | Data Type | Description |
---|---|---|
discount_percent | number | The percentage of subtotal discount |
excluded_item_tags | array of string | A list of item tags which cannot be discounted. |
excluded_items | array of string | A list of items which cannot be discounted. |
item_tags | array of string | An optional list of item tags which will receive a discount. If blank, discount applies to all items except excluded items. |
items | array of string | An optional list of items which will receive a discount. If blank, discount applies to all items except excluded items. |
Name | Data Type | Description |
---|---|---|
discount_percent | number | The percentage of subtotal discount |
item_tags | array of string | An optional list of item tags which will receive a discount of one of the required purchased items is purchased. |
items | array of string | A list of items which will receive a discount if one of the required purchase items is purchased. |
limit | integer (int32) | The (optional) maximum quantity of discounted items. |
required_purchase_items | array of string | Required items (at least one from the list) that must be purchased for coupon to be valid |
required_purchase_items_tags | array of string | An optional list of item tags which are required to be purchased. |
Name | Data Type | Description |
---|---|---|
discount_percent | number | The percentage of subtotal discount |
item_tags | array of string | An optional list of item tags which will receive a discount if one of the required purchased items is purchased. |
items | array of string | A list of items which will receive a discount if one of the required purchase items is purchased. |
limit | integer (int32) | The (optional) maximum quantity of discounted items. |
required_purchase_items | array of string | Required items (at least one from the list) that must be purchased for coupon to be valid |
required_purchase_items_tags | array of string | Required item tags (at least one from the list) that must be purchase for coupon to be valid. |
required_purchase_quantity | integer (int32) | The quantity of items that must be purchased for the discount to be applied. |
Name | Data Type | Description |
---|---|---|
discount_percent | number | The percentage of subtotal discount |
excluded_items | array of string | A list of items which cannot be discounted. |
items | array of string | An list of items which will receive a discount. |
limit | integer (int32) | The (optional) maximum quantity of discounted items. |
minimum_cumulative_msrp | number | The (optional) minimum cumulative msrp of qualifying items. |
minimum_subtotal | number | The (optional) minimum subtotal of qualifying items. |
Name | Data Type | Description |
---|---|---|
discount_percent | number | The percentage of subtotal discount |
excluded_items | array of string | A list of items which cannot be discounted. |
items | array of string | An optional list of items which will receive a discount. If blank, discount applies to all items except excluded items. |
limit | integer (int32) | The (optional) maximum quantity of discounted items. |
Name | Data Type | Description |
---|---|---|
discount_percent | number | The percentage of subtotal discount |
shipping_methods | array of string | One or more shipping methods that may be used with this coupon |
Name | Data Type | Description |
---|---|---|
discount_percent | number | The percentage of subtotal discount |
Name | Data Type | Description |
---|---|---|
discount_percent | number | The percentage of subtotal discount |
shipping_methods | array of string | One or more shipping methods that may be free |
Name | Data Type | Description |
---|---|---|
currency_code | string(3) | The ISO-4217 three letter currency code the customer is viewing prices in |
discount_percent | number | The percentage of subtotal discount |
limit | number | The maximum amount of subtotal used to determine discount. |
Name | Data Type | Description |
---|---|---|
discount_percent | number | The percentage of subtotal discount |
items | array of string | A list of items of which at least one must be purchased for coupon to be valid. |
Name | Data Type | Description |
---|---|---|
currency_code | string(3) | The ISO-4217 three letter currency code the customer is viewing prices in |
discount_percent | number | The percentage of subtotal discount |
subtotal_amount | number | The amount of subtotal required to receive the discount percent |
Name | Data Type | Description |
---|---|---|
affiliate_oid | integer (int32) | Affiliate oid |
coupon_type | string | The type of coupon. |
description | string | Description of this coupon |
exclude_expired | boolean | Exclude expired coupons if true |
expiration_dts_begin | string (dateTime) | Expiration date begin |
expiration_dts_end | string (dateTime) | Expiration date begin |
merchant_code | string | Merchant code is a unique character string for this coupon. |
merchant_code_or_description | string | Merchant code description used for searching |
start_dts_begin | string (dateTime) | Start date begin |
start_dts_end | string (dateTime) | Start date end |
Name | Data Type | Description |
---|---|---|
coupon | Coupon | Coupon |
error | Error | Error object if unsuccessful |
items_invalid_for_coupons | array of string | Items invalid for coupons. These will display as warnings within the UI. |
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 |
Name | Data Type | Description |
---|---|---|
invalidForThis | boolean | |
name | string | |
validForThis | boolean | |
validOnlyForThis | boolean |
Name | Data Type | Description |
---|---|---|
coupons | array of Coupon | |
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 |
Name | Data Type | Description |
---|---|---|
discount_amount | number | The amount of subtotal discount |
quickbooks_code | string(20) | Quickbooks accounting code. |
subtotal_amount | number | The amount of subtotal required to receive the discount amount |
Name | Data Type | Description |
---|---|---|
item_tags | array of string | An optional list of item tags which will receive a discount. If blank, discount applies to all items except excluded items. |
items | array of string | The items being discounted by this coupon. |
limit | number | The maximum number of discounted items. |
tiers | array of CouponTierQuantityAmount | A list of discount tiers. |
Name | Data Type | Description |
---|---|---|
items | array of string | An optional list of items of which a quantity of one or many must be purchased for coupon to be valid. If empty, all items apply toward subtotal amount. |
tiers | array of CouponTierAmount | A list of discount tiers. |
Name | Data Type | Description |
---|---|---|
item_tags | array of string | An optional list of item tags which will receive a discount. If blank, discount applies to all items except excluded items. |
items | array of string | A list of items of which at least one must be purchased for coupon to be valid. |
limit | number | The (optional) maximum quantity of discounted items. |
tiers | array of CouponTierQuantityPercent | A list of discount tiers. |
Name | Data Type | Description |
---|---|---|
quickbooks_code | string(20) | Quickbooks accounting code. |
shipping_methods | array of string | One or more shipping methods that may receive this discount |
tiers | array of CouponTierPercent | A list of discount tiers. |
Name | Data Type | Description |
---|---|---|
items | array of string | An optional list of items of which a quantity of one or many must be purchased for coupon to be valid. If empty, all items apply toward subtotal amount. |
tiers | array of CouponTierPercent | A list of discount tiers. |
Name | Data Type | Description |
---|---|---|
items | array of string | An optional list of items of which a quantity of one or many must be purchased for coupon to be valid. If empty, all items apply toward subtotal amount. |
tiers | array of CouponTierPercent | A list of discount tiers. |
Name | Data Type | Description |
---|---|---|
discount_amount | number | The amount of subtotal discount |
items | array of string | A list of items which will receive this discount. |
Name | Data Type | Description |
---|---|---|
discount_percent | number | The percent of subtotal discount |
quickbooks_code | string(20) | Quickbooks accounting code. |
subtotal_amount | number | The amount of subtotal required to receive the discount percent |
Name | Data Type | Description |
---|---|---|
discount_amount | number | The amount of discount per item. |
item_quantity | integer (int32) | The quantity of item purchased (in units) |
quickbooks_code | string(20) | Quickbooks accounting code. |
Name | Data Type | Description |
---|---|---|
discount_percent | number | The percent of discount per item. |
item_quantity | integer (int32) | The quantity of item purchased (in units) |
quickbooks_code | string(20) | Quickbooks accounting code. |
Name | Data Type | Description |
---|---|---|
localized | string | A friendly display of the coupon type suitable for human reading |
name | string | The name of the coupon type |
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 |
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 |
Name | Data Type | Description |
---|---|---|
payload_name | string | Payload name |
result_set | ResultSet | Result set |
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. |
Name | Data Type | Description |
---|---|---|
display | string | A friendly display of this value suitable for human reading |
value | string | The actual value |
Name | Data Type | Description |
---|---|---|
coupon_codes | array of string | Coupon codes |
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 |
Name | Data Type | Description |
---|---|---|
duplicate_codes | array of string | Duplicate codes |
error | Error | Error object if unsuccessful |
metadata | ResponseMetadata | Meta-data about the response such as payload or paging information |
rejected_codes | array of string | Rejected codes |
success | boolean | Indicates if API call was successful |
uploaded_codes | array of string | Uploaded codes |
warning | Warning | Warning object if a non-fatal issue or side-effect occurs |
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 |
Name | Data Type | Description |
---|---|---|
UC-REST-ERROR | string | Contains human readable error message |
Name | Data Type |
---|---|
body | ErrorResponse |
Name | Data Type | Description |
---|---|---|
UC-REST-ERROR | string | Contains human readable error message |
Name | Data Type |
---|---|
body | ErrorResponse |
Name | Data Type | Description |
---|---|---|
UC-REST-ERROR | string | Contains human readable error message |
Name | Data Type |
---|---|
body | ErrorResponse |
Name | Data Type | Description |
---|---|---|
UC-REST-ERROR | string | Contains human readable error message |
Name | Data Type |
---|---|
body | ErrorResponse |
Name | Data Type | Description |
---|---|---|
UC-REST-ERROR | string | Contains human readable error message |
Name | Data Type |
---|---|
body | ErrorResponse |