GithubHelp home page GithubHelp logo

shopifychamp / shopify-api-php-sdk Goto Github PK

View Code? Open in Web Editor NEW
6.0 1.0 4.0 876 KB

PHP SDK for Shopify REST and GraphQL API

License: MIT License

PHP 100.00%
shopify-sdk shopify-php shopify-graphql-api shopify php-sdk php-shopify

shopify-api-php-sdk's Introduction

SHOPIFY API PHP SDK

Latest Stable Version License

PHP SDK helps to connect with shopify Public App and Private App using REST Api and Graphql.

  • Call GET, POST, PUT and DELETE RestApi method.
  • Process GraphQL Admin API for Query root and Mutations.
  • Queryroot is used to get resources and mutations is used to update resources (products/orders/customers).
  • Automatic manage Shopify API rate limits.
  • Compatible with Cursor Based Pagination to resource with pagination.

Installation

  • Install package with Composer
$ composer require shopifychamp/shopify-api-php-sdk

Requirements

  1. For Api call need Guzzle. The recommended way to install Guzzle is through Composer.

    $ composer require guzzlehttp/guzzle
    
  2. To prepare graphql query with GraphQL query builder.

    $ composer require rdx/graphql-query
    

Getting started

Initialize the client

1. For Private App

  • To create instance of Client class, need shop, api_key, password of private app, api_params is an array to pass api version with YYYY-DD/unstable format otherwise, Api latest version will be assigned.

    <?php 
    require(__DIR__ . '/../vendor/autoload.php');
    use Shopify\PrivateApp;
    
    $api_params['version'] = '2019-10';
    $client = new Shopify\PrivateApp($shop, $api_key, $password, $api_params);
    

2. For Public App

  • To create instance of Client class, need shop, api_key, api_secret_key of public app.

    <?php 
    require(__DIR__ . '/../vendor/autoload.php');
    use Shopify\PuplicApp;
    
    $api_params['version'] = '2019-10';
    $client = new Shopify\PublicApp($shop, $api_key, $api_secret_key, $api_params);
    
  • Prepare authorise url to install public app and get access_token to store in database or session for future api call.

    if(isset($_GET['code']))
    {
        //get access_token after authorization of public app
        if($access_token = $client->getAccessToken($_GET)){
            //set access_token for api call
            $client->setAccessToken($access_token);
            $response = $client->call('GET','products',['limit'=>250]);
        }
    }else{
        //$redirect_uri (mention in App URL in your public app)
        $redirect_url= isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on"?'https://':'http://';
        if ($_SERVER["SERVER_PORT"] != "80") {
            $redirect_url .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
        } else {
            $redirect_url .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
        }
    
        header('Location: '.urldecode($client->prepareAuthorizeUrl($redirect_url)));
    }
    

Call REST Api

  • Get Products with limit 250 with call() function

    $response = $client->call('GET','products',['limit'=>250]);
    print_r($response);
    
  • Get products of next page with page_info

    $response = $client->call('GET','products',['limit'=>250]);
    

    Check next page available with hasNextPage() function:

    if($client->hasNextPage())
    {
        $next_page_response = $client->call('GET','products',['limit'=>20,'page_info'=>$client->getNextPage()]);
        print_r($next_page_response);
    }
    

    Check if previous page available with hasPrevPage() function:

    if($client->hasPrevPage())
    {
        $prev_page_response = $client->call('GET','products',['limit'=>20,'page_info'=>$client->getPrevPage()]);
        print_r($prev_page_response);
    }
    

Call GraphQL Api

  • Get product title, description with id by query() function

    {
        product(id: "gid://shopify/Product/1432379031652") {
          title
          description
        }
    }
    

    Note:

    • For single attribute and field
        attribute('id','gid://shopify/Product/1432379031652') and field('title')
    
    • For multiple attributes and fields
    attributes(['product_type','fragrance','limit'=>250]) and `fields(['title','description'])
    

    Prepare query:

    <?php 
    use rdx\graphqlquery\Query;
    
    $query = Query::query("");
    $query->fields('product');
    $query->product->attribute('id', "gid://shopify/Product/1432379031652");
    $query->product->fields(['title','description']);
    $graphqlString = $query->build();
    
    

    Call GraphQL with callGraphql() function:

    $response = $client->callGraphql($graphqlString);
    
  • Create customer with graphql mutation() function

    mutation {
      customerCreate(input: { firstName: "John", lastName: "Tate", email: "[email protected]" }) {
        customer {
          id
        }
      }
    }
    

    Prepare mutation:

    <?php 
    use rdx\graphqlquery\Query;
    
    $query = Query::mutation();
    $query->fields('customerCreate');
    $query->customerCreate->attribute('input',['firstName'=>'John','lastName'=> "Tate", 'email'=> "[email protected]"]);
    $query->customerCreate->field('customer');
    $query->customerCreate->customer->field('id');
    $graphqlString = $query->build();
    

    Call GraphQL qith callGraphql() function:

    $response = $client->callGraphql($graphqlString);
    
  • Cursor Pagination with graphQL

    {
      products(first: 250) {
        edges {
          cursor
          node {
            id
          }
        }
      }
    }
    

    Prepare Query and $reserve_query variable to store query for next page call:

    <?php 
    use rdx\graphqlquery\Query;
    
    $query = Query::query("");
    $query->fields('products');
    $query->products->attribute('first', 250);
    $query->products->field('edges');
    $query->products->edges->fields(['cursor','node']);
    $query->products->edges->node->fields(['title','description']);
    $reserve_query = $query;
    $graphqlString = $query->build();
    
    

    Call GraphQL qith callGraphql() function. And

    $response = $client->callGraphql($graphqlString);
    
    

    If you continue repeating this step with the cursor value of the last product in each response you get until your response is empty. So need to check cursor index available in last array of $response then repeat call by adding cursor value with after attribute in products field.

    if(isset($response['data']['products']['edges']) && $last_array = end($response['data']['products']['edges']))
    {
        if(isset($last_array['cursor']))
        {
            //assign cursor value in `last` attribute
            $query = $reserve_query->products->attribute('after', $last_array['cursor']);
            $graphqlString = $reserve_query->build();
            $next_response = $client->callGraphql($graphqlString);
            print_r($next_response);
        }
    }
    

Error Handling

Below errors handled with ApiException Class

  • Trying to pass invalid api version
  • Trying to pass invalid shop domain
  • Http REST api call exception from Guzzle(GuzzleHttp\Exception\RequestException)
    try
    {
        $client = new Shopify\PrivateApp($shop, $api_key, $password, $api_params);
        $response = $client->call('GET','products',['limit'=>20]);
        print_r($response);
    }
    catch (\Shopify\Exception\ApiException $e)
    {
        echo "Errors: ".$e->getError().'<br> status code: '.$e->getCode();
    }
    

References

shopify-api-php-sdk's People

Contributors

kshitijverma22 avatar shopifychamp avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

shopify-api-php-sdk's Issues

BUG

Describe the bug
when i was trying to delete the ScriptTag By using SDK then a error occurred while all of the Api's request is working Fine like POST/GET but i am not understanding why it is happening when i choose the DELETE operation ,

This is my error :
Fatal error: Uncaught Shopify\Exception\ApiException: Client error: DELETE https://edd46b2c4ddb1469dbef46434614bfbab:***@testtechievolve.myshopify.com/admin/api/2019-10/script_tags.json?id=187190444172 resulted in a 406 Not Acceptable response in C:\xampp\htdocs\shopifySDK\vendor\shopifychamp\shopify-api-php-sdk\src\Client.php:277 Stack trace: #0 C:\xampp\htdocs\shopifySDK\vendor\shopifychamp\shopify-api-php-sdk\src\Client.php(200): Shopify\Client->request('DELETE', 'https://edd46b2...', Array) #1 C:\xampp\htdocs\shopifySDK\header.php(19): Shopify\Client->call('DELETE', 'script_tags', Array) #2 C:\xampp\htdocs\shopifySDK\index.php(2): require('C:\xampp\htdocs...') #3 {main} thrown in C:\xampp\htdocs\shopifySDK\vendor\shopifychamp\shopify-api-php-sdk\src\Client.php on line 277

This is my code :
187190444172 : This is my created ScriptTag id

$script_tag_array = array(
'id' => 187190444172
);
$scriptTag = $client->call('DELETE','script_tags',$script_tag_array);
echo "

";
print_r($scriptTag);

Expected behavior
I want to delete any ScriptTag by using this SDK .

Error Screenshots
image URL : https://www.awesomescreenshot.com/image/34970264?key=05e25bf63ba437cdf61458e5832dcc14

Additional context
when i was trying to delete the ScriptTag By using SDK then a error occurred while all of the Api's request is working Fine like POST/GET but i am not understanding why it is happening when i choose the DELETE operation , can you please check my above code and if i am doing wrong in my code then please correct them.

Your Any Help must be appreciated ,

Thanks

Class "App\Shopify\PrivateApp" not found

Describe the bug
A clear and concise description of what the bug is.
my code are
require(DIR . '/../vendor/autoload.php');

use Shopify\PrivateApp;
$api_params['version'] = '2023-04';
$this->shopify = new Shopify\PrivateApp(Config('constants.shopify.shopurl'), Config('constants.shopify.apikey'), Config('constants.shopify.apipasswd'), $api_params);

To Reproduce
Steps to reproduce the behavior:

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior
A clear and concise description of what you expected to happen.

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: [e.g. iOS]
  • Version [e.g. 22]

Additional context
Add any other context about the problem here.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.