PHP code example of shopgpt / shopify-integration

1. Go to this page and download the library: Download shopgpt/shopify-integration library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

shopgpt / shopify-integration example snippets


'oauth' => [
    'state_ttl' => env('SHOPIFY_STATE_TTL', 300),
],

public function getKey();
public function shopifyDomain(): string;
public function shopifyExternalId(): ?string;
public function shopifyAccessToken(): ?string;
public function shopifyRefreshToken(): ?string;
public function shopifyTokenExpiresAt(): ?DateTimeInterface;
public function shopifyScopes(): ?string;
public function shopifyIsInstalled(): bool;

use ShopGPT\ShopifyIntegration\Concerns\InteractsWithShopifyStore;
use ShopGPT\ShopifyIntegration\Contracts\ShopifyStore;

class Integration extends Model implements ShopifyStore
{
    use InteractsWithShopifyStore;
}

// config/shopifyIntegration.php
'store' => [
    'model'   => App\Models\Integration::class,
    'columns' => [
        'store_domain' => 'domain',
        'access_token' => 'token',
        'external_id'  => 'integration_id',
        'platform'     => 'type',
    ],
],

class AppStoreRepository extends EloquentStoreRepository
{
    protected function newStore(string $shop, array $shopData): Model
    {
        $store = parent::newStore($shop, $shopData);

        $store->user_id = Auth::id()
            ?? User::firstOrCreate(['email' => $shopData['email']], [...])->id;

        return $store;
    }
}

'store' => ['repository' => App\Repositories\AppStoreRepository::class],

'store' => ['encrypt_tokens' => true],

// Pages loaded inside the Shopify Admin iframe
Route::middleware('shopifyIntegration.embedded')->group(function () {
    Route::get('/shopify/app', fn () => view('shopify'));
});

// XHR from inside the iframe, bearing a session token
Route::middleware('shopifyIntegration.session')->group(function () {
    Route::get('/api/products', [ProductController::class, 'index']);
});

$products = ShopifyIntegration::currentStore()->api()->graphql(<<<'GQL'
    query { products(first: 10) { edges { node { id title } } } }
GQL)->json('data.products.edges');

'redirects' => [
    'after_install' => 'dashboard',
    'on_failure'    => '/connect-failed',
],

return redirect(ShopifyIntegration::installUrl('acme.myshopify.com'));

Event::listen(StoreInstalled::class, function (StoreInstalled $event) {
    Auth::login($event->store->user);
});

class AppStoreRepository extends EloquentStoreRepository
{
    protected function newStore(string $shop, array $shopData): Model
    {
        $store = parent::newStore($shop, $shopData);

        $store->user_id = User::firstOrCreate(
            ['email' => $shopData['email']],
            ['name'  => $shopData['shop_owner'] ?? null],
        )->id;

        return $store;
    }
}

Route::middleware('shopifyIntegration.installed')->group(function () {
    Route::get('/dashboard', [DashboardController::class, 'index']);
});

class AuthenticateStoreOwner
{
    public function handle($request, Closure $next)
    {
        $storeUserId = ShopifyIntegration::currentStore()?->user_id;

        if ($storeUserId && $user = User::find($storeUserId)) {
            Auth::setUser($user);
        }

        return $next($request);
    }
}

class Integration extends Model implements ShopifyStore
{
    use InteractsWithShopifyStore;

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }
}

'store' => ['model' => App\Models\Integration::class],

use ShopGPT\ShopifyIntegration\Facades\ShopifyIntegration;

use ShopGPT\ShopifyIntegration\Contracts\ShopifyStoreRepository;

$stores = app(ShopifyStoreRepository::class);   // or ShopifyIntegration::stores()

use ShopGPT\ShopifyIntegration\Support\StoreState;

StoreState::hasValidToken($store);
StoreState::tokenExpiresSoon($store, $buffer = null);
StoreState::hasRequiredScopes($store, $

$store->isInstalled();
$store->hasValidToken();
$store->hasRequiredScopes();
$store->needsReauthorization();
$store->api();

Integration::query()->installed()->get();

$store->shopifyDomain();          // acme.myshopify.com
$store->shopifyAccessToken();     // decrypted
$store->shopifyScopes();
$store->shopifyTokenExpiresAt();  // DateTimeInterface|null

$api = $store->api();

// GraphQL
$api->graphql('query { shop { name } }');
$api->graphql($query, ['first' => 10]);

// REST
$api->get('products.json', ['limit' => 50]);
$api->post('products.json', ['product' => [...]]);
$api->put('products/123.json', ['product' => [...]]);
$api->delete('products/123.json');

try {
    $store->api()->graphql($query);
} catch (StoreUninstalledException $e) {
    // already flagged; your StoreUninstalled listeners have run
} catch (RateLimitedException $e) {
    $this->release($e->retryAfter);
} catch (StoreUnavailableException $e) {
    // still installed — try again later
}

// StoreScopesUpdated — what actually moved
$event->gained();   // ['write_products']
$event->lost();     // ['read_orders'] — calls needing these now 403

// StoreProfileUpdated — the one that matters for billing
$event->planChanged();    // the plan is not what it was — dev store went live?
$event->previousPlan;     // and $event->currentPlan

// TokenRefreshFailed — false means the current token is still usable and
// the next call retries; true means the merchant must re-authorise
$event->fatal;

$context->store;              // ShopifyStore
$context->shopData;           // array — raw shop.json
$context->viaTokenExchange;   // bool — arrived embedded, not through the redirect
$context->scopes;             // string|null — what Shopify granted
$context->host;               // string|null — the host param, embedded only

$context->domain();           // acme.myshopify.com
$context->email();
$context->profile();          // the 11 profile fields, read from shop.json
$context->isDevelopmentStore();

'topics' => [
    'app/uninstalled'        => HandleAppUninstalled::class,
    'app/scopes_update'      => HandleScopesUpdate::class,
    'shop/update'            => HandleShopUpdate::class,
    'shop/redact'            => HandleShopRedact::class,
    'customers/redact'       => HandleCustomersRedact::class,
    'customers/data_request' => HandleCustomersDataRequest::class,

    // Any other topic you subscribe to, mapped to your own job:
    // 'your/topic'          => App\Jobs\YourHandler::class,
],

use ShopGPT\ShopifyIntegration\Jobs\WebhookJob;

class YourHandler extends WebhookJob
{
    public function handle(): void
    {
        $this->store();      // ?ShopifyStore, resolved through your repository
        $this->topic;        // the topic this was registered under
        $this->payload;      // array
        $this->webhookId;    // X-Shopify-Webhook-Id

        $this->resourceId(); // $payload['id']
    }
}

protected static function payloadForQueue(array $payload): array
{
    return ['id' => $payload['id']];
}

$this->withHeaders(ShopifyIntegration::sessionTokenHeaders($store))
     ->getJson('/api/products')
     ->assertOk();

ShopifyIntegration::sessionTokenHeaders($store, ['exp' => time() - 60]);
ShopifyIntegration::sessionTokenHeaders($store, ['aud' => 'another-app']);

ShopifyIntegration::webhookHeaders('app/uninstalled', $store, $payload);
bash
php artisan vendor:publish --tag=shopifyIntegration-config
bash
php artisan vendor:publish --tag=shopifyIntegration-migrations