How To Build Shopify Apps with PHP

How To Build Shopify Apps With PHP (Tutorial Series)

We have a Shopify App Development Course! Be one of the first students!

Are you looking for an in-depth guide on how to create Shopify apps? Click the enroll button to get started!

In the previous article, through the Shopify developer, we set up the Shopify app that we’re going to use in this article. If you haven’t read the article yet or if you have no Shopify app ready yet, you may read the first part of this series to help you catch up.

Getting Started

To make your Shopify app work, your Shopify app must be authenticated by the store. That means that the shop owner must install your Shopify app and give you the permission you needed to work on their store. For example, displaying a list of available products. This process is mainly done by OAuth, which is a very highly secured method for communication between applications.

It is also important to know that every shop that installs your Shopify app, they have an access token that they need to use to keep their session running. That token can be saved to your database

Generating Shopify API Token

To build Shopify app using PHP, we’ll be using the client that I’m personally using which is the Shopify Generating API Token Guide by Alex. If you don’t have it yet, you may download it from GitHub and extract the files to your project.

Source Files

Shopify API client free download
  • inc – this folder contains a PHP file (functions.php) that contains a function that you can use to make Shopify actions like displaying the products from a collection.
  • api_call_write_products.php – An example PHP file to make actions like modify a product. You can read the file and study it yourself. But in this tutorial, we’ll be making it from a scratch.
  • generate_token.php – PHP file for generating token per store. This file we’ll be used after the store install the app.
  • install.php – PHP file for Shopify app installment. self-explanatory.

install.php

<?php

// Set variables for our request
$shop = $_GET['shop'];

$api_key = "ASSIGN YOUR API KEY HERE";
$scopes = "read_orders,write_products";
$redirect_uri = "http://YOUR-DOMAIN-NAME.COM/generate_token.php";

// Build install/approval URL to redirect to
$install_url = "https://" . $shop . "/admin/oauth/authorize?client_id=" . $api_key . "&scope=" . $scopes . "&redirect_uri=" . urlencode($redirect_uri);

// Redirect
header("Location: " . $install_url);
die();
Code language: PHP (php)

Process Breakdown

First, assign the value of $_GET[‘shop’] to the variable $shop. If you don’t know where that value is coming from. It’s from the URL that the user will be visiting. For example:

https://example.com/install.php?shop=example.myshopify.com

$api_key variable is where you’ll be assigning your API key.
You can get your API key from your developer app page.

How To Build Shopify Apps With PHP

You may leave the $scope variable.

$redirect_uri should contain the URL of your generate_token.php file
$install_url is a variable that contains the complete URL where the user will be prompted to install the app.

After setting up the variables, redirection to the URL from $install_url variable will happen.

Important! You should only change the value of the $api_key and $redirect_uri variables.

generate_token.php

<?php
// Get our helper functions
require_once("inc/functions.php");

// Set variables for our request
$api_key = "ASSIGN YOUR API KEY HERE";
$shared_secret = "ASSIGN YOUR SECRET KEY HERE";

$params = $_GET; // Retrieve all request parameters
$hmac = $_GET['hmac']; // Retrieve HMAC request parameter

$params = array_diff_key($params, array('hmac' => '')); // Remove hmac from params
ksort($params); // Sort params lexographically
$computed_hmac = hash_hmac('sha256', http_build_query($params), $shared_secret);

// Use hmac data to check that the response is from Shopify or not
if (hash_equals($hmac, $computed_hmac)) {
	// Set variables for our request
	$query = array(
		"client_id" => $api_key, // Your API key
		"client_secret" => $shared_secret, // Your app credentials (secret key)
		"code" => $params['code'] // Grab the access key from the URL
	);
	// Generate access token URL
	$access_token_url = "https://" . $params['shop'] . "/admin/oauth/access_token";
	// Configure curl client and execute request
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_URL, $access_token_url);
	curl_setopt($ch, CURLOPT_POST, count($query));
	curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($query));
	$result = curl_exec($ch);
	curl_close($ch);
	// Store the access token
	$result = json_decode($result, true);
	$access_token = $result['access_token'];
	// Show the access token (don't do this in production!)
	echo $access_token;
} else {
	// Someone is trying to be shady!
	die('This request is NOT from Shopify!');
}
Code language: PHP (php)

Before we proceed, make sure you change the value of the variables $api_key and $shared_secret. Again, you can get this data from your developer app dashboard.

If you noticed, the code above is using cURL client to execute requests. These requests will give you a value which is a JSON data type and that needs to be decoded so that PHP can use this value.

After getting the access token, you may add a MySQL query to save the value of the $access_token variable for future use but if you want to learn how to easily store it in the database, then you might as well check this link below (trust me it’s very easy):

Installing the Shopify App

Once everything is set up, you may go to your project URL and run install.php. To do this, you must include the variable shop in the URL. For example:

https://example.com/example/install.php?shop=shop.myshopify.com

Make sure it’s the same URL from your app dashboard. Otherwise, you will encounter errors.

How To Install Shopify Apps With PHP


By going to your install.php, you will see this confirmation to install the app:

Image of Building Shopify Apps with PHP

Conclusion

Congratulations! If you’ve seen the same page like mine, that means that your install.php and other files are working.

To display products using Shopify API and PHP. You may read the following article.

16 Comments.

  1. I received this error after visiting the install url:
    “Sorry, this shop is currently unavailable.”
    I created i follow every step and i created test store on shopify. What do you think is the problem?

    1. Hi Raff,

      Have you tried doing the following?

      1. Check if the store exist
      2. Check if the URL is correct and make sure there’s no typos.

      I believe it’s in your URL, make sure you type in like this:
      https://example.com/install.php?shop=your-store-name.myshopify.com

      Thank you for reading!

      If the problem still persists, don’t hesitate to respond to this comment.

      Good luck!

      Bernard

      1. Hi! Thanks for your reply, the url is correct and store is existing. I tried to create new app and test store but i got the same error. By the way, im also receiving “403 Forbidden” error whenever i visit the install together with the test store url and on the address/url bar of my browser it says that it’s “Not secure”. So i removed the S on https and it works then i received this error “Sorry, this shop is currently unavailable.” My domain has ssl and i dont know why im receiving the 403 error and not secure error.

    1. Hi soniya,

      Thank you for reaching out.

      First of all, you need to extract the shopify client in the same folder in which the install.php is located.

      Do you have your own host? First you need to have a web host where you can upload the files mentioned in this tutorial.

      Once everything is uploaded, you can proceed to your URL. For example your domain is soniya.com

      It goes like this:
      soniya.com/install.php?shop=rebusify.myshopify.com

      If you have more questions don’t hesitate to ask.

      Thanks for reading!

      Best regards,
      Bernard

  2. Hey really nice tutorial but i have a question, what URL should i use in the app settings App URL.
    I’m not sure how to redirect the user after he uninstalled the app and installs the app again.
    And if i need to leave the install as the APp Url add a code there to verify if the user installed the app before and redirect to the index.php or leave the index.php as the App Url and add the verification there to redirect to the install.php?
    Any recommendation would be really helpful thanks

  3. Hi,
    Very useful tutorial.I follow all the steps and installed the app and redirect to generate_token.but I am not getting the access token.curl function return empty values.please assist on it

  4. hello,

    i followed your tutorial in all points, but when it comes to shopify, it tells me, that the app could not be installed. i only have the button to cancel the process. what have i done wrong?

Leave a Reply