Shopify App Development Illustrations Vector

How To Display Shopify Products with PHP

  Shopify

Learn how to display Shopify products using Shopify API and PHP

Welcome to part three of Shopify development tutorial, in this article we’ll be giving you a tutorial on how to display Shopify products using PHP. So if you haven’t made your Shopify app yet, you may proceed to this article to learn how to set up Shopify and PHP.

 

products.php

Create a new PHP file and name it products.php inside the file paste the following code:

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

The code above will retrieve the parameters from Shopify app. Once the merchant runs the app in their Shopify store admin. Shopify will return values that are necessary for communicating with Shopify through PHP

After getting all the parameters, assign the $_GET['hmac'] to a new variable $hmac then serialize the $requests variable. Then remove the key ‘hmac’ inside the array $requests.

Then we’ll sort the parameters lexographically

Next, the following variables are important for making Shopify requests.
Remember that we generated a token when we installed the app in our store? Right now we’re going to use that, now paste the token in the value of $token variable.

Next, the $shop variable. Paste the URL of the store that you are using for this app BUT without https and myshopify.com. Just the SUBDOMAIN.

Example:

https://this-is-the-subdomain.myshopify.com/

Next, Add this code below

Update: Always use /admin/api/2019-07/ whenever you use shopify_call() function. Otherwise, it won’t return any response.

$collectionList = shopify_call($token, $shop, "/admin/api/2019-07/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/2019-07/collects.json", $array, 'GET');
$collects = json_decode($collects['response'], JSON_PRETTY_PRINT);

We’ll be calling the function shopify_call() to get the first collection ID that we needed 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/2019-07/collects.json", $array, 'GET');
$collects = json_decode($collects['response'], JSON_PRETTY_PRINT);

Where can I get my collection id?

Finding Collection ID in Shopify Admin page
  • Click Products
  • Next, Collections
  • Then click one of your desired collection.
  • 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 to your $collection_id variable.

To explain, the code above will return an array that contains all the product IDs inside the collection ID that we used. Basically, it’s a JSON code but we decoded it and turn it into an array that’s why we use json_decode() function.

Next, Add this code below

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’s name available inside the collection ID that we have used.

Test the Shopify App

Display Shopify Products per Collection ID using PHP and Shopify API

Congratulations! Now you have successfully displayed all the products that are available inside a certain collection. If you have concerns or questions, don’t hesitate to ask down in the comments.

 

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

19 comments on How To Display Shopify Products with PHP

  1. Thanks for the reply Bernard. I read that article, very helpful.

    One question, how do you retrieve the token from the database? I assume we query where “shop url is equals to”, but how can i get the shop url dynamically to pass to the query?

    Should we be using $_SERVER[‘HTTP_HOST’] or something? Or is there a shopify specific helper we can use to grab this current shop url?

    Thanks again for your help.

    1. Hi Anthony,

      We’re really happy that we’re able to help you!

      To answer your question, you can retrieve your access token, that’s right, through Shop URL in WHERE statement of MySQL query. You don’t have to use the $_SERVER['HTTP_HOST'], you can get the URL from $_GET variable. You can use print_r($_GET) so you can see all the values you can get from $_GET variable. For the Shop URL, it should be $_GET['shop'].

      If you have more questions,
      Let us know and we’d be really happy to help.

      Cheers!
      Bernard

  2. I’m confused why you hard code the access token and site URL? Once in production we will not be able to hard code the user’s values. How do we go about storing/retrieving these values in production?

    Thanks for your time.

  3. After creating this product page and going back to the app in my shopify store I get an error saying “mysite” can’t be reached (the website used for the App URL).

    I tried uninstalling and re-installing the app.

    If I go directly to the product page created, I do see the products.

    Any idea how to solve the connection issue in the app on shopify?

      1. Bernard,

        Thank you for your response. I did not have an index.php file. However, I have now added that file and I am still getting the issue. I have uninstalled and reinstalled the app as well.

        Any other areas I should look?

        Thank you,
        Corey

        1. Hi Corey!

          Have you tried renaming product.php to index.php?

          That could do a trick. I believe

          Also, there’s no need to uninstall and reinstall the app, as I believe this is the file issue.

          Best regards,
          Bernard

          1. I have now tried renaming product.php to index.php. Unfortunately I get the same error. I inspected the element of the iframe. I got the redirect url and pasted that into my browser. I can confirm the redirect url works that the iframe is trying to load.

            I am at a lost as to why the page won’t load in the app.

  4. Hello, I installed the app and all but when I try to run this products script I get “Warning: Invalid argument supplied for foreach() on line 24”. I did a print_r on the array and I got “(
    [errors] => [API] Invalid API key or access token (unrecognized login or wrong password)
    )” . What do you think is causing this issue?

    1. Hello Aldin,

      Have you checked if you’re using the right access token that you got from your install.php? Or is there no typo in your API key?

      If the problem still persists, I suggest you to uninstall the app and re-install it again.

      Thanks for reading!

      Best Regards,
      Bernard

      1. Hello Bernard,

        The same error is coming to my app. I tried storing access token in database but it is only storing blank in it.
        I also tried uninstalling the app and re-installing it for 20 times but again and again the same error [errors] => [API] Invalid API key or access token (unrecognized login or wrong password) is coming up. Could you please help me with this.

        Thanks

        Anand

        1. Hi Anand,

          Thank you for reaching out.

          What about the install uri?
          Make sure it is formatted like this:
          $install_url = "https://" . $shop . "/admin/oauth/authorize?client_id=" . $api_key . "&scope=" . $scopes . "&redirect_uri=" . urlencode($redirect_uri);

          Best regards,
          Bernard

          1. Hi Bernard,
            Thank You for your Response. However the problem could not be solved out even after trying what you said. I further tried different things and was able to find out that my generate_token. php file works well and even stores data in database, but the curl part is not working which is why it always leaves a blank in access_token in database. I have already enabled php curl in php extension.
            Could you help me in this?

            Thanks

          2. Hi Anand,

            Thank you for reaching out!

            If the access_token is leaving empty value, that means there’s something wrong with your API key.
            Check if there’s a typo, check your apps and your keys in your Developers account.
            Check your store. Check your codes.

            Also, you may try to reset the key access and secret key and try to replace it with a new one.

            Don’t hesitate to tell me more details about the issue. We’d love to help.

            Best regards,
            Bernard

    1. Hello Christian,

      To run the PHP script to display the products from your shopify store, you have to make sure first that:

      1.) You’re referencing ‘functions.php’
      2.) You have replaced the values for the $token and $shop variables
      3.) You are using the latest API versioning of Shopify which is 2019-04.

      If you haven’t migrated your scripts to the latest version of API yet, I highly suggest you to read this article:
      https://weeklyhow.com/building-shopify-apps-with-php-shopify-2019-04-update/

      This will guide you to properly migrate your scripts from old API calls to latest API.

      If you have more questions, please don’t hesitate to ask 🙂

      Best Regards,
      Bernard

Leave a Reply

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

*
*
*