ShopiKit Documentation ยท version 1.0.0

ShopiKit โ€“ PHP Boilerplate for Shopify Apps

A clean PHP 8.3 + MySQL foundation for embedded Shopify apps, built on the patterns that pass the App Store review today, with a working demo app and an owner admin.

Managed installSession tokensGraphQL Admin APIBilling APIWebhooks + GDPRQueue & workerTheme app embedAdmin blockOwner admin

#What is inside

ShopiKit is a framework-less PHP application: small, readable classes under the ShopiKit\ namespace, MySQL, and no build step for the app itself. It runs on any VPS or shared host with PHP 8.3 and HTTPS.

๐Ÿ” Install and auth

Managed install with token exchange (no OAuth redirects), expiring offline tokens refreshed automatically, App Bridge session tokens checked on every request.

โšก Admin API

GraphQL client with cost-based throttling, retries, cursor pagination and userErrors handling.

๐Ÿ’Ž Billing

Free / Basic / Pro, monthly and yearly, free trial, upgrade, downgrade, test charges on development stores, daily reconciliation.

๐Ÿช Webhooks and GDPR

One HMAC-verified endpoint, deduplication, queued processing, replay, the 3 compliance topics and automatic data deletion.

โš™๏ธ Background work

MySQL queue with retries and backoff, worker for systemd or cron, scheduler for recurring tasks.

๐Ÿงฉ Extensions

A theme app embed (announcement bar) and an admin block (product page card) that talks to your backend.

๐Ÿ› ๏ธ Owner admin

Overview and MRR, shops, plan editor, queue, errors, webhooks, support tickets, GraphQL console, system check, settings, admin users with authenticator codes.

๐Ÿš€ Developer tools

Setup wizard, code generator, shopify app dev integration, tests, deploy script and server templates.

#Requirements

WhatVersionNotes
PHP8.3 or newerExtensions: curl, json, mbstring, openssl, pdo_mysql
MySQL8.0+ (or MariaDB 10.6+)The queue uses SELECT โ€ฆ FOR UPDATE SKIP LOCKED
Composer2.xInstalls PHPMailer (and PHPUnit for tests)
Node.js22.12+Only for the Shopify CLI and the admin block extension, never on the server
ShopifyPartner account + a development storeFree at shopify.com/partners
ProductionHTTPS domainnginx or Apache with PHP-FPM; cron (and ideally systemd) for the worker

#Quick start (local)

About 15 minutes from the unzipped folder to the demo app running in your development store. Works on Windows (Laragon, XAMPP), macOS and Linux.

  1. Install the dependencies in the project folder:

    composer install
    npm install
  2. Run the setup wizard. It creates .env, generates APP_KEY, creates the database, runs the migrations and your owner admin account. Press Enter to keep a suggested value; the Shopify keys can stay empty for now (step 4 fills them).

    php bin/install.php
  3. Connect the project to a Shopify app. Log in when the browser opens, pick your organization and choose Create this project as a new app:

    npx shopify app config link

    This writes shopify.app.<name>.toml with your Client ID. Copy the [access_scopes] and [webhooks] sections from shopify.app.toml into it if they are missing (see Create the Shopify app).

  4. Put the app keys in .env (also used by the worker):

    type nul > .env.shopify   # macOS/Linux: touch .env.shopify
    npx shopify app env pull --env-file .env.shopify

    Copy SHOPIFY_API_KEY and SHOPIFY_API_SECRET from .env.shopify into .env, then delete .env.shopify.

  5. Start the app. The CLI opens a tunnel, points the app at it and starts the PHP server (shopify.web.toml):

    npx shopify app dev

    Choose your development store, then press p and install the app.

  6. Start the worker in a second terminal (background jobs: shop details, exports, webhooks):

    php bin/worker.php
  7. Open the owner admin at <tunnel URL>/admin and check System check.

TipAfter changing .env, restart the worker: it reads the file once when it starts. Web requests read it every time.

#Create the Shopify app

Apps are created and configured in the Dev Dashboard (dev.shopify.com) and in shopify.app.toml, which shopify app deploy pushes to Shopify.

What shopify.app.toml contains

KeyValue in ShopiKitWhy
client_idyour app's Client IDWritten by shopify app config link
handleshopikit-demoMust equal SHOPIFY_APP_HANDLE: used for the billing return URL
application_urlyour APP_URLThe embedded app; updated to the tunnel during shopify app dev
embeddedtrueThe app runs inside the Shopify admin
scopesread_products,write_productsAsk only for what you use (App Store rule)
use_legacy_install_flowfalseShopify-managed install: no OAuth code in your app
webhooks.subscriptionsuri = "/webhooks"Relative URIs follow application_url (tunnel or domain)

Billing needs public distribution

The Billing API only works for apps with public distribution. In the Dev Dashboard open your app โ†’ Distribution โ†’ Public โ†’ Confirm. This does not submit or publish anything, but the choice cannot be changed later. Until you do it, the Plans page shows "Billing is not available yet".

Development storesCharges on development stores are always test charges: nothing is billed. ShopiKit also creates test charges whenever APP_ENV is not production.

#Configuration (.env)

.env holds the server settings and every secret. It lives next to app/, outside public/, and is never committed. Everything that is not a secret can also be changed later in /admin/settings.

VariableExampleMeaning
APP_NAMEProduct NotesName shown to merchants and in subscription names
APP_ENVlocal / productionproduction + a real store = real charges
APP_URLhttps://app.example.comPublic HTTPS URL (set automatically during shopify app dev)
APP_DEBUG1 / 00 on the live server
APP_KEYbase64, 32 bytesEncrypts Shopify tokens in the database. Never change it after going live
DB_*MySQL connection
SHOPIFY_API_KEY, SHOPIFY_API_SECRETClient ID and secret from the Dev Dashboard
SHOPIFY_API_SECRET_OLDPrevious secret during a rotation (still accepted for webhooks and session tokens)
SHOPIFY_API_VERSION2026-10Admin API version; keep it equal to webhooks.api_version
SHOPIFY_APP_HANDLEshopikit-demoThe handle of shopify.app.toml
MAIL_*, SUPPORT_EMAIL, OWNER_EMAILSMTP for support emails and alerts (empty MAIL_HOST = emails skipped)
CURL_CA_BUNDLEC:/laragon/etc/ssl/cacert.pemWindows only, when curl cannot verify HTTPS (the wizard finds it)
ADMIN_DEMO0 / 11 = read-only owner admin, for a public live demo

#The demo app: Product Notes

A small but real app that shows every building block in use. Read it, run it, then replace it with your own app.

FeatureShows how toCode
DashboardRead from Shopify, show store info, plan usage, a getting-started list, ask for a reviewHttp/Pages/Dashboard.php
Product listGraphQL with cursor pagination and search, Polaris tableHttp/Pages/Notes.php show()
Private note per productStore app data per shop, apply a plan limit (notes_max)Models/Notes.php
Tag productWrite to Shopify (tagsAdd) with userErrors handlingNotes::tag()
Export CSVQueue a background job, poll its status, download a fileJobs/ExportNotes.php
PlansSubscribe, trial, yearly, downgrade, usage tilesHttp/Pages/Plan.php, Shopify/Billing.php
Announcement barTheme app embed with merchant settings and a deep linkextensions/announcement-bar
Product note cardAdmin block on the product page, reading your backendextensions/product-note-block, Pages/Block.php
products/updateHandle a webhook (keeps the note's product title fresh)Webhooks/ProcessWebhook.php
HelpSupport form with store context, FAQHttp/Pages/Docs.php

#Folder structure

app/
  Core/        Db, Env, AppSettings, Settings, Crypto, Http, I18n, Log, Mailer, RateLimiter, Totp, Usage
  Shopify/     Config, SessionToken, Tokens, Installer, Graphql, Billing, Hmac
  Http/        AppController (embedded app), AdminController (/admin), PublicSite, Shell, View, Context
  Http/Pages/  one class per embedded page (Dashboard, Notes, Plan, Settings, Docs, Block)
  Models/      Shops, Plans, Notes
  Queue/       Queue, Job, Registry
  Jobs/        InstallShop, BillingSync, ShopRedact, ExportNotes
  Webhooks/    Receiver (endpoint), ProcessWebhook (handlers)
bin/           install, make, migrate, worker, scheduler, admin-user, dev-server
extensions/    announcement-bar (theme app embed), product-note-block (admin block)
lang/en.json   every text of the embedded app
migrations/    numbered SQL files, applied by bin/migrate.php
public/        index.php (front controller) and assets/ (the only web-visible folder)
deploy/        deploy.sh, nginx.conf, systemd/, crontab.txt
tests/         PHPUnit

#Requests and pages

Shopify admin opens APP_URLโ†’Shell (App Bridge + Polaris)โ†’app.js fetches /frag/<page> with a session tokenโ†’AppController verifies itโ†’Page returns HTML or JSON

HTML attributes understood by app.js

AttributeEffect
data-nav="/notes"Navigate inside the app
<form data-action="/notes/save">POST the form to /frag/notes/save
data-post="/plan/cancel" data-pplan="pro"POST with field plan=pro (every data-p* becomes a field)
data-download="/notes/download?id=5"Fetch a file with the session token and save it
data-search="/notes"Search field that navigates to ?q=
data-refresh="5"Reload the page every 5 s while the element is present (job progress)

JSON answers can contain toast, error, redirect (in-app path), top (open a URL in the top window, e.g. the billing approval) and reload.

#Install and authentication

#Admin API (GraphQL)

// In a page: $this->ctx->graphql(). In a job: new Graphql($shop) or Graphql::forShopId($id)
$data = $this->ctx->graphql()->query('query($id: ID!) { product(id: $id) { title tags } }', ['id' => $gid]);

// Mutations: check userErrors
$res = $gql->query($mutation, $vars)['tagsAdd'];
Graphql::assertNoUserErrors($res, 'tagsAdd');   // throws GraphqlError with the messages

// Every item of a connection (jobs, exports)
foreach ($gql->paginate($query, 'products') as $product) { ... }

// One page for a list screen, forward or backward
$page = $gql->page($query, 'products', 20, $after, $before);

The client waits and retries when Shopify throttles, retries 5xx errors, and marks the shop's token invalid on 401 (a new token exchange happens when the merchant opens the app). Try queries in the owner admin's GraphQL console, or press g in shopify app dev for GraphiQL.

#Queue, worker, scheduler

Queue::push('demo.export_notes', ['shop_id' => $id, 'export_id' => $exportId], [
    'queue' => 'default',          // webhooks | default (add your own)
    'priority' => 4,               // lower = sooner
    'delay' => 0,                  // seconds
    'unique_key' => "export:$id",  // no duplicate while one is queued or running
]);

#Webhooks and GDPR

POST /webhooksโ†’HMAC checkโ†’dedupe by webhook idโ†’webhook_log + queueโ†’200 OKโ†’worker: ProcessWebhook
Every new table with a shop_idneeds ON DELETE CASCADE to shops, or an entry in ShopRedact::SHOP_TABLES. tests/RedactTest.php fails if you forget.

#Plans and billing

#Owner admin

At /admin, for you and your team (not embedded in Shopify). Create the first account with php bin/install.php or php bin/admin-user.php you@example.com.

PageWhat you do there
OverviewInstalls, uninstalls, estimated MRR per plan, worker status, failed jobs, errors, open tickets
ShopsSearch stores; per store: details, billing history, usage, errors, tickets, plan limit overrides, reload details, sync billing
PlansEdit prices, trials, limits, features; create plans
QueueWaiting jobs, failed jobs with error and payload, retry, run any job by hand
ErrorsErrors grouped by fingerprint with stack trace; mark resolved (they come back if they happen again)
WebhooksDeliveries per topic, latest deliveries with replay, GDPR requests
SupportMessages from the in-app help form, with store context; reply by email
GraphQL consoleRun a query or mutation on any installed store
System checkPHP, extensions, APP_KEY, keys, migrations, worker, cron, SMTP, production mode, and the URLs to copy
SettingsEverything in Settings and branding
Admin usersTeam accounts, authenticator codes (TOTP), audit log of every admin action

Security: rate-limited login, account lock after 5 failures, optional 6-digit authenticator code, session cookie limited to /admin, CSRF token on every form. Set ADMIN_DEMO=1 to show the admin publicly in read-only mode.

#Settings and branding

/admin/settings changes the app without touching code. A value is taken from the settings table, then from .env, then from the default.

GroupSettings
GeneralApp name, tagline, company, website, support and alert emails, install notifications
BrandingBrand and accent colours, logo (app, admin, public pages)
Embedded appNotice on every page, review prompt and delay, help intro, support messages per day
BillingBilling on/off, force test charges, yearly saving label, "Most popular" plan
EmailFrom address and name, support confirmations
MaintenanceKill switch for exports, log retention, deletion delay for uninstalled stores

Add your own setting: one line in AppSettings::FIELDS, then read it with AppSettings::get('your.key'), ::bool(), ::int() or ::string(). The form, validation and saving are automatic.

#Code generator

php bin/make.php page Reports            # page class + route + menu entry + texts
php bin/make.php job SendReport          # job class + Registry entry "app.send_report"
php bin/make.php webhook orders/create   # handler case in ProcessWebhook
php bin/make.php migration add_reports   # migrations/002_add_reports.sql

#Add a page

  1. Run php bin/make.php page Reports, or create app/Http/Pages/Reports.php extending BasePage.
  2. Route in AppController::ROUTES: 'GET /reports' => [Pages\Reports::class, 'show']; POST actions the same way.
  3. Menu entry in Shell::NAV and the texts in lang/en.json.
  4. Build the HTML with Polaris web components and the View helpers (page, table, hero, usage, emptyState, postButtonโ€ฆ). Always escape values with e().
public function show(): string
{
    $shop = $this->ctx->shop;                       // the current shop row
    $limit = Plans::cap($shop, 'reports_month');    // plan limit (null = unlimited)
    $html = '<s-section heading="' . e(t('reports.title')) . '">โ€ฆ</s-section>';
    return View::page(t('reports.title'), $html);
}

public function create(): array
{
    return ['toast' => t('reports.created'), 'reload' => true];
}

#Add a background job

php bin/make.php job SyncOrders
// app/Jobs/SyncOrders.php is created and registered as "app.sync_orders". Queue it:
Queue::push('app.sync_orders', ['shop_id' => $shopId], ['unique_key' => "sync_orders:$shopId"]);

Long work: process a chunk, save the cursor in the payload or a table, and return 2; to continue in 2 seconds. Daily work for every shop: add a Queue::push in the daily_shops task of bin/scheduler.php.

#Add a webhook

  1. Add the topic to [[webhooks.subscriptions]] topics in your shopify.app.*.toml (and the scope it needs).
  2. php bin/make.php webhook orders/create adds the handler case in ProcessWebhook. Large payloads can be trimmed in Receiver::trim().
  3. npx shopify app deploy (or restart shopify app dev), then test with shopify app webhook trigger.

#Add a plan limit

  1. In /admin/plans add the key to each plan's limits, e.g. "reports_month": 5 (Free), 50 (Basic), null (Pro = unlimited).
  2. Count usage: Usage::add($shopId, 'reports'), read it with Usage::used($shopId, 'reports').
  3. Check before the action: if ($limit !== null && $used >= $limit) return $this->limitReached(t('โ€ฆ'));
  4. Show it on the Plans page: one more View::usage() tile in Plan::show(), and a feature line in /admin/plans.

#Add a table

php bin/make.php migration add_reports   # edit migrations/002_add_reports.sql
php bin/migrate.php                       # applies pending migrations (php bin/migrate.php --status to list)

Give tables with a shop_id a foreign key REFERENCES shops(id) ON DELETE CASCADE. Queries go through Db: Db::one, Db::all, Db::value, Db::insert, Db::update, Db::upsert, Db::transaction, always with parameters.

#Extensions

Theme app embed: announcement bar

extensions/announcement-bar/blocks/announcement-bar.liquid is an app embed ("target": "body") with its settings in the schema. Merchants switch it on in the theme editor; the app's Settings page opens it directly with /admin/themes/current/editor?context=apps&activateAppId=<API key>/announcement-bar. Assets in assets/ are served by Shopify's CDN. No theme code is changed (App Store requirement).

Admin block: product note

extensions/product-note-block/src/BlockExtension.jsx renders on the product page of the Shopify admin (admin.product-details.block.render). It calls fetch('/frag/block/note?gid=โ€ฆ'): Shopify adds the session token automatically, and AppController::EXTENSION_PATHS answers with the CORS headers. The button opens the app with href="app:/notes/edit?id=โ€ฆ". Merchants add the block from the product page's Apps menu.

Deploy extensions and configuration with npx shopify app deploy (creates a new app version). During development shopify app dev serves them live.

#Texts and translations

Every text of the embedded app is in lang/en.json and is read with t('notes.saved', ['count' => 3]). To add a language, copy the file to lang/fr.json and translate it: the app uses the admin language Shopify sends (?locale=) and falls back to English for missing keys. Extensions have their own locales/ folders.

#Remove the demo

When your own app is ready, delete what belongs to Product Notes:

#Deploy to a VPS

  1. Server: Ubuntu 24.04 with nginx, PHP 8.3-FPM (+ curl, mbstring, mysql), MySQL 8, Composer, certbot.
  2. Code in /var/www/shopikit (git clone or deploy/deploy.sh --first), then composer install --no-dev --optimize-autoloader.
  3. .env with APP_ENV=production, APP_DEBUG=0, your domain in APP_URL, a new APP_KEY, then php bin/migrate.php and php bin/admin-user.php you@example.com.
  4. nginx: copy deploy/nginx.conf, replace the domain and paths, run certbot. The document root is public/ and HTTP_AUTHORIZATION must be passed to PHP (session tokens).
  5. Worker: copy deploy/systemd/shopikit-worker@.service and queues.env (see the comments) and systemctl enable --now shopikit-worker@main.
  6. Cron: the scheduler line of deploy/crontab.txt.
  7. Shopify: in shopify.app.toml set application_url to your domain, then npx shopify app deploy. Check /admin/system.

Updates: fill deploy/.deploy.env once, then after each commit run deploy/deploy.sh. It uploads only the changed files, keeps a local backup of the overwritten ones, runs migrations and restarts the workers.

#Shared hosting

#App Store checklist

What reviewers check, and what ShopiKit already does for you:

What you still do before submitting:

#Troubleshooting

502 Bad Gateway from trycloudflare.com during shopify app dev

The CLI proxy connects to localhost, which can be IPv6 (::1). bin/dev-server.php listens on localhost for this reason; if you start PHP yourself, use php -S localhost:PORT, not 127.0.0.1.

"SSL certificate problem: unable to get local issuer certificate"

PHP's curl on Windows has no CA list. Set CURL_CA_BUNDLE in .env to a cacert.pem (Laragon: C:/laragon/etc/ssl/cacert.pem, XAMPP: C:/xampp/php/extras/ssl/cacert.pem) and restart the worker.

"Apps without a public distribution cannot use the Billing API"

Choose Public distribution for the app in the Dev Dashboard (see Create the Shopify app).

Webhooks never arrive

Use relative URIs (uri = "/webhooks") in the toml, restart shopify app dev or run shopify app deploy, and make sure the worker runs. Deliveries appear in /admin/webhooks.

The app shows "Something went wrong"

Open /admin/errors: every failed request and job is there with its stack trace. Also check /admin/system.

Nothing happens after an action (export, install details)

The worker is not running. Start php bin/worker.php; the Overview page shows when it was last seen.

"Decryption failed (APP_KEY changed?)"

The tokens were encrypted with another APP_KEY. Restore the old key, or let merchants open the app again (a new token exchange replaces the token).

#Tests

composer test        # or: php vendor/bin/phpunit

The suite covers session tokens (including secret rotation), webhook and query HMAC, encryption, TOTP, shop domain validation and GDPR deletion (every table with a shop_id is covered). The database tests use the database in .env and are skipped if it is not reachable.

#Support and license

Item support is provided through the CodeCanyon item page (comments and the support tab). Please include your PHP version, what you did, and the error from /admin/errors.

License: building an app that merchants pay for requires the Extended License; see licensing/README.txt. ShopiKit is not affiliated with or endorsed by Shopify Inc. Shopify is a trademark of Shopify Inc.

Changelog: CHANGELOG.md.