How to add Custom Shipping method / Carrier on Shopify
First you need to understand how the API works, read https://shopify.dev/docs/admin-api/rest/reference/shipping-and-fulfillment/carrierservice
The idea is very simple. In order for you to generate a custom dynamic carrier or shipping. You need to send a config data to Shopify which will has names and call back url at least once.
"carrier_service": {
"name": " Shipping Rate Provider Custom",
"callback_url": "https://yourdomain.org/shopify/carrier_callback.php",
"service_discovery": true
}
Call back URL is the one responsible for generating the carrier options. This is the shipping method with rates that is connected to Shopify checkout page. You only need to run it once, when it’s already there the call back URL will do all the work.
See complete code below with PHP Curl
Please simple code below
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
$d = '{
"carrier_service": {
"name": " Shipping Rate Provider Custom",
"callback_url": "https://yourdomain.org/shopify/carrier_callback.php",
"service_discovery": true
}
}';
$d = json_decode($d);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($d));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close ($ch);
Now, assuming that your have already ran the code above, you can now go to your callback url which in this case is on https://yourdomain.org/shopify/carrier_callback.php. All you now have have to do is simple display a JOSN string on this format.
{ "rates": [ { "service_name": "canadapost-overnight", "service_code": "ON", "total_price": "1295", "description": "This is the fastest option by far", "currency": "CAD", "min_delivery_date": "2013-04-12 14:48:45 -0400", "max_delivery_date": "2013-04-12 14:48:45 -0400" }, { "service_name": "fedex-2dayground", "service_code": "2D", "total_price": "2934", "currency": "USD", "min_delivery_date": "2013-04-12 14:48:45 -0400", "max_delivery_date": "2013-04-12 14:48:45 -0400" }, { "service_name": "fedex-priorityovernight", "service_code": "1D", "total_price": "3587", "currency": "USD", "min_delivery_date": "2013-04-12 14:48:45 -0400", "max_delivery_date": "2013-04-12 14:48:45 -0400" } ] }
Now it’s all yours.