Live Shipping Rates
We return Live Shipping Rates on Shopify, Magento and WooCommerce for now (January 2020)
How it works?
Create new shipping service on the store
On WooCommerce stores there can be an unlimited amount of services, but on Shopify you can create only one service (Shopify limit).
To create the service you’ll have to specify the name of the service and callback url, that will return us shipping rates. We validate the callback when it is being created by sending test request to it. Test requests contain header X-Shipping-Service-Test-Request: 1.
To check it the request was really sent by API2Cart, compare header signature X-Shipping-Service-Signature
The signature is built based on all headers that start with X-Shipping-Service, except for X-Shipping-Service-Signature.
1. Create array of headers, let the header name be its key, its value - the header value string.
Sort the headers by the name.
2. Create the string for signature, that is made of headers. For that, encode the array of headers in JSON and concatenate from request body.
3. Calculate sha256 signature in binary format
4. Convert the binary signature to base64
$headersToSign = [
'X-Shipping-Service-Test-Request' => '1',
'X-Shipping-Service-Request-Timestamp' => '1553177278'
$headersJson = json_encode($headers);
$sign = base64_encode(hash_hmac('sha256', $headersJson . $body, $signingKey, true));
Test request example (from API2Cart)
Once you get test request, your endpoint have to respond in JSON format
The response will differ for different shopping carts
For instance, your callback response structure for Shopify will look like the following:
For WooCommerce the response structure will look like that:
When we send a certain amount of packages, we expect to get the same amount of packages_rates objects. The property rates can be empty, which means there can be no rates for a certain package.
If the structure is not valid, we return an error. For example, you will get error when you pass a string in total_cost.
If the callback returns 404 error code, we will not try again
If the callback returns 200 error code, we will check response validity and then return it to the store in the format that fits the store.
If the store returns 200 error code, butwith empty or incorrect response, we will wait 2 seconds and will try again.
If the callback don’t respond in 15 seconds, we will throw an error and will not try again.
If everything is ok, the new service will be created.
2) As the store requests rates, we unify the request and send it to callback specified when the service was created. Also, we send X-Shipping-Service-Id header.
If the response is not valid or the callback didn’t answer, we will log the error and increment error count of the shipping service by 1. If the next request will be successful, the count will be reduced to zero. Soon we will add the functionality that will turn off the service when the error limit is exceeded.