Creating an Order with the Public API

Before You Start

Ensure you read through the Public API Getting Started guide to learn how to get authorized and locate your API Keys.

✅Read more

Getting Started with the Public API



Call Prerequisites

Finding Associates

This guide will cover order creation for an existing Associate account. This Associate should be valid and placed in a tree.

Find one to use in Corporate Admin, or create one using the POST Create Customer call. You’ll be using the DirectScale ID (Associate ID) as the identifier in the API.

DirectScale ID

Corporate Shop

To ensure everything is set up properly, create an order using the Corporate Shop inside Corporate Admin, by clicking the New Corporate Order button. You'll find troubleshooting order creation issues much easier with the admin because it allows setting changes.

New Corporate Order button



Building an Order Request

We’ll cover the following steps in the remainder of this document.

  1. Identify store and available products
  2. Collect items, calculate totals, and discover shipping methods
  3. Identify user account
  4. Identify or gather user payment information
  5. Set up and submit order request
  6. View/list orders


Identify Store and Available Products

Stores

A Store is a logical grouping of configuration information, including categories and products. This can be configured specific to an application or can be shared across applications. Find the store you’ve been asked to use, take its ID, and use it in later calls. Learn more about Stores here: Adding Stores

Call: GET https://dsapi-stage.directscale.com/v1/products/stores

Response:

[{
      "ID": 1,
      "Description": "Corporate"
  },
  {
      "ID": 2,
      "Description": "Wholesale"
   },
   {
      "ID": 3,
      "Description": "Retail"
   },

All Items (products) Call

You have the option of getting all the items with all their data (including categories, pictures, pricing, etc.) and managing them in your own application. Although this call returns a lot of data, you'll find that it performs well. Learn more about managing inventory here: {Inventory Management Guide}()

Call: GET https://dsapi-stage.directscale.com/v1/products/items

Response: Returns an array of every product in the system with this data. Note “Custom Fields” too:

[{
    "Id": 34,
    "Sku": "SampleSKU",
    "KitLevel": 0,
    "Category": {
      "Id": 0,
      "Name": "",
      "Description": "",
      "DisplayIndex": 0.0,
      "ImageUrl": null,
      "ParentId": 0,
      "ProductLineId": 0,
      "ShortDescription": "",
      "StoreIds": [],
      "HasChildren": false
    },
    "ChargeShipping": true,
    "Disabled": false,
    "Height": 0.0,
    "Image": "",
    "Length": 0.0,
    "LengthUnitOfMeasure": "cm",
    "ManufacturerPartNum": "",
    "OutOfStockStatus": 1,
    "PackCount": 0.0,
    "PackageGroupId": 1,
    "PreferedVendorId": 0,
    "SortOrder": 0,
    "TaxClassId": 0,
    "ProductClass": 0,
    "TrackStock": true,
    "UnitOfMeasure": "",
    "Upc": "",
    "Weight": 0.0,
    "WeightUnitOfMeasure": "kg",
    "Width": 0.0,
    "FlagCancer": false, // California Prop 65
    "FlagBirthDefects": false, // California Prop 65
    "HasKitGroups": false,
    "HsCode": "",
    "Custom": {
      "ItemId": 0,
      "Field1": "",
      "Field2": "",
      "Field3": "",
      "Field4": "",
      "Field5": ""
    },
    "FastStart": {
      "Gen1": 0.0,
      "Gen2": 0.0
...
    },
    "Images": [],
    "Languages": [{
      "Description": "<h2><strong>This is a great product</strong></p>",
      "LanguageCode": "en",
      "ProductName": "Great Product!",
      "SeoKeywords": "",
      "Specifications": ""
    }],
    "Options": [], // Sizes and color options, etc. show up here
    "OptionsMap": [],
    "Discounts": [{ // AKA "Prices"
      "Id": 35,
      "Bonus": null,
      "End": "9999-01-01T00:00:00",
      "Price": 314.59,
      "PriceCurrency": "USD",
      "Cv": 10,
      "Qv": 50,
      "RewardPointsEarned": 100.0,
      "Start": "2018-07-31T00:00:00",
      "Type": 1,
      "Stores": [],
      "OrderType": [],
      "PriceGroups": [],
      "Regions": []
    }]

📘Note about Filtered Item Calls

In addition to the Get All Items call, you're also provided APIs with grouping options, should you prefer to use the DirectScale management system to break items into groups.

Product Categories

Learn more about product categories here: [Adding Categories(https://help.directscale.com/hc/en-us/articles/360037905874-Adding-Categories).

Call: GET https://dsapi-stage.directscale.com/v1/products/store/<storeId>/categories

Response:

{
    "ID": 22,
    "Name": "Transform",
    "Description": "",
    "ImageUrl": null,
    "ParentID": 0,
    "HasChildren": false,
    "SubCategories": null,
},
{
    "ID": 15,
    "Name": "Recovery",
    "Description": "",
    "ImageUrl": null,
    "ParentID": 0,
    "HasChildren": false,
    "SubCategories": null,
},
{
    "ID": 24,
    "Name": "Samples",
    "Description": "",
    "ImageUrl": null,
    "ParentID": 0,
    "HasChildren": false,
    "SubCategories": null,
},

Get Items by Filter

For a given collection of data about a customer, store, etc., this call will get a list of available items with data filtered to the parameters passed. To use this, in addition to the Store and Category IDs, you’ll need:

  • Region ID (/products/get regions)
  • Price Group ID (/order/Get Price Group(s))
  • Language Code (ISO 2 char)

Call: GET https://dsapi-stage.directscale.com/v1/products/categories/22/items?CurrencyCode=usd&LanguageCode=en&RegionID=1&PriceGroup=1&StoreID=2

Response:

[{
    "ItemID": 80,
    "Quantity": 1.0,
    "ExtendedPrice": 56.21,
    "ExtendedBonus": 0.0,
    "ExtendedCV": 53.0,
    "ExtendedQV": 53.0,
    "ProductName": "Collagen",
},

Top-selling Products

This is a quick and useful call that returns a list of top-selling items in a particular category. Depending on the numberOfProducts passed in, you’ll get a list of products in order of top sold.

The parameters in the URL are similar to the Get Items by Filter call above, and the response payload is identical.

Call: https://dsapi-stage.directscale.com/v1/products/categories/22/topproducts?numberOfProducts=1&CurrencyCode=usd&LanguageCode=en&RegionID=1&PriceGroup=1&StoreID=1&CountryCode=US

Response:

[{
    "ItemID": 80,
    "Quantity": 1.0,
    "ExtendedPrice": 56.21,
    "ExtendedBonus": 0.0,
    "ExtendedCV": 53.0,
    "ExtendedQV": 53.0,
    "ProductName": "Collagen",
},

Collect Items and Calculate Totals

The public API does not provide a cart system to manage the interactive user shopping experience. You’ll need to do that in your own application or use the eCommerce Shop and Admin. However, all calls required for order calculation and creation are provided.

📘Note

We also provide an order history call to gather data from previous orders. (GET /customers/{customerId}/orders).

Calculate Customer Order Total

With a StoreId and Items, you can begin calculating order totals.

Here is the minimum payload to accomplish this, with some comments inline:

📘Note

If you don’t have a Customer ID to calculate with, use an existing customer in the system. You can also pass in a Price Group, etc. to adjust pricing.

{
    "StoreId": 3, 
    "CurrencyCode": "usd", // There is no public API call to find this, but an invalid value will process.
    "Items": [{
        "ItemId": 30, // Note: this is the ID, not the SKU
        "Quantity": 3
      }],
    "ShippingAddress": {}, // Works empty, but for better pricing accuracy, fill this out. 
    "ShipMethodId": 6 // See note below.
}

See the API Documentation for the full payload.

📘Note on ShipMethodId

You must provide a valid ShipMethodId to get the order to calculate. Please use this call to find a valid ID: https://dsapi-stage.directscale.com/v1/orders/shipping-methods

The response will then return a collection of all valid shipping methods for this order.

Call: https://dsapi-stage.directscale.com/v1/customers/2/orders/calculate

Response:

  • Items contains the product description, specifications, and name in addition to the pricing info. You can use this to display product details in your application.
  • ShippingMethods shows pricing for each method. Re-call calculate with the number associated with the method to reflect that method in totals.
  • Increasing address accuracy in the request will give tax values.
{
  "Items": [{
    "ItemId": 30,
    "Bonus": 7.8,
    "ChargeShipping": true,
    "CurrencyCode": null,
    "Cv": 39.0,
    "Description": "<h4 class=\"product-title\">Full product description included in response.</h4>",
    "ExtendedBonus": 23.4,
    "ExtendedCv": 117.0,
    "ExtendedPrice": 149.85,
    "ExtendedQv": 117.0,
    "LanguageCode": "en",
    "OriginalPrice": 49.95,
    "Price": 49.95,
    "ProductName": "Another Brick in the Wall",
    "Sku": "F5",
    "Specifications": "<p>Product specs here.</p>",
    "Quantity": 3.0,
    "Qv": 39.0
  }],
  "ShippingMethods": [{
      "ShipMethodId": 6,
      "Description": "Demo Ship",
      "ShippingAmount": 5.0
    },
    {
      "ShipMethodId": 7,
      "Description": "USPS",
      "ShippingAmount": 12.85
    }
  ],
  "CurrencyCode": "usd",
  "DiscountTotal": 0.0,
  "ShippingTotal": 5.0,
  "SubTotal": 149.85,
  "TaxableSubtotal": 149.85,
  "TaxTotal": 0.0,
  "Total": 154.85
}

Identify User Account

Order must be created with an associated user account. This account can be created using the API call Create Customer.

POST https://dsapi-stage.directscale.com/v1/customers/

Alternatively, an existing account can be looked up and used.


Identify or gather user payment information

DirectScale stores card tokens generated through processor-hosted pages, either through remote form fields or iframed pages. Using JavaScript, these payment providers (merchant) processor pages return a card token and basic data to the calling page.

Each account in the Platform can store multiple saved payments in the form of tokens and non-identifying account card data tied to the Associate’s record.

Such as:

  • Last four digits on the card
  • Expiration date
  • Name on the card

You’ll use Get Customer Saved Payment Methods to see this data.

Mapping into Create Order Payment Structure

The payment structure required in the Order Create JSON looks like the following (with comments in-line detailing where these values come from):

"Payments": [{
	"Amount": 154.85, // “Total” on Calculate (links to section in this doc)
	“OnFileCard": "Primary", // Enum-Primary,DoNotSave,Secondary,OneTimeUse
	"CurrencyCode": "usd", // “CurrencyCode” on Calculate
	"MerchantId": 99, // “MerchantId” on PaymentMethods (below)
	"SavePayment": true, 
	"OrderCreditCard": {
		"CardToken": "abc123456", // “PaymentMethodId” on PaymentMethods
		"NameOnCard": "Sam Space", // “NameOnAccount” on PaymentMethods
		"Last4": "1234", // “Ending” on PaymentMethods
		"CardType": "Visa", // “CardType” on PaymentMethods
		"ExpirationMonth": 12, // Expires (month) on PaymentMethods
		"ExpirationYear": 2022 // Expires (year) on PaymentMethods
	}
}],	

To collect this information, look up the card-on-file belonging to the account. If no card exists, you must create a new card entry on the system and then fetch the information.

Let’s take a look at each of these calls:

Get Customer Saved Payment Methods

To get a list of saved payments on file, you need to know for which store you’re getting payments. A payment provider is affiliated with a store entity in Corporate Admin, so different stores can support different payment methods. A single store can support multiple payment providers.

Call: https://dsapi-stage.directscale.com/v1/customers/2/paymentmethods/?storeid=3

Response (partial view):

{
      "PaymentMethodId": "abc123456",
      "MerchantId": 99,
      "CardType": "Visa",
      "NameOnAccount": "Sammy Spacey",
      "Ending": "1234",
      "Expires": "2022-12",
      "CurrencyCode": "USD"
},

⚠Important

Unfortunately, the structure of this response does not match the structure of the Create Order request. You will need to map this response to your own Payment object to put into Create Order.

Create a New Payment

To capture a new credit card or generate a different sort of payment account (like PayPal if the provider supports it), you’ll need to bring up a pop-up window or render a remote source in a <div> or iframe. The API response contains a URL to display (that belongs to the payment provider) and some JavaScript you can use to capture the token and other data from the provider page.

Once you get that token, you can either:

OR

  • Simply pass the payment information into the Create Order call with the SavePayment flag set to ‘true’.

Call: https://dsapi-stage.directscale.com/v1/customers/2/paymentmethods/iframe?iframeid=test&storeid=3&countrycode=us&region=ut&languagecode=en

Response:

{
  "MerchantId": 99,
  "IFrameUrl": "https://demo.corpadmin.directscalestage.com/AddCardFrameTest",
  "Height": 810,
  "Width": 530,
  "Script": "<script>\r\n   window.addEventListener('message', receiveMessage, false);\r\n   function 
receiveMessage(event){\r\n       if(event.data.isTestCardEvent && event.data.type != 'eCheck'){\r\n           
var origin = event.origin || event.originalEvent.origin;\r\n           if (origin !== 
'https://demo.corpadmin.directscalestage.com'){\r\n               OnIFrameError('Unexpected Origin');\r\n               
return;\r\n           }\r\n           var data = {};\r\n           data.Token = event.data.card_ref;\r\n           data.Last4 
= event.data.card_num;\r\n           data.CardType = event.data.type;\r\n           data.ExpireMonth = 
event.data.expireMonth;\r\n           data.ExpireYear = event.data.expireYear;\r\n           data.MerchantID = 
'99';\r\n           if(data.Token === undefined){\r\n               return;\r\n           }\r\n           
OnIFrameSave(data);\r\n       }\r\n   }\r\n</script>\r\n"
}

In the preceding example response, the IFrameUrl parameter is a DirectScale server because the test merchant ID is 99; otherwise, it would be the URL of a provider (in most cases, unless pulling in fields using JavaScript).

The form will usually look something like this:

Payment Method modal

Enter the JavaScript on the page and render the supplied URL, and it’ll work. The data object contains all you need to either create the order or save the payment.

Save Payment to Customer Account

Now that you have the new card token, you can either enter it in the Order > Payment object and flag it to save, or you can save it to the account.

📘Note

There’s also a call to delete payments from the account if you’d like to add a UI to do that.
https://dsapi-stage.directscale.com/v1/customers/{customerid}/paymentmethods/{paymentmethodid}?merchantid={merchantid}

Call: (optional, because the system can save the card with the Create Order request) https://dsapi-stage.directscale.com/v1/customers/2/paymentmethods/

Response: This call just returns the token you passed in and a 201 response code, if all is well.

Map Payment Data to Order Payment Object

See the Mapping into Create Order Payment Structure for explicit details on how to do this mapping.


Set Up and Submit Order Request

Now, you need to assemble the necessary pieces and create the order.

  • Items
  • Payments
  • Shipping Address
  • Shipping Method
  • Coupon Codes

Call: POST https://dsapi-dev.directscale.com/v1/customers/2/orders

Here’s the request payload, again with inline comments:

{
    "ShipMethodId": 6, // “ShipMethodId” from Calculate
    "StoreId": 3, // Stores call
    "CurrencyCode": "usd", // On the selected Payment Method
    "ShippingAddress": { // Get this from the cust record, or a form
      "Street1": "350 S 400 W",
	 "Street2": "350 S 400 W",
      "City": "Lindon",
      "Region": "UT", // Products -> Get Regions may help here
      "PostalCode": "84042",
      "CountryCode": "us" // Also in Product -> Get Regions
    },

    "Items": [
      {
        "ItemId": 30, // From your cart that’s used Get Items
        "Quantity": 3
      }
    ],
	"Payments": [{ // See the User Payment section for this mapping
		"Amount": 154.85,
		"SavePaymentMethodId": 1,
		"OnFileCard": "Primary",
		"CurrencyCode": "usd",
		"MerchantId": 99, 
		"SavePayment": true,
		"OrderCreditCard": {
		  "CardToken": "abc123456",
		  "NameOnCard": "Sammy Spacey",
		  "Last4": "1234",
		  "CardType": "Visa",
		  "ExpirationMonth": 12,
		  "ExpirationYear": 2022
		}
	}]
}

Response: (201 - created)

{
  "OrderId": 50306, // Order ID in Disco
  "Total": 40.65,
  "SubTotal": 25.7,
  "TaxTotal": 0,
  "ShippingTotal": 14.95,
  "DiscountTotal": 0,
  "CurrencyCode": null, 
  "QvTotal": 0,
  "CvTotal": 0,
  "TaxableSubTotal": 25.7,
  "Items": null // If this is null, use
    // https://dsapi-stage.directscale.com/v1/orders/{orderId}
                // to fetch Order Item information.
}

View/List Orders

To see the order, use the calls:

  • GET https://dsapi-stage.directscale.com/v1/orders/{orderId}

OR

  • GET https://dsapi-stage.directscale.com/v1/customers/{customerId}/orders


Having Trouble?

We want this to be a good experience for you. Visit the Help Center and click on the Help button to ask Customer Care for guidance. They’ll direct you or point you to resources that can help.

Thank you for working with DirectScale!