How To Build Shopify Apps With PHP

How To Build Shopify Apps With PHP #2

  Shopify

Learn how to generate token for Shopify API with PHP

In the previous article, through the Shopify developer, we setup 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();

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!');
}

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:

http://example/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

 

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.

React to this topic
Bernard Polidario
About Bernard Polidario

A full-stack developer who has been around programming community for 10+ years and still has a lot of passion for programming and design. I am the founder of WeeklyHow and I can be reached at [email protected]

https://weeklyhow.com

10 comments on How To Build Shopify Apps With PHP #2

  1. Hi , i a m trying to create a shopify app but i am little confused where to keep the client folder ( which contain inc and others files like install.php)??
    and from which url we can run install.php file??
    also i have created a account in https://partners.shopify.com and created a app there from where i can get api key and secrete key.
    I also have a shopify store: https://rebusify.myshopify.com

    Please help.

    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. 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.

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*
*