Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Shopify Laravel Package

kyon147/laravel-shopify

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   ```bash
   composer require kyon147/laravel-shopify
   php artisan vendor:publish --tag=shopify-config
  • Configure .env with your Shopify API credentials:
    SHOPIFY_API_KEY=your_api_key
    SHOPIFY_API_SECRET=your_api_secret
    SHOPIFY_API_SCOPES=write_products,read_orders
    SHOPIFY_API_HOSTNAME=your-shop.myshopify.com
    
  1. First Use Case: OAuth Flow

    • Add routes in routes/web.php:
      Route::get('/shopify/auth', [ShopifyController::class, 'install']);
      Route::get('/shopify/auth/callback', [ShopifyController::class, 'callback']);
      
    • Use the Shopify facade to handle authentication:
      use Kyon147\Shopify\Facades\Shopify;
      
      // Redirect to Shopify OAuth
      return Shopify::redirectToShopifyAuth();
      
      // Handle callback
      $shop = Shopify::getShopFromRequest();
      
  2. Verify Installation

    • Visit /shopify/auth to test the OAuth flow.
    • Check shopify_shops table for installed shops.

Implementation Patterns

Core Workflows

1. Shop Management

  • Install/Uninstall Shops:
    // Install a shop (redirects to OAuth)
    return Shopify::installShop();
    
    // Uninstall programmatically
    Shopify::uninstallShop($shopDomain);
    
  • Shop Listings:
    $shops = Shopify::getAllShops();
    foreach ($shops as $shop) {
        echo $shop->name . ' (' . $shop->domain . ')';
    }
    

2. API Access

  • Authenticated Requests:
    $products = Shopify::call('GET', 'products', ['limit' => 10]);
    
  • Webhooks:
    • Register a webhook:
      Shopify::registerWebhook('orders/create', 'https://your-app.com/webhooks/orders');
      
    • Handle incoming webhooks in a controller:
      public function handleWebhook(Request $request) {
          $topic = $request->input('topic');
          $payload = $request->input('payload');
          Shopify::handleWebhook($topic, $payload);
      }
      

3. Session Management

  • Per-Shop Sessions:
    $shop = Shopify::getCurrentShop();
    $session = Shopify::getSession($shop->domain);
    
  • Session Data:
    Shopify::setSessionData($shop->domain, 'user_id', 123);
    $userId = Shopify::getSessionData($shop->domain, 'user_id');
    

4. SPA Integration (Vue/React)

  • Token-Based Auth:
    • Generate a token for frontend use:
      $token = Shopify::generateOnlineAccessToken($shop->domain);
      
    • Use in your SPA to make authenticated requests:
      fetch('https://your-shop.myshopify.com/admin/api/2023-04/products.json', {
          headers: {
              'X-Shopify-Access-Token': 'your_token_here'
          }
      });
      

5. Billable Metrics (for Paid Apps)

  • Track usage:
    Shopify::recordUsage($shop->domain, 'api_calls', 5);
    
  • Generate reports:
    $report = Shopify::generateUsageReport($shop->domain);
    

Integration Tips

Laravel Ecosystem

  • Service Providers: Extend the package’s ShopifyServiceProvider to add custom logic:

    public function register() {
        $this->app->extend('shopify', function ($app) {
            return new CustomShopifyManager($app['shopify']);
        });
    }
    
  • Events: Listen to Shopify events (e.g., shop.installed):

    Shopify::on('shop.installed', function ($shop) {
        // Send welcome email
    });
    
  • Middleware: Protect routes with shop-specific middleware:

    Route::middleware(['shopify.auth'])->group(function () {
        // Routes requiring Shopify auth
    });
    

Testing

  • Mocking Shopify: Use the package’s mocking utilities:

    Shopify::shouldReceive('call')
        ->once()
        ->with('GET', 'products')
        ->andReturn(['products' => []]);
    
  • Test Webhooks:

    $this->post('/webhooks/orders', [
        'topic' => 'orders/create',
        'payload' => json_encode(['order_id' => 123])
    ]);
    

Gotchas and Tips

Pitfalls

  1. Session Expiry:

    • Online access tokens expire after 90 days. Implement token refresh logic:
      try {
          $token = Shopify::getOnlineAccessToken($shop->domain);
      } catch (\Exception $e) {
          if ($e->getCode() === 401) {
              $token = Shopify::refreshOnlineAccessToken($shop->domain);
          }
      }
      
  2. Webhook Verification:

    • Always verify webhook signatures:
      $isValid = Shopify::verifyWebhook($request);
      if (!$isValid) {
          abort(403, 'Invalid webhook signature');
      }
      
  3. Rate Limiting:

    • Shopify enforces rate limits (e.g., 2 calls/second). Implement retries:
      try {
          $response = Shopify::call('GET', 'products', ['limit' => 250]);
      } catch (\Kyon147\Shopify\Exceptions\RateLimitException $e) {
          sleep($e->getRetryAfter());
          retry();
      }
      
  4. Shop Context:

    • Always ensure the correct shop is set before making API calls:
      Shopify::setShop($shopDomain);
      $products = Shopify::call('GET', 'products');
      
  5. Config Overrides:

    • Avoid hardcoding API keys. Use environment variables or Laravel’s config:
      config(['shopify.api_key' => env('SHOPIFY_API_KEY')]);
      

Debugging Tips

  1. Enable Logging:

    • Configure logging in config/shopify.php:
      'log' => [
          'enabled' => true,
          'channel' => 'single',
      ],
      
    • Check logs for OAuth errors or API responses:
      tail -f storage/logs/laravel.log | grep shopify
      
  2. API Response Inspection:

    • Use the debug method to inspect raw responses:
      $response = Shopify::call('GET', 'products', ['limit' => 1]);
      Shopify::debug($response);
      
  3. Common Errors:

    • InvalidShopDomain: Ensure the shop domain matches the installed shops.
    • MissingScope: Verify your SHOPIFY_API_SCOPES include all required permissions.
    • InvalidAccessToken: Regenerate tokens or check for typos in the shop domain.

Extension Points

  1. Custom API Endpoints:

    • Extend the ShopifyManager to add custom API routes:
      public function extendApiRoutes() {
          Route::get('/custom-endpoint', [CustomController::class, 'handle'])
              ->middleware(['shopify.auth']);
      }
      
  2. Webhook Handlers:

    • Register custom webhook handlers:
      Shopify::onWebhook('orders/create', function ($payload) {
          // Custom logic for order creation
      });
      
  3. Session Drivers:

    • Replace the default session driver (e.g., for Redis):
      Shopify::setSessionDriver(new RedisSessionDriver());
      
  4. Billing Integration:

    • Hook into the usage.recorded event to sync with a billing system:
      Shopify::on('usage.recorded', function ($shop, $metric, $value) {
          // Sync with Stripe/Paddle
      });
      
  5. Blade Directives:

    • Add custom Blade directives for Shopify data:
      Blade::directive('shopifyShop', function ($expression) {
          return "<?php echo Shopify::getCurrentShop()->{$expression}; ?>";
      });
      
      Usage:
      @shopifyShop('name')
      

Configuration Quirks

  1. Hostname Handling:
    • Ensure SHOPIFY_API_HOSTNAME is set to the **
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle