Shopify App Development

Shopify is a fast-growing online e-Commerce platform. A Shopify user can create online stores to sell his/her goods and services. An advantage of Shopify is that, unlike many other e-commerce platforms, we don’t need to install anything ourself. All shopify stores are hosted by shopify itself.

What is a Shopify App?

A shopify app can be said as an external software that can add features to our shopify store. An app can fetch products, modify products, delete products, view orders and lot more. There are two types of apps, Public and Private.

Public apps are apps that are available in the shopify app store and can be used in more than one store.

Private apps can be used in only one store an it cannot be submitted to the app store.

To develop a public app, the first thing we need to do is to register as a partner with shopify. A partner account will allow us to create shopify apps.

Hoping already registered, we’ll need to login to the partner account.

Creating an App

As we’ve logged in, we can see our account dashboard with many tabs on our left panel. Click on the Apps tab and select create a new app. It’ll redirect us to another form where our app information needs to be entered. The essential information will be the App Name, App URL and the Redirection URL. As for now, we are just filling the required fields.

App name can be any name you want for you app. It can be something that clearly describes what our app does.

App URL is the URL to which our app redirects when a merchant clicks on our app banner from their store admin.

Redirection URL is the URL to which the merchant will be redirected when he authorizes our app. It is specified in the redirect_uri parameter during our app authorization step.

After our app creation, shopify will generate API key and shared secret for our app which will be later used for our shopify API authentication.

You may click the above tab Edit App Store Listing to get the url for our app from where we can install it in our store which we will need later.

Creating a Development Store

Development stores are used for testing the apps that we develop. A development store has no time limits and all functionalities of a real shopify store is available except accepting payments. Instead shopify allows us to use its Bogus gateway to test our payments. To create a development store, click on the development store tab on our left panel and click Create a Development Store.

Provide with your development store name and login details and click create. It’ll navigate us to our test store’s dashboard. Now we’ll be able to access our store at,

https://storename.myshopify.com/admin

Setting Bogus gateway

Bogus gateways are for testing payments, we need to click settings from our development store and select payments. Under the Accept credit cards section select (for testing) Bogus gateway and click activate.

Then we can go to our online store front and place an order. At the payment details please give these informations.

For credit card number,

1 to see a successful transaction
2 to see a failed transaction
3 to see an exception that shows an error message

For CVV enter any 3 digit number and for Expiry date give any future date.

APP Development

Now its time to start app development. First lets create the file composer.json in our app directory with the following contents.

{
    "minimum-stability": "dev",
    "require": {
        "sandeepshetty/shopify_api": "dev-master"
    }
}

Lets now install all the shopfiy API libraries and its dependencies. For that execute this command from the directory where composer.json is,

php composer.phar install

Make sure composer is already installed, and if not install it using this command,

curl -s http://getcomposer.org/installer | php

Once composer is installed re-execute the above command for installing API libraries.

If everything goes well, we’ll see these folders in the vendor directory.

Composer
sandeepshetty
autoload.php

Setting up database for our App

We need to set up a database for storing our data. We have both app data and store data. So lets create two tables in our database.

Lets create tbl_appsettings for our app data.

CREATE TABLE IF NOT EXISTS `tbl_appsettings` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `api_key` varchar(300) DEFAULT NULL,
  `redirect_url` varchar(300) DEFAULT NULL,
  `permissions` text,
  `shared_secret` varchar(300) NOT NULL,
  PRIMARY KEY (`id`)
)

Here api_key is the key we got before when we created our app. Redirect_url is the url that our app will be redirected when it is installed by a merchant. Permissions are an array of permissions for our app and shared_secret is the secret key that identifies us as the owner for the app.
Now lets create tbl_usersettings for our store data.

CREATE TABLE IF NOT EXISTS `tbl_usersettings` ( 
	`id` int(11) NOT NULL AUTO_INCREMENT,
	`access_token` text NOT NULL,
	`store_name` varchar(300) NOT NULL,
	PRIMARY KEY (`id`)
)

Here access_token is the permanent access token of our online store and store name is the name we’ve given for our store.

Setting up the permissions for our App

Lets create the file that we need our app to be redirected soon after the merchant installs it. Please make sure that we’ve given this page’s url in the app url section in the app creation time. So lets create myshopifyapp.php as our page. The content will be,

<?php
require 'vendor/autoload.php';
use sandeepshetty\shopify_api;
?>

You might have noticed, that we’ve included the library downloaded before using composer. When an app is accessed from a store it’ll always pass the shop name as a parameter with the call back url we set at the time of app creation. As we have the API library lets make sure that the shop name already exist with shopify, to make sure its a valid request.

For that we may use the is_valid_request() from the library to make sure not just everybody can access the URL. If the request is valid we’ll save the shopify signature and the shop name in our session. This will be used to determine a user is logged in or not.

