Do you remember my last post where I showed you how to create an API using Slim? In the “Possibilities” section, I tried to expand its usage to interact with Magento or WordPress. Well, I recently had to integrate a 3rd party system with Shopify, an E-Commerce platform.

In this post, I’ll show you how to interact with the Shopify API in order to add products to your store, get your latest orders and many more fun activities!

This time we won’t use Slim. On one of my recent projects, I decided to use Laravel instead of my beloved Yii as my MVC framework. I have to say that the Laravel team did a great job. That’s why when I had to build my new API, I made the switch to Laravel’s Lumen.

Lumen is a micro-framework version of Laravel. It uses the exact same core but stripped down of extra features that would not necessarily be needed to build services and APIs. It focuses on speed while still using Laravel’s features like Eloquent, caching, queues, validation, routing, middleware.

1) Setup the Shopify store Private app

Go to the administration panel of your Shopify store > Apps > Private Apps

Create a new Private App and give it a name, “Shopify API” for example.

Creating a Private app will allow us to get Shopify API’s credentials for that specific store in order to make calls to the different endpoints.

2) Installation of the Lumen’s project

I created a repository on GitHub through which we’ll go step by step.

a) Lumen’s server requirements
Similar to Laravel’s:
PHP >= 5.4
Mcrypt PHP Extension
OpenSSL PHP Extension
Mbstring PHP Extension
Tokenizer PHP Extension

b) Clone the repository and install the project
Clone the repository on your Apache server

git clone https://github.com/fbouyer/lumen-shopify-api.git

Go inside the directory created

cd lumen-shopify-api

Download Composer

curl -sS https://getcomposer.org/installer | php

Install all the dependencies through Composer (Lumen Framework, Shopify API Client)

php composer.phar install

If you open “composer.json“, you’ll find the following packages:

"require": {
   "laravel/lumen-framework": "5.0.*",
   "vlucas/phpdotenv": "~1.0"
},
"require-dev": {
   "phpunit/phpunit": "~4.0",
   "phpish/http": "dev-master",
   "phpish/shopify": "dev-master"
},

“phpish/shopify” is the package we’ll use to call the Shopify API. It’s a very simple Shopify API client that will save us a lot of time and lines of code.

3) Setup Shopify API Client credentials in Lumen

The Shopify API client will need the set of credentials to know which store to interact with and get permissions.

Make a copy of “.env.example” and name it “.env

In “.env” change the values of:
SHOPIFY_SHOP, this is the URL of your Shopify shop
SHOPIFY_API_KEY, you will find this on the Shopify private app page
SHOPIFY_PASSWORD, you will find this on the Shopify private app page

And that’s about it!

4) Create your first product

To make it easier, I created a test route/controller with a dummy product ready to be pushed to your store.

Open app/Http/Controllers/ExampleController.php

You will find a “createProducts” method, let’s go through it.

// Initialize the Shopify API Client
$shopify = shopifyclient(env('SHOPIFY_SHOP'), env('SHOPIFY_API_KEY'), env('SHOPIFY_PASSWORD'), true);

This will create a Shopify API client (using phpish/shopify package) and initialize it with your store private app credentials that you added to the “.env” file.

// Product and its variants data
$productData = [
   'product' => [
       "title" => 'T-Shirt',
       "body_html" => 'This is a great T-Shirt!',
       "vendor" => 'Awesome Company',
       "options" => [
           ['name' => 'Color'],
           ['name' => 'Size']
       ],
       "published" => true,
       "variants" => [
           [
               'price' => 35,
               'sku' => 'blue-tshirt',
               'inventory_management' => 'shopify',
               'inventory_quantity' => 10,
               'option1' => 'Blue',
               'option2' => 'Large'
           ],
           [
               'price' => 30,
               'sku' => 'red-small-tshirt',
               'inventory_management' => 'shopify',
               'inventory_quantity' => 10,
               'option1' => 'Red',
               'option2' => 'Small'
           ]
       ]
   ]
];

This array contains our product and its variants data. I will assume that you know Shopify’s product architecture, if not, it is explained in the Shopify API documentation. I recommend going through this documentation to discover all the endpoints available and their parameters.

In the above array, we have a T-Shirt product that has 2 variants. To explain it in “Magento” terms, we have a configurable product that has two configurable attributes; “Size” and “Color”. The configurable products have 2 simple products attached, one “Small” and “Red”, the other “Large” and “Blue”.

And finally:

// Make a POST call to the Products endpoint of the Shopify API
// with our product data automatically JSON encoded.
// It will return a JSON response of the product created or an error
$product = $shopify('POST /admin/products.json', [], $productData);

return $product;

Now to create our product just go to:
http://path_to_lumen/create-products

I recommend creating a VirtualHost in Apache for this project that will serve the directory lumen-shopify-api/public otherwise you might get a 404 error.

If everything went well you should see a response like this in your browser:

Screen Shot 2015-06-11 at 4.44.36 PM

Congrats! You created your first product!

Now go to your store, your product should look like this:

Screen Shot 2015-06-11 at 2.42.39 PM

5) And now what?

Okay, you created your first product through the Shopify API, through your own API. Wait, what? Yeah, it doesn’t sound very efficient. Well, now that you’re a little bit more familiar with our environment, let’s unleash its full potential. I mostly use this project as a “middle-man” between systems.

Example: you need to sync your Shopify orders/sales with a 3rd party system or a custom project. Let’s say, every 5 minutes, the 3rd party system makes a call to your API to get new sales from Shopify.

First I would create a new controller called SaleController with a method “list”. If you go to the Shopify API documentation, you’ll find the sale endpoint, the rest of the code is easy-peasy.

// Make a GET call to the Orders endpoint which will
// return an array of sales
$sales = $shopify('GET /admin/orders.json', [], []);

// Loop through the array and make any data transformation necessary to comply with your 3rd party system requirement
$sales = /* code here */

return $sales;

In the file “app/Http/routes.php“, after the “create-products” route add the new sale route:

$app->group(['namespace' => 'AppHttpControllers'], function($group){
   $group->get('create-products', 'ExampleController@createProducts');
   $group->get('sales', 'SaleController@list');
});

By going to http://path_to_lumen/sales, you’ll get a formatted list of your Shopify sales, ready to be integrated.

Now think of all the other possibilities, product management, stock and pricing, user management, etc. Isn’t integration fun?

6) Extra: Logging

For those who may have used the logging function in my previous post on Slim. I figured that you might like being able to do the same thing in Lumen.

In “app/Http/Middleware”, you’ll find “LogMiddleware.php“. You should go read the Middleware documentation in Laravel if you’re not familiar with it.

In “bootstrap/app.php”, uncomment the following lines to enable it:

$app->withFacades();

'AppHttpMiddlewareLogMiddleware',

Log::pushHandler(new MonologHandlerStreamHandler(storage_path().'/logs/log-'.date('Ymd').'.log'));

You’ll find all your API logs in daily log files under “storage/logs”:

GitHub repository