API Purpose
The Americommerce Spark Pay Online Stores API is an incredibly powerful way of interacting with the core Americommerce Spark Pay Online Stores data that drives the front end and administration console. Using the API you can read/write data such as customer information, product information, orders and almost every piece of data Americommerce Spark Pay Online Stores uses.
Common uses include:
- Integrating with inhouse and 3rd party systems ( Americommerce Spark Pay Online Stores even uses it’s own API for integrations)
- Syncing data between different sources such as inventory, orders and customers
- Making webpages that reference store data for use in your store or other external stores
- Much more…
Not typically used for: (but can be)
- Changing the front end of your web store’s design, look and feel
- In other words you wouldn’t necessarily use this to change the myAccount page to look like how you want, but you may use it to build your own myAccount pages that override our default ones, or to integrate pages into the myAccount area.
- This would typically be done by our Client Side Javascript API
- There are also custom hooks in various processes/workflows that can be tapped into to call out to other remote services for things like Tax Calculations, Shipping Calculations, Rewards Point Systems, Real Time Inventory Calls, etc.
Where is it and how to reference
The API is referenced right off of your site. You can navigate to this URL in your web browser to get a list of the methods available to you and their descriptions, how they work, their data model and much more. Be sure to reference the https version, as the http version will list the methods but will not work when calling the methods.
Main Architecture and how it interacts with AmeriCommerce
Americommerce Spark Pay Online Stores is comprised of the Front End site, the Admin Panel site and the database that stores all of the information for both. The developers at Americommerce Spark Pay Online Stores use an nTier hybrid component oriented and object oriented architecture to interact with all business and data logic.
We have what we call Entity objects that are completely object oriented calls into our deeper architecture. These are simple logical pieces such as the Customer entity, Product entity, etc. They have methods called .Post(), .Validate(), etc. and are very easy to use. These Entity objects call deeper into our architecture and hit the transport layers, business rules layer and database layers and others used for proxy, serialization and remoting.
The web service API sits between the entity objects and the front end application allowing you to call 100% of the validation and helpers that we have at every single level of our architecture. Due to the stateless nature of the API we have done some very creative things with the transports to make the web service as stateful as possible.
For the web service you pass back and forth an XML Transport object (a property bag) of all fields of an object in many cases, there are helpers and other methods that return other data as well. These property bags are exact duplicates of our entity object’s properties and serialize directly into our entity objects to make an instance of them for processing.
A typical call may look like this:
- Call API to get customer with email bob@site.com
- API returns a transport object with all of bob’s information (a copy of our Entity object that we use)
- You edit bob’s customer information locally in your code
- Call the API to Post() bob’s newly changed information
- API processes, validates against business rules and sends you back a new transport object with all of bob’s information, or the errors found. Optionally a Boolean of true or false can be passed back.
- Bob’s information is now up-to-date in AmeriCommerce.
Basic method references
Every web method exposed thru the Americommerce Spark Pay Online Stores API has a defined naming structure which begins with it’s entity name _ method name, such as Customer_GetByKey, Customer_Save, Customer_FillAddressCollection, etc. See them all in the primary listing by visiting the url of the web service. Each method is explained.
There are also helper methods exposed that do particular things like rebuilds the category tree Category_RebuildCategoryTree or DoTimedEvents which calls into the timed events in AmeriCommerce. These helpers are there to pull or perform more specific functions. Even things like getting the current orders for the day and such would be helpers in this list. They are intermingled throughout the Entity calls.
How to reference from Visual Studio
Visual Studio 2005+ offers some great ways to interact with webservices in a seamless way. They build references and strongly typed objects that you can use in your code to streamline the process and it removes the worry and bother of working directly with the XML of the requests. This can save you hours.
Using Visual Studio to make these strongly typed objects allows you to call methods and create objects using Intellisense quickly and easily. It allows for direct referencing oCustomer.FirstName and setting it easily.
To work with the API natively in Visual Studio follow these steps:
- Open Visual Studio and navigate to your web or windows project.
- Right click on the project where you will need to reference the web service
- You will see “Add Web Reference” in the right click menu
- Enter the URL to the web service in the box, click ‘Go’, then rename the web service name to ACAPI to help ease coding (the default name is not very good).
- After this Visual Studio will add the web reference and you will see it. It adds overridable config settings that contain the address of the service and such as well for you automatically in app.config or web.config.
- If we update your website or the API changes, you can simply right click “ACAPI” and select “update web reference” and all new changes will be picked up.
- You are ready to reference the web service and begin coding.
Other Ways To Consume Web Service
Since this is a web service any development environment can interact with it. It’s completely platform agnostic.
Other options include:
- Ruby on Rails consumption
- PHP consumption
- Javascript consumption
- J2EE consumption
- C++, Powerbuilder and others
- See our API Examples Article to see how to work with these other languages.
.Net also provides the WSDL.exe command line tool which will build the web service proxy classes in a dll for your reference from other systems instead of doing it from Visual Studio. Read more here:
Security and Logging In
The Americommerce Spark Pay Online Stores web service uses the user accounts that you setup under Global Settings in the Americommerce Spark Pay Online Stores administration console so that you can control Role Based Security permissions for each area, and usernames/passwords accordingly without intervention from AmeriCommerce. This gives you complete control over logging in/out of the web service. Read more about setting up an API User here.
Additionally, we also require an API Security Token to be sent as well, this can be retrieved from Americommerce Spark Pay Online Stores support personnel and must be kept strictly confidential.
All web methods can only be accessed over https as well which helps to limit security threats and it also encrypts the data being sent back and forth.
Your SOAP request would look like this:
<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
<soap12:Header>
<AmeriCommerceHeaderInfo xmlns="http://www.americommerce.com">
<UserName>string</UserName>
<Password>string</Password>
<SecurityToken>string</SecurityToken>
</AmeriCommerceHeaderInfo>
</soap12:Header>
<soap12:Body>
<TestTransport xmlns="http://www.americommerce.com" />
</soap12:Body>
</soap12:Envelope>
Use Visual Studio
To make things simpler, Visual Studio makes accessing/changing this information a bit easier, see below examples for how to login using c#.
//Reference the web service
AmeriCommerceDb.AmeriCommerceDatabaseIO oWS = new AmeriCommerceDb.AmeriCommerceDatabaseIO();
//create the header and set the values, after that every call to the web service is covered and you will not have to set again
AmeriCommerceDb.AmeriCommerceHeaderInfo oHeader = new AmeriCommerceHeaderInfo();
oHeader.UserName = "yourusername";
oHeader.Password = "yourpassword";
oHeader.SecurityToken = "yoursecuritytoken";
oWS.AmeriCommerceHeaderInfoValue = oHeader;
Session Tracking & Remote Carting
For some items on the API you need to have access to a client specific session for the current person on the site. Items such as Add To Cart and Wish Lists require a client specific session to mimic the front end of the site. Primarily this is only needed if you intend to use AddToCart() method on the web service API and then want to navigate to the store’s cart and checkout pages and have the items show up, without session tracking on, the cart will be blank and you will be adding to a different session than the user on the site. Just reading and writing data from the API has no need for session tracking.
You can initiate a session in 1 of a few ways:
- Visit any Americommerce Spark Pay Online Stores storefront page like normal, this will start a session and set a session key in the client’s cookies on their browser. This cookie can be read from the browsers cookies and used anywhere required such as “AddToCart()” methods on the web service.
- Call Session_StartSession() on the web service, this will start a session on the Americommerce Spark Pay Online Stores website and give you a key to reference the session. You will then need to set the “SessionId” cookie on the browser if you intend to call session related methods on the web service like “AddToCart()”. It may be handy to cache the key in your application for easy reference.
- Call Session_StartSession() on the web service. Send the “z=[sessionid]” parameter on any url going to the Americommerce Spark Pay Online Stores front end with a session key and it will set the session and cookie upon first loading of that page. At that point the session cookie is set for the store domain.
- Call Session_StartSession() on the web service. You can use a transparent gif that Americommerce Spark Pay Online Stores hosts and pass in the “z=[sessionid]” parameter on the url to that image which will set the session for that user.
- Grab the session id off of yourdomain.com/store/session.aspx. This page outputs the session key and session id for your usage, debugging and tracking. This page can be loaded in an iframe or similar and the cookie or value from the iframe can be retrieved.
Note: If you are hosting pages on another server and still using some Americommerce Spark Pay Online Stores pages you must plan for a user FIRST entering the ‘site’ either on those pages or directly accessing an Americommerce Spark Pay Online Stores page first. The session must flow back and forth seamlessly or you will lose track of cart contents and click paths for that user. Be sure to test between FireFox and Internet Explorer as they both handle cookies a bit differently.
Sample getting a customer, set data and save using C#
This sample routine shows how to get a customer’s information from AmeriCommerce, change it and resave that information back to AmeriCommerce.
public void TestSaveCustomerInformationToAmeriCommerce()
{
//Reference the web service
AmeriCommerceDb.AmeriCommerceDatabaseIO oWS = new AmeriCommerceDb.AmeriCommerceDatabaseIO();
//create the header and set the values, after that every call to the web service is covered and you will not have to set again
AmeriCommerceDb.AmeriCommerceHeaderInfo oHeader = new AmeriCommerceHeaderInfo();
oHeader.UserName = "yourusername";
oHeader.Password = "yourpassword";
oHeader.SecurityToken = "yoursecuritytoken";
oWS.AmeriCommerceHeaderInfoValue = oHeader;
//Not necessary but you can override it directly if you like
oWS.Url = "https://www.yoursite.com/store/ws/AmeriCommerceDb.asmx";
//Make a customer transport to work with
colPictuAmeriCommerceDb.CustomerTrans oCustomer = null;
//Get an existing customer by email and store id from the web service
//1 references your main store id, customers are saved per store.
oWS.Customer_GetByEmailAndStore("bob@yoursite.com", 1);
//oCustomer now has all information from the Americommerce Spark Pay Online Stores system on it,
//let's now override AmeriCommerce's data and save it back to AmeriCommerce.
//Set key customer information
oCustomer.firstName = "Bob";
oCustomer.lastName = "Johnson";
oCustomer.phoneNumber = "409-898-5656";
//saving integers, decimals and other objects are a little weird,
//you must create an instance of our nullable data types
AmeriCommerceDb.DataInt32 iStoreID = new AmeriCommerceDb.DataInt32();
iStoreID.Value = 1;
oCustomer.storeID = iStoreID;
//Check the data against all of the validation rules in all layers of the Americommerce Spark Pay Online Stores architecture
//returns a string of validation errors or 'Ok' if valid.
if (oWS.Customer_Validate(oCustomer) != "Ok")
return; //exit out or do something with the error text
//Save the data back to Americommerce Spark Pay Online Stores and return True if successful, false or error if not.
bool bSuccess = oWS.Customer_Save(oCustomer);
//There is also a method called Customer_SaveAndGet() which gets the new customer with its information in 1 call
//oCustomer = oWS.Customer_SaveAndGet(oCustomer);
//The save is complete, navigate to bob johnson in the admin and the new information will be there.
}
Sample Saving a NEW Customer using C#
Working with collections in C#
Collections of objects in XML and when put into Visual Studio’s strongly typed objects are a bit tricky to work with, here is a streamlined example that makes it a bit easier by translating the array back and forth.
public void TestSaveProductAdditionalCategoriesToAmeriCommerce()
{
//Reference the web service
AmeriCommerceDb.AmeriCommerceDatabaseIO oWS = new AmeriCommerceDb.AmeriCommerceDatabaseIO();
//create the header and set the values, after that every call to the web service is covered and you will not have to set again
AmeriCommerceDb.AmeriCommerceHeaderInfo oHeader = new AmeriCommerceHeaderInfo();
oHeader.UserName = "yourusername";
oHeader.Password = "yourpassword";
oHeader.SecurityToken = "yoursecuritytoken";
oWS.AmeriCommerceHeaderInfoValue = oHeader;
//Get an existing customer by email and store id from the web service
//ITEM-12345 must exist in your store
AmeriCommerceDb.ProductTrans oProduct = oWS.Product_GetByItemNumber("ITEM-12345");
//Can set product information if you like
oProduct.itemName = "My Item";
oProduct.itemNr = "ITEM-12345";
//let's work with the picture collection and add a new picture
//Fill the picture collection with any existing pictures
//This returns your product object with all pictures on it from the AC system
oProduct = oWS.Product_FillProductPictureCollection(oProduct);
ArrayList colPictures = new ArrayList(oProduct.ProductPictureColTrans);
//Make a picture transport object to set properties on
AmeriCommerceDb.ProductPictureTrans oPrimaryPicture = null;
//just store the image reference in a string for comparisons
string sMyPictureUrl = "/images/products/item12345.jpg";
//Loop through the existing pictures on the product in question
//look for one already existing
bool bImageAlreadyExists = false;
foreach (object oItem in colPictures)
{
AmeriCommerceDb.ProductPictureTrans oPic = (AmeriCommerceDb.ProductPictureTrans)oItem;
if (oPic.ImageFile == sMyPictureUrl)
{
oPrimaryPicture = oPic; //set to the transport
bImageAlreadyExists = true;
}
}
if(bImageAlreadyExists == false)
oPrimaryPicture.IsNew = true; //so it will add the new picture
oPrimaryPicture.ImageFile = sMyPictureUrl;
oPrimaryPicture.IsPrimary = true; //makes it the default picture
//if it's new then add it to the products picture collection
//if it's not then its already there and we are just resetting its values
if (oPrimaryPicture.IsNew)//only add if its new because its a new picture
colPictures.Add(oPrimaryPicture);
//this long call handles assigning it properly back to the product
oProduct.ProductPictureColTrans = (AmeriCommerceDb.ProductPictureTrans[])colPictures.ToArray(typeof(AmeriCommerceDb.ProductPictureTrans));
//One interesting thing is you do NOT have to Save the pictures seperately...you can just save the product
//of course you can still process them seperately, but in many cases it's best to work with the parent object
//Check the data against all of the validation rules in all layers of the Americommerce Spark Pay Online Stores architecture
//returns a string of validation errors or 'Ok' if valid.
if (oWS.Product_Validate(oProduct) != "Ok")
return; //exit out or do something with the error text
//Save the data back to Americommerce Spark Pay Online Stores and return True if successful, false or error if not.
bool bSuccess = oWS.Product_Save(oProduct);
}
OTHER SAMPLES
This sample gets a list of orders for processing by order status:
AmeriCommerceDb.AmeriCommerceDatabaseIO oWS = new AmeriCommerceDb.AmeriCommerceDatabaseIO();
AmeriCommerceDb.AmeriCommerceHeaderInfo oHeader = new AmeriCommerceDb.AmeriCommerceHeaderInfo();
oHeader.UserName = "yourusername";
oHeader.Password = "yourpass";
oHeader.SecurityToken = "yourtoken";
oWS.AmeriCommerceHeaderInfoValue = oHeader;
string sResults = "";
int iOrderStatusID = 6; //use whatever id you would like or look up the ID by name using the webservice
AmeriCommerceDb.OrderTrans[] oOrders = oWS.Order_GetByOrderStatus(iOrderStatusID);
ArrayList colOrders = new ArrayList(oOrders); //just for working easily with the collection
for(int x = 0; x < colOrders.Count; x++) //use a for loop because we are setting the object below
{
AmeriCommerceDb.OrderTrans oOrder = (AmeriCommerceDb.OrderTrans)colOrders[x]; //setup our object for reading
//do stuff with the order here
sResults += "Order ID is " + oOrder.orderID.Value + "<br/>";
//fill the order items collection
//this call fills the order items onto your already existing order object
oOrder = oWS.Order_FillOrderItemCollection(oOrder);
ArrayList colOrderItems = new ArrayList(oOrder.OrderItemColTrans);
foreach (AmeriCommerceDb.OrderItemTrans oOrderItem in colOrderItems)
{
sResults += " Purchased " + oOrderItem.itemName + "<br/>";
}
}
Response.Write(sResults);