In case if the store name is not available in the database, we get the permissions from the database, and then convert it into an array and supply it to the permission_url() method. We also pass the shop name and api key with it. The permission_url() method will then generate a URL to the page that asks the merchant to give permission for the app to get specific data. So our myshopifyapp.php will have these as contents.

<?php
session_start(); //start a session
require 'vendor/autoload.php';
use sandeepshetty\shopify_api;
$db = new Mysqli("localhost", "root", "", "shopify_app");
if($db->connect_errno){
	die('Connect Error: ' . $db->connect_errno);
}

$select_settings = $db->query("SELECT * FROM tbl_appsettings WHERE id = 1");
$app_settings = $select_settings->fetch_object();

if(!empty($_GET['shop'])){ //check if the shop name is passed in the URL
	$shop = $_GET['shop']; //shop-name.myshopify.com

  	$select_store = $db->query("SELECT store_name FROM tbl_usersettings WHERE store_name = '$shop'"); //check if the store exists
  
  	if($select_store->num_rows > 0){
      
	      	if(shopify_api\is_valid_request($_GET, $app_settings->shared_secret)){ 		//check if its a valid request from Shopify        
		  	$_SESSION['shopify_signature'] = $_GET['signature'];
		  	$_SESSION['shop'] = $shop;
		  	header('Location: http://localhost/shopify/admin.php'); //redirect to the admin page
	      	}
      
	}else{     

	      	//convert the permissions to an array
	      	$permissions = json_decode($app_settings->permissions, true);

	      	//get the permission url
	      	$permission_url = shopify_api\permission_url(
	      	   	$_GET['shop'], $app_settings->api_key, $permissions
	      	);
	      	$permission_url .= '&redirect_uri=' . $app_settings->redirect_url;

		header('Location: ' . $permission_url); //redirect to the permission url
	}
}
?>

When we have the permission from the merchant, it’ll be redirected to the redirect_uri specified in our permission URL. The merchant will be redirected to this redirect_uri for only the first time he installs this app. So it doesn’t need to be the same as the app URL we set at the time of app creation. Now we can generate a permanent access token by passing the store name, api key, shared secret, and the shopify temporary code to the oauth_access_token() method. And then we save all the store details in the database and navigate to the admin page. So lets add this piece of code to our myshopifyapp.php file.

<?php
if(!empty($_GET['shop']) && !empty($_GET['code'])){

  	$shop = $_GET['shop']; //shop name

  	//get permanent access token
  	$access_token = shopify_api\oauth_access_token(
      		$_GET['shop'], $app_settings->api_key, $app_settings->shared_secret, $_GET['code']
  	);

  	//save the shop details to the database
  	$db->query("
     		INSERT INTO tbl_usersettings 
     		SET access_token = '$access_token',
     		store_name = '$shop'
 	");

  	//save the signature and shop name to the current session
  	$_SESSION['shopify_signature'] = $_GET['signature'];
  	$_SESSION['shop'] = $shop;

  	header('Location: http://localhost/shopify/myshopifyapp.php /admin.php');
}
?>

Now we’ve set the permissions for our app. Now we’ll install our app in the development store we created earlier. As our app is an unpublished one we wont find it in the shopify app store. So we’ll need a URL that points to our app. For that there are two ways. One is to access the url we had in the last step of app creation earlier. The other way is to access the below URL with our shop-name and api key in it.

http://shop-name.myshopify.com/admin/api/auth?api_key=xyz

API requests from our App

Its time to perform some actions with the store we’ve installed our app in. As we don’t have any data to fetch from our store, lets go and create some sample products. Now we can fetch those products from our store using shopify API. For that we need to call the client method from our API library by passing shop name, api key, access token and shared secret. Lets now create admin.php with,

<?php
$shopify = shopify_api\client(
  $shop, $shop_data->access_token, $app_settings->api_key, $app_settings->shared_secret
);

$products = $shopify('GET', '/admin/products.json', array('published_status' => 'published'));
?>

Now we can use the $shopify variable to call methods from our API library. In the above code we get a list of products from our store to the $products variable.
As we are retrieving something from our store, we use GET as our first argument. The second argument products.json refers to the products in our store. The third argument is an array of arguments, which filters the result to only show published products in our store which are available for the customers to view. We can also use, the product_type argument to retrieve a list a products which belong to a particular product type.

The response may look like this

Array(
    [0] => Array
        (
            [body_html] => striped shirt
            [created_at] => 2013-10-13T23:09:53-04:00
            [handle] => striped-shirt
            [id] => 164668989
            [product_type] => t-shirts
            [published_at] => 2013-10-13T23:09:13-04:00
            [published_scope] => global
            [template_suffix] => 
            [title] => striped shirt
            [updated_at] => 2013-10-14T01:31:44-04:00
            [vendor] => abc
            [tags] => 
            [variants] => Array
                (
                    [0] => Array
                        (
                            [barcode] => 
                            [compare_at_price] => 
                            [created_at] => 2013-10-13T23:09:53-04:00
                            [fulfillment_service] => manual
                            [grams] => 234
                            [id] => 378254785
                            [inventory_management] => 
                            [inventory_policy] => deny
                            [option1] => Default Title
                            [option2] => 
                            [option3] => 
                            [position] => 1
                            [price] => 322.00
                            [product_id] => 164668989
                            [requires_shipping] => 1
                            [sku] => 
                            [taxable] => 1
                            [title] => Default Title
                            [updated_at] => 2013-10-13T23:09:53-04:00
                            [inventory_quantity] => 0
                        )

                )

            [options] => Array
                (
                    [0] => Array
                        (
                            [id] => 197676733
                            [name] => Title
                            [position] => 1
                            [product_id] => 164668989
                        )

                )

            [images] => Array
                (
                    [0] => Array
                        (
                            [created_at] => 2013-10-14T01:31:39-04:00
                            [id] => 330590691
                            [position] => 1
                            [product_id] => 164668989
                            [updated_at] => 2013-10-14T01:31:39-04:00
                            [src] => http://cdn.shopify.com/s/files/1/0279/0287/products/striped .jpg?305
                        )

                )

            [image] => Array
                (
                    [created_at] => 2013-10-14T01:31:39-04:00
                    [id] => 330590691
                    [position] => 1
                    [product_id] => 164668989
                    [updated_at] => 2013-10-14T01:31:39-04:00
                    [src] => http://cdn.shopify.com/s/files/1/0279/0287/products/striped .jpg?305
                )

        )
)

Here we list all the associated fields of a product. We can also fetch only the required fields, by passing the fields as an argument in an array like.

<?php
$arguments = array(
  'published_status' => 'published',
  'fields' => 'body_html,created_at,handle,id,title,image'
);

$products = $shopify('GET', '/admin/products.json', $arguments);
?>

Fields array can be given as comma separated.

Lets consider another scenario with Orders. Customers make orders in our store. We can fetch orders of our store by,

<?php
$arguments = array(
  'limit' => '10', //default:50
  'page' => '1', //default: 1
  'status' => 'open',

);
$orders = $shopify('GET', '/admin/orders.json', $arguments);
?>

Here we are using orders.json to refer orders in our store. We pass few arguments with our request with an order limit set to 10 and the status as open.

Webhooks

A webhook is an HTTP post or an HTTP callback. Instead of making API calls from our app at regular intervals to know whether a certain event has occurred, we can register a webhook which will send an HTTP request from the store to our app. This will help us to make less API calls and build more neat and robust apps.

The shopify API will let us do a lot of action with its webhook resource. Every webhook post will need a topic and an address. The topic will be the event when the webhook should be registered. Address will be the URI where the webhook will send the POST data.

A sample webhook for order creation event will look like,

POST /admin/webhooks.json
{
  "webhook": {
    "topic": "orders\/create",
    "address": "http:\/\/example.hostname.com\/",
    "format": "json"
  }
}

and the response will be like

HTTP/1.1 201 Created
{
  "webhook": {
    "id": 1047897619,
    "address": "http:\/\/example.hostname.com\/",
    "topic": "orders\/create",
    "created_at": "2017-01-31T14:32:06-05:00",
    "updated_at": "2017-01-31T14:32:06-05:00",
    "format": "json",
    "fields": [
    ],
    "metafield_namespaces": [
    ]
  }
}

We can get the event details in the page we’ve specified as the address above and can perform necessary actions to be done. Detailed documentation on webhooks can be seen at https://help.shopify.com/api/reference/webhook.

Conclusion

We can manipulate this app in such a way that it fulfills our needs. Creating an app in shopify involves creating a partners account, a development store and an app. A shopify app is much like a php app, apart from which a shopify app uses the shopify API to manipulate data from our shopify store. Furthur detailed documentation on the API tutorial is avilable at https://help.shopify.com/api/reference.

STILL SPENDING TIME ON SUPPORT?

Outsource your helpdesk support to save time and money. We have technicians available for little over 5 USD per hour in order to assist your customers with their technical questions. Grow your business and concentrate more on your SALES!

Xieles Support is a provider of reliable and affordable internet services, consisting of Outsourced 24×7 Technical Support, Remote Server Administration, Server Security, Linux Server Management, Windows Server Management and Helpdesk Management to Web Hosting companies, Data centers and ISPs around the world. We are experts in Linux and Windows Server Administration, Advanced Server Security, Server Security Hardening. Our primary focus is on absolute client satisfaction through sustainable pricing, proactively managed services, investment in hosting infrastructure and renowned customer support.

More About Xieles Support
2017-02-18T21:47:14+00:00 February 18th, 2017|Ecommerce, Shopify|0 Comments

Leave A Comment