项目作者: clarity-tech

项目描述 :
A Simple Wrapper for Shopify REST Api for Laravel
高级语言: PHP
项目地址: git://github.com/clarity-tech/laravel-shopify.git
创建时间: 2020-10-31T07:06:06Z
项目社区:https://github.com/clarity-tech/laravel-shopify

开源协议:

下载


Laravel Shopify

Laravel Shopify is a simple package which helps to build robust integration into Shopify.

Installation

Add package to composer.json

  1. composer require clarity-tech/laravel-shopify

Laravel 5.5+

Package auto discovery will take care of setting up the alias and facade for you

Laravel 5.4 <

Add the service provider to config/app.php in the providers array.

  1. <?php
  2. 'providers' => [
  3. ...
  4. ClarityTech\Shopify\ShopifyServiceProvider::class,
  5. ],

Setup alias for the Facade

  1. <?php
  2. 'aliases' => [
  3. ...
  4. 'Shopify' => ClarityTech\Shopify\Facades\Shopify::class,
  5. ],

Set shopify app authentication

Update config/app.php with below code and in routes add auth:shopify as middleware

  1. 'guards' => [
  2. ...
  3. 'shopify' => [
  4. 'driver' => 'shopify-auth',
  5. 'provider' => 'shops',
  6. ],
  7. ],
  8. 'providers' => [
  9. ...
  10. 'shops' => [
  11. 'driver' => 'eloquent',
  12. 'model' => App\Models\Shop::class,
  13. ]
  14. ],

Set credendials

in your .env file set these values from your app \
SHOPIFY_APIKEY=your-api-key \
SHOPIFY_SECRET=your-secret-key \
SHOPIFY_VERSION=admin-api-version \
only if app is private \
API_PASSWORD=private-app-password

Optional Configuration (publishing)

Laravel Shopify requires api key configuration. You will need to publish configs assets

php artisan vendor:publish --tag=shopify-config

This will create a shopify.php file in the config directory. You will need to set your API_KEY and SECRET

  1. 'key' => env("SHOPIFY_APIKEY", null),
  2. 'secret' => env("SHOPIFY_SECRET", null)

Usage

Frontend

Get the shopify session token using shopify fronend sdk & add Shopify-Token header in every request or send the inital url params appended by shopify

Backend

To install/integrate a shop you will need to initiate an oauth authentication with the shopify API and this require three components.

They are:

  1. 1. Shop URL (eg. example.myshopify.com)
  2. 2. Scope (eg. write_products, read_orders, etc)
  3. 3. Redirect URL (eg. http://mydomain.com/authorize)

This process will enable us to obtain the shops access token

  1. use ClarityTech\Shopify\Facades\Shopify;
  2. Route::get("shop/install", function(\Illuminate\Http\Request $request)
  3. {
  4. //$redirectUrl = route('shop.authorize');
  5. $redirectUrl = "http://mydomain.com/shop/authorize";
  6. $myShopifyDomain = $request->shop;
  7. $scope = ["write_products","read_orders"];
  8. $authorizeUrl = Shopify::getAuthorizeUrl($myShopifyDomain, $scopes, $redirectUrl);
  9. return redirect()->to($authorizeUrl);
  10. });

Let’s retrieve access token

  1. Route::get("process_oauth_result",function(\Illuminate\Http\Request $request)
  2. {
  3. $shopifyApi = resolve('shopify');
  4. $myShopifyDomain = $request->shop;
  5. $code = $request->code;
  6. $token = $shopifyApi
  7. ->setShopDomain($myShopifyDomain)
  8. ->getAccessToken($code);
  9. //this gets access token from shopify and set it to the current instance which will be passed in further api calls
  10. dd($accessToken);
  11. //store the access token for future api calls on behalf of the shop
  12. // redirect to success page or billing etc.
  13. });

To make the code less verbose we have added a app uninstalled job which can be subscribed via the app uninstalled webhook from shopify that can be configured automatically from your shop

After installation dispatch this job

  1. SubscribeAppUninstalledWebhookJob::dispatch($shop);

which will subscribe to the app/uninstalled webhook
under /webhooks/shopify/uninstalled route and will

To verify request(hmac)

  1. use ClarityTech\Shopify\Facades\Shopify;
  2. public function verifyRequest(Request $request)
  3. {
  4. $params = $request->all();
  5. if (Shopify::verifyRequest($params)){
  6. logger("verification passed");
  7. }else{
  8. logger("verification failed");
  9. }
  10. }

To verify webhook(hmac)

  1. use ClarityTech\Shopify\Facades\Shopify;
  2. public function verifyWebhook(Request $request)
  3. {
  4. $data = $request->getContent();
  5. $hmacHeader = $request->header('x-shopify-hmac-sha256');
  6. if (Shopify::verifyWebHook($data, $hmacHeader)) {
  7. logger("verification passed");
  8. } else {
  9. logger("verification failed");
  10. }
  11. }

To access Admin API use

  1. $myshopify_domain = "example.myshopify.com";
  2. $access_token = "xxxxxxxxxxxxxxxxxxxxx";
  3. $api = Shopify::setShop($myshopify_domain, $access_token)->basicApi();
  4. // For sync rest api
  5. $res = $api->rest('GET', '/admin/shop.json')
  6. // For sync graphql api
  7. $res = $api->graph('{ products(first: 1) { edges { node { handle, id } } } }', [])

To access API resource use

  1. Shopify::get("resource uri", ["query string params"]);
  2. Shopify::post("resource uri", ["post body"]);
  3. Shopify::put("resource uri", ["put body"]);
  4. Shopify::delete("resource uri");

Let use our access token to get products from shopify.

NB: You can use this to access any resource on shopify (be it Product, Shop, Order, etc)

  1. use ClarityTech\Shopify\Facades\Shopify;
  2. $shopUrl = "example.myshopify.com";
  3. $accessToken = "xxxxxxxxxxxxxxxxxxxxx"; //retrieve from your storage(db)
  4. $products = Shopify::setShop($myShopifyDomain, $accessToken)->get("admin/products.json");

To pass query params

  1. // returns Collection
  2. Shopify::setShop($myShopifyDomain, $accessToken);
  3. $products = Shopify::get('admin/products.json', ["limit"=>20, "page" => 1]);

Controller Example

If you prefer to use dependency injection over facades like me, then you can inject the Class:

  1. use Illuminate\Http\Request;
  2. use ClarityTech\Shopify\Shopify;
  3. class Foo
  4. {
  5. protected $shopify;
  6. public function __construct(Shopify $shopify)
  7. {
  8. $this->shopify = $shopify;
  9. }
  10. /*
  11. * returns products
  12. */
  13. public function getProducts(Request $request)
  14. {
  15. $accessToken = 'xxxxxxxxxxxxxxxxxxxxx';//retrieve from your storage(db)
  16. $products = $this->shopify->setShop($request->shop, $accessToken)
  17. ->get('admin/products.json');
  18. dump($products);
  19. }
  20. }

Miscellaneous

To get Response headers

  1. Shopify::getHeaders();

To get specific header

  1. Shopify::getHeader("Content-Type");

Check if header exist

  1. if(Shopify::hasHeader("Content-Type")){
  2. echo "Yes header exist";
  3. }

To get response status code or status message

  1. Shopify::getStatusCode(); // 200
  2. Shopify::getReasonPhrase(); // ok

Optional features

We also have a middleware for verifying the webhooks
you can directly use it in your webhooks by the name verify.webhook

We have also added a automatic app uninstalled job dispatch when app is uninstalled by subscribing to the webhook topic app/uninstalled.
To configure this you need to implement the interface Shopify/Contracts/ShopifyShop in your shop model and then

  1. SubscribeAppUninstalledWebhookJob::dispatch($shop);

To customize the AppUninstalled Job
Publish it by
php artisan vendor:publish --tag=shopify-jobs

You might not need this
We also dispatch events for webhooks if it is not for uninstalled topic for the same webhook
ClarityTech\Shopify\Events\ShopifyWebhookRecieved