The simple way of developing a custom app using PHP
Shopify is one of the most popular ecommerce platforms, offering developers a significant opportunity to create and monetize their web applications.
Note that Shopify has implemented API versioning, releasing updates every quarter. It’s essential to stay informed about these updates, as Shopify consistently enhances its API. If you’re developing Shopify apps, it’s crucial to ensure your apps remain updated accordingly.
ON THIS PAGE
Shopify PHP?
While there isn’t a specific “Shopify PHP” framework, it’s important to note that PHP, a programming language for web development, can be utilized to create Shopify apps. Additionally, developers can employ PHP frameworks like Laravel to facilitate the development of Shopify apps.
How to do Shopify Custom App Development?
Building your own Shopify apps is straightforward; all you need is to grasp how the API functions. By following a few steps, you can develop a custom Shopify app using PHP.
What to do and Where to start?
To begin, you have to create a new Shopify app in your Shopify Partner Account, So if you don’t have an account yet, you can sign up by visiting the Shopify Partner site.
Once you successfully create the account, you can see all the options in the sidebar menu.
Steps:
- Click on “Apps”.
- The app listing page will open in the top right corner, where you can see the “Create App Manually” button.
- Click the “Create App” button.
- It will take you to the “Create a New App” page.
- On the right side of the page, you will see Use Shopify partners, and below “Create App Manually”.
- Click “Create App Manually”.
- Enter the app name.
- Click the “Create” button.
- It will take you to the App detail page with the “Client ID” & “Client Secret”.
- On the right sidebar, you can see all options related to the app details.
- You can jump to How to Develop a Custom PHP APP with code examples from here.
- An external server must host the custom app code with the SSL certificate.
To know more about all options:
Overview
Below the overview, you can see the following:
- Client credentials: Use the client credentials to access the Shopify API from your app. They’re also available on the API access page.
- Test your app: Test your app on a development store as testing stores cannot be transferred.
- Get ready for production: When you’re ready, choose to distribute your app either on the Shopify App Store or by single-merchant install link.
- Create app extensions: App extensions integrate the features of your app into frequently used areas of Shopify.
Build
Configuration
- App name
- App handle – Configure your app handle in the app’s TOML file.
- URLs
- App URL
- Preferences URL (optional)
- Allowed redirection URL(s)
- Include at least one redirect URL before making your app public. Users will be directed to these allowed URLs after installing the app. Learn more about redirection URLs.
- Embedded in Shopify admin
- Load your app in Shopify admin using Shopify App Bridge.
- Embed the app in Shopify admin. (True / False)
- Event version
- Set the version used to serialize webhooks and cloud service events.
- Compliance webhooks
- Public apps are required to have endpoints that subscribe to Shopify’s privacy webhook topics. Learn more about mandatory webhooks.
- App Proxy
- Fetch and display data on a store from your app. Learn more about app proxy.
- POS
- Load your app in Shopify POS using Shopify App Bridge.
- App settings
- You don’t need to release a new app version to update these settings. Changes take effect immediately.
- App icon.
- API contact email.
- Google Cloud Pub/Sub.
- Amazon EventBridge – Manage webhook events at scale with Amazon EventBridge.
- Storefront API – Apps distributed via a single-merchant install link can use the Storefront API to develop customized shopping experiences.
- Shopify provides a Storefront API that allows you to customize Shopify buying experiences. The Storefront API allows you to access product information, create customer orders, and check out purchases programmatically.
- Turn your app into a sales channel.
- Make it possible for users to sell their products with your app. Learn more about sales channels.
- Making your app a sales channel allows you to:
- Embed your sales channel in Shopify admin.
- Have users publish products to your channel.
- Use the Checkout API and apply for additional payment processing options.
- For your app to become a sales channel, it must not be published or have any installs. This process is not reversible once it is installed.
- Embedded app home.
- Manage your app’s navigation and mobile optimization settings.
- Export control classification number.
- Required for when you sell or transfer your app. Learn more.
- Delete this App
- A button to delete this app.
API Access
- Credentials
- Client ID – Your client ID serves as your app’s public identifier, required for interacting with Shopify APIs.
- Client secret – Your client secret is used for authenticating and authorizing your app. Keep it confidential. Learn more about rotating or revoking client credentials.
- Refresh Token – A refresh token is temporary, and valid only for one hour. If you are unable to request new tokens for all stores using your app in an hour, generate a new refresh token and start where you left off.
- Access requests
- Protected customer data access – To protect merchants and their customers, apps distributed on the App Store and utilizing Admin API version 2022-10 or later, or checkout UI extensions, must request access to customer data such as names, emails, and order history. Learn more about Shopify’s requirements to access protected customer data.
- Read all order’s scope
- Grants access to a store’s full order history, rather than just the last 60 days provided by the read_orders scope. Learn more about orders.
- Access subscriptions APIs
- Build and manage subscriptions.
- Access payment mandate scopes
- Collect deferred payment using a customer’s vaulted card. Learn more about payment mandates.
- Allow network access in checkout and account UI extensions
- Get data you can’t currently get from Shopify into checkout and account UI extensions. Your app must use network calls and maintain a fast and performant checkout to use network access. Learn more about building checkout UI extensions or customer account UI extensions.
- Access post-purchase extensions
- Add custom content like offers and requests to customers immediately after checkout with post-purchase extensions.
Extensions
- Create an app extension
- Surface your app’s functionality on Shopify user interfaces like checkout, point of sale, or store admin.
Release
- Versions
- List of App versions with the status.
- Distribution
- Select a distribution method
- Public distribution
- Publish your app on the Shopify App Store as listed or unlisted. Reach a global merchant audience with unlimited installs.
- Custom distribution
- Generate custom install links for one store or one Plus organization. Installs are limited to one store or the number of stores that an organization has.
- Public distribution
- Select a distribution method
Monitor
- Insights will give the reporting structure of the app,
- App History
- API Health
- Webhooks
- Functions
- Admin Performance
Custom PHP App
Getting Started
Your Shopify app needs to be authenticated by the store to function. This means the shop owner must install your Shopify app and grant you the necessary permissions to operate within their store. For example, displaying a list of available customers, products, collections, and orders. This process is done by OAuth, which is a highly secure method for communication between applications.
It is also important to know that every shop that installs your Shopify app has an access token that they need to use to keep their session running. That token can be saved to your database.
How to generate a Shopify API token and App Installation/Connection?
Create any PHP files and folders to generate, create, and install the app into your Shopify admin.
- Following are the files and folders
- First of all, create a main folder called “custom_app”.
- Then create an inc folder inside the main folder.
- Files & folder structure look like:
- The inc folder contains a PHP file (functions.php) that consists of a function that you can use to make Shopify actions like displaying the customers, products, collections, and orders.
- The custom_app folder contains a PHP file(generate_token.php) that generates a token per store. The store will use this file after installing the app.
- The custom_app folder contains a PHP file(install.php) for Shopify app installation.
- The custom_app folder contains the PHP file(index.php), which is the main page of your application to display dashboard items.
- Let’s look at what code the generate_token.php, install.php & index.php files contain as these three files are used to install the custom app in Shopify admin.
- You have to assign your API key in this code to create your Shopify partner account.
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 Explanation for install.php
- First, assign the value of $_GET[‘shop’] to the variable $shop.
- Don’t worry about from where that value is coming. It’s from the URL that the user will be visiting.
- For example:
- https://example.com/install.php?shop=example.myshopify.com
- For example:
- $api_key variable is where you’ll be assigning your API key.
You can get your API key from your Shopify partner app page, as shown in the screenshot. - You may leave the $scope variable or assign it later based on the required permission.
- $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 prompts to install the app.
- After setting up the variables, redirection to the URL from the $install_url variable will happen.
Note: 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 lexicographically
$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!)
//Here is the place where you can store the access token to the database
echo $access_token;
} else {
// Someone is trying to be shady!
die('This request is NOT from Shopify!');
}
Code Explanation for generate_token.php
Before we proceed, make sure you change the value of the variables $api_key and $shared_secret.
Replace the Allowed redirection URL(s) in the Shopify partner app dashboard under configuration as shown in the above image.
Again, you can get this data from your Shopify partner app dashboard, as shown in the above screenshot.
- If you noticed, the code above is using the cURL client to execute requests.
- These requests will provide you with a JSON data type value that needs to be decoded for PHP to utilize.
- After getting the access token, you may add a MySQL query to save the value of the $access_token variable for future use.
Installing the Shopify App
- Once you have followed all instructions, you can proceed to your project URL and execute install.php.
- For Example
- https://example.com/example/install.php?shop=shop.myshopify.com
- For Example
- By going to your install.php, you will see this confirmation to install the app
How to display customers, products, collections, and orders?
- Now, you want to start working with Shopify API to display the products of the Shopify store.
- Please create a new PHP file named “products.php” and paste the provided code inside it.
- The files & folder structure will look like this.
<?php
require_once("inc/functions.php");
$requests = $_GET;
$hmac = $_GET['hmac'];
$serializeArray = serialize($requests);
$requests = array_diff_key($requests, array('hmac' => ''));
ksort($requests);
$token = PASTE YOUR GENERATED TOKEN HERE
$shop = PASTE YOUR SHOP URL HERE
Code Explanation for products.php
- The code above will first retrieve the data of the Shopify store.
- After getting all the data, assign the $_GET[‘hmac’] to a new variable $hmac serialize the $requests variable. Then remove the key ‘hmac’ inside the array $requests.
- Then we’ll sort the $requests variable with the ksort() function.
- Next, the following variables are essential for making Shopify requests.
- Remember that we generated a token when we installed the app in our store? Now, we’re going to use that token by pasting it into the value of the $token variable.
- Note that we are not yet using the database, it’s essential to back up the access token in a file for reference.
- Next, for the $shop variable, paste the store URL you are using for this app, but exclude “https://” and “myshopify.com”. Only include the SUBDOMAIN.
- For Example:
- https://this-is-the-subdomain.myshopify.com/
- For Example:
Using Collection API
$collectionList = shopify_call($token, $shop, "/admin/api/2024-01/custom_collections.json", array(), 'GET');
$collectionList = json_decode($collectionList['response'], JSON_PRETTY_PRINT);
$collection_id = $collectionList['custom_collections'][0]['id'];
$array = array("collection_id"=>$collection_id);
$collects = shopify_call($token, $shop, "/admin/api/2024-01/collects.json", $array, 'GET');
$collects = json_decode($collects['response'], JSON_PRETTY_PRINT);
We’ll be using the function shopify_call() to get the first collection ID that we need for retrieving the products.
You may skip this part if you want to display specific products from a collection ID.
To display specific products from a collection ID, you can use this code instead:
$collection_id = PASTE YOUR COLLECTION ID HERE
$array = array("collection_id"=>$collection_id);
$collects = shopify_call($token, $shop, "/admin/api/2020-07/collects.json", $array, 'GET');
$collects = json_decode($collects['response'], JSON_PRETTY_PRINT);
Where can I get my collection ID?
- Click Products
- Next, Collections
- Then click one of your desired collections.
- Check the URL – https://example.myshopify.com/admin/collections/1234567890
The numerical value at the end of the URL above is the collection ID, copy that and paste it into your $collection_id variable.
To explain, the code above will return an array containing all the product IDs inside the collection ID that we used. It’s a JSON code but we decoded it and turned it into an array that’s why we use the json_decode() function.
Using Product API
foreach($collects as $collect){
foreach($collect as $key => $value){
$products = shopify_call($token, $shop, "/admin/api/2019-07/products/".$value['product_id'].".json", array(), 'GET');
$products = json_decode($products['response'], JSON_PRETTY_PRINT);
echo $products['product']['title'];
}
}
The code above will display all the product names available inside the collection ID that we have used.
API Versioning
Note that API versioning allows Shopify to continuously evolve the platform while offering third-party developers a predictable path for feature upgrades and deprecations.
To ensure you always know about upcoming API changes, follow the Changelog and always keep your contact information up to date in the Partner Dashboard.
Release schedule
Shopify releases a new API version every three months at the beginning of the quarter. Version names are date-based to be meaningful and semantically unambiguous (for example, 2023-01). Below is an example release schedule for 2023:
Stable Version | Release Date | The stable version is supported until |
2023-01 | January 1, 2023 | January 1, 2024 |
2023-04 | April 1, 2023 | April 1, 2024 |
2023-07 | July 1, 2023 | July 1, 2024 |
2023-10 | October 1, 2023 | October 1, 2024 |
Stable versions are released at 5 pm UTC.
Each stable version is supported for 12 months (minimum), ensuring at least 9 months of overlap between consecutive stable versions. When a new stable version introduces changes that affect your app, you have 9 months to test and migrate your app to the new version before support for the previous version is discontinued.
Tip
When a new version has an impact beyond the API, such as on the online store or the UI of the Shopify admin, a developer preview is made available in your Partner Dashboard. To learn more, see Developer Previews.
We strongly recommend updating your apps to make requests to the latest stable API version every quarter. If your app uses a stable version that is no longer supported, Shopify will fall back and respond to your request with the same behavior as the oldest supported stable version.
For example, when Shopify removes 2023-07, API requests to version 2023-07 will be served to version 2023-10 because that will be the oldest supported stable version.
If your request doesn’t include a version, the API defaults to the oldest supported stable version. However, we do not recommend relying on this behavior for adopting deprecated changes. As you update your app, you should specify the API version with every request. By making your app version aware, you anchor your code to a specific set of features that are guaranteed to behave in the same way for the supported timeframe.
Example version support schedule
Conclusion
Finally, you will install the app on your Shopify store admin, and it will retrieve all products available within a specific collection from your store admin. This indicates that your setup is correct and functioning properly.