#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.
Managed install with token exchange (no OAuth redirects), expiring offline tokens refreshed automatically, App Bridge session tokens checked on every request.
GraphQL client with cost-based throttling, retries, cursor pagination and userErrors handling.
Free / Basic / Pro, monthly and yearly, free trial, upgrade, downgrade, test charges on development stores, daily reconciliation.
One HMAC-verified endpoint, deduplication, queued processing, replay, the 3 compliance topics and automatic data deletion.
MySQL queue with retries and backoff, worker for systemd or cron, scheduler for recurring tasks.
A theme app embed (announcement bar) and an admin block (product page card) that talks to your backend.
Overview and MRR, shops, plan editor, queue, errors, webhooks, support tickets, GraphQL console, system check, settings, admin users with authenticator codes.
Setup wizard, code generator, shopify app dev integration, tests, deploy script and server templates.
#Requirements
| What | Version | Notes |
|---|---|---|
| PHP | 8.3 or newer | Extensions: curl, json, mbstring, openssl, pdo_mysql |
| MySQL | 8.0+ (or MariaDB 10.6+) | The queue uses SELECT โฆ FOR UPDATE SKIP LOCKED |
| Composer | 2.x | Installs PHPMailer (and PHPUnit for tests) |
| Node.js | 22.12+ | Only for the Shopify CLI and the admin block extension, never on the server |
| Shopify | Partner account + a development store | Free at shopify.com/partners |
| Production | HTTPS domain | nginx 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.
Install the dependencies in the project folder:
composer install npm installRun the setup wizard. It creates
.env, generatesAPP_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.phpConnect 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 linkThis writes
shopify.app.<name>.tomlwith your Client ID. Copy the[access_scopes]and[webhooks]sections fromshopify.app.tomlinto it if they are missing (see Create the Shopify app).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.shopifyCopy
SHOPIFY_API_KEYandSHOPIFY_API_SECRETfrom.env.shopifyinto.env, then delete.env.shopify.Start the app. The CLI opens a tunnel, points the app at it and starts the PHP server (
shopify.web.toml):npx shopify app devChoose your development store, then press p and install the app.
Start the worker in a second terminal (background jobs: shop details, exports, webhooks):
php bin/worker.phpOpen the owner admin at
<tunnel URL>/adminand check System check.
.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
| Key | Value in ShopiKit | Why |
|---|---|---|
client_id | your app's Client ID | Written by shopify app config link |
handle | shopikit-demo | Must equal SHOPIFY_APP_HANDLE: used for the billing return URL |
application_url | your APP_URL | The embedded app; updated to the tunnel during shopify app dev |
embedded | true | The app runs inside the Shopify admin |
scopes | read_products,write_products | Ask only for what you use (App Store rule) |
use_legacy_install_flow | false | Shopify-managed install: no OAuth code in your app |
webhooks.subscriptions | uri = "/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".
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.
| Variable | Example | Meaning |
|---|---|---|
APP_NAME | Product Notes | Name shown to merchants and in subscription names |
APP_ENV | local / production | production + a real store = real charges |
APP_URL | https://app.example.com | Public HTTPS URL (set automatically during shopify app dev) |
APP_DEBUG | 1 / 0 | 0 on the live server |
APP_KEY | base64, 32 bytes | Encrypts Shopify tokens in the database. Never change it after going live |
DB_* | MySQL connection | |
SHOPIFY_API_KEY, SHOPIFY_API_SECRET | Client ID and secret from the Dev Dashboard | |
SHOPIFY_API_SECRET_OLD | Previous secret during a rotation (still accepted for webhooks and session tokens) | |
SHOPIFY_API_VERSION | 2026-10 | Admin API version; keep it equal to webhooks.api_version |
SHOPIFY_APP_HANDLE | shopikit-demo | The handle of shopify.app.toml |
MAIL_*, SUPPORT_EMAIL, OWNER_EMAIL | SMTP for support emails and alerts (empty MAIL_HOST = emails skipped) | |
CURL_CA_BUNDLE | C:/laragon/etc/ssl/cacert.pem | Windows only, when curl cannot verify HTTPS (the wizard finds it) |
ADMIN_DEMO | 0 / 1 | 1 = 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.
| Feature | Shows how to | Code |
|---|---|---|
| Dashboard | Read from Shopify, show store info, plan usage, a getting-started list, ask for a review | Http/Pages/Dashboard.php |
| Product list | GraphQL with cursor pagination and search, Polaris table | Http/Pages/Notes.php show() |
| Private note per product | Store app data per shop, apply a plan limit (notes_max) | Models/Notes.php |
| Tag product | Write to Shopify (tagsAdd) with userErrors handling | Notes::tag() |
| Export CSV | Queue a background job, poll its status, download a file | Jobs/ExportNotes.php |
| Plans | Subscribe, trial, yearly, downgrade, usage tiles | Http/Pages/Plan.php, Shopify/Billing.php |
| Announcement bar | Theme app embed with merchant settings and a deep link | extensions/announcement-bar |
| Product note card | Admin block on the product page, reading your backend | extensions/product-note-block, Pages/Block.php |
| products/update | Handle a webhook (keeps the note's product title fresh) | Webhooks/ProcessWebhook.php |
| Help | Support form with store context, FAQ | Http/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
public/index.phproutes/webhooks,/frag/*(embedded app),/admin/*(owner admin),/healthand the public pages.- Shell is a static page: App Bridge and Polaris first (App Store requirement), the app menu (
Shell::NAV) and a loader. It contains no shop data. - app.js loads each page as an HTML fragment with the session token in the
Authorizationheader and keeps the address bar in sync, so Shopify's menu highlights the right item. - A page action returns a string (HTML), an array (JSON for toasts, redirects, reloads) or a Download (a file).
HTML attributes understood by app.js
| Attribute | Effect |
|---|---|
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
- Session tokens: every
/fragrequest carries an App Bridge JWT.SessionToken::verify()checks signature (current or old secret), expiry, audience and that the shop is a real*.myshopify.com. - Managed install: the first request of a new shop exchanges that token for an expiring offline token (
Tokens::exchange()). No OAuth redirect code is needed. - Refresh:
Tokens::accessToken()refreshes the token 5 minutes before it expires, under a per-shop lock, so parallel workers never refresh twice. - Tokens are stored encrypted (AES-256-GCM with
APP_KEY). - After install, the
shop.installjob loads the store details. Put your first-run work inJobs/InstallShop.php. - Embedded responses send
Content-Security-Policy: frame-ancestorsfor the shop and admin.shopify.com.
#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
]);
- A job class implements
Queue\Job. Returntruewhen done, an int N to run again in N seconds (chunked work), or throw to retry with backoff (30 s, 2 min, 8 min). After the last attempt it moves to failed jobs in the admin. bin/worker.phpprocesses the queues. It exits by itself after 500 jobs or 256 MB, so run it under systemd (restarts it) or cron (--until-empty --max-seconds=55).bin/scheduler.phpruns every minute from cron: recovers stale jobs, daily billing sync per shop, retention clean-up, privacy safety net. Add tasks with$every('name', seconds, fn () => โฆ).
#Webhooks and GDPR
- Shopify gets its answer in milliseconds; the work happens in the worker.
- app/uninstalled: tokens deleted, jobs cancelled. app_subscriptions/update: billing state synced. shop/update: store details refreshed.
- customers/data_request, customers/redact: recorded (the demo stores no customer data; add your export / deletion there if your app does).
- shop/redact (48 h after uninstall): every row of the shop is deleted (
Jobs/ShopRedact.php). A safety net deletes uninstalled shops after 30 days even if it never arrives. - Test a topic:
npx shopify app webhook trigger --topic products/update --address <APP_URL>/webhooks. Replay real deliveries from /admin/webhooks.
ON DELETE CASCADE to shops, or an entry in ShopRedact::SHOP_TABLES. tests/RedactTest.php fails if you forget.#Plans and billing
- Plans live in the
planstable and are edited in /admin/plans: name, price, trial days, visibility, order, limits (JSON), trial limits and the feature lines shown on the plan card. - A yearly plan has the code of its monthly plan plus
_yearly(pro_yearly) and uses the monthly plan's limits. The Plans page shows a Monthly / Yearly switch when yearly plans exist. - The merchant approves on Shopify's screen and comes back to
/billing/return; the state is always read from Shopify, never from the URL. - Limits:
Plans::cap($shop, 'notes_max')returns an int, ornullfor unlimited. Per-shop overrides are set in /admin/shop. - Turn billing off entirely in /admin/settings โ Billing (free app): every store uses the Free plan.
#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.
| Page | What you do there |
|---|---|
| Overview | Installs, uninstalls, estimated MRR per plan, worker status, failed jobs, errors, open tickets |
| Shops | Search stores; per store: details, billing history, usage, errors, tickets, plan limit overrides, reload details, sync billing |
| Plans | Edit prices, trials, limits, features; create plans |
| Queue | Waiting jobs, failed jobs with error and payload, retry, run any job by hand |
| Errors | Errors grouped by fingerprint with stack trace; mark resolved (they come back if they happen again) |
| Webhooks | Deliveries per topic, latest deliveries with replay, GDPR requests |
| Support | Messages from the in-app help form, with store context; reply by email |
| GraphQL console | Run a query or mutation on any installed store |
| System check | PHP, extensions, APP_KEY, keys, migrations, worker, cron, SMTP, production mode, and the URLs to copy |
| Settings | Everything in Settings and branding |
| Admin users | Team 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.
| Group | Settings |
|---|---|
| General | App name, tagline, company, website, support and alert emails, install notifications |
| Branding | Brand and accent colours, logo (app, admin, public pages) |
| Embedded app | Notice on every page, review prompt and delay, help intro, support messages per day |
| Billing | Billing on/off, force test charges, yearly saving label, "Most popular" plan |
| From address and name, support confirmations | |
| Maintenance | Kill 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
- Run
php bin/make.php page Reports, or createapp/Http/Pages/Reports.phpextendingBasePage. - Route in
AppController::ROUTES:'GET /reports' => [Pages\Reports::class, 'show']; POST actions the same way. - Menu entry in
Shell::NAVand the texts inlang/en.json. - Build the HTML with Polaris web components and the
Viewhelpers (page,table,hero,usage,emptyState,postButtonโฆ). Always escape values withe().
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
- Add the topic to
[[webhooks.subscriptions]] topicsin yourshopify.app.*.toml(and the scope it needs). php bin/make.php webhook orders/createadds the handler case inProcessWebhook. Large payloads can be trimmed inReceiver::trim().npx shopify app deploy(or restartshopify app dev), then test withshopify app webhook trigger.
#Add a plan limit
- In /admin/plans add the key to each plan's limits, e.g.
"reports_month": 5(Free),50(Basic),null(Pro = unlimited). - Count usage:
Usage::add($shopId, 'reports'), read it withUsage::used($shopId, 'reports'). - Check before the action:
if ($limit !== null && $used >= $limit) return $this->limitReached(t('โฆ')); - Show it on the Plans page: one more
View::usage()tile inPlan::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:
Http/Pages/Notes.php,Block.php,Models/Notes.php,Jobs/ExportNotes.phpand their routes, menu entry and registry line- The
products/updateandproducts/deletecases inProcessWebhookand the topics in the toml - The
product_notesandexportstables (a new migration withDROP TABLE) and the export clean-up in the scheduler - The two folders in
extensions/, the demo texts inlang/en.jsonand the "Product Notes (demo)" group inAppSettings - The getting-started steps in
Dashboard.phpand the demo limits in/admin/plans
#Deploy to a VPS
- Server: Ubuntu 24.04 with nginx, PHP 8.3-FPM (+ curl, mbstring, mysql), MySQL 8, Composer, certbot.
- Code in
/var/www/shopikit(git clone ordeploy/deploy.sh --first), thencomposer install --no-dev --optimize-autoloader. - .env with
APP_ENV=production,APP_DEBUG=0, your domain inAPP_URL, a newAPP_KEY, thenphp bin/migrate.phpandphp bin/admin-user.php you@example.com. - nginx: copy
deploy/nginx.conf, replace the domain and paths, run certbot. The document root ispublic/andHTTP_AUTHORIZATIONmust be passed to PHP (session tokens). - Worker: copy
deploy/systemd/shopikit-worker@.serviceandqueues.env(see the comments) andsystemctl enable --now shopikit-worker@main. - Cron: the scheduler line of
deploy/crontab.txt. - Shopify: in
shopify.app.tomlsetapplication_urlto your domain, thennpx 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
- Point the domain's document root to
public/(or uploadpublic/intopublic_htmland the rest one level above it; adjust the path inpublic/index.php). - Make sure the
Authorizationheader reaches PHP. On Apache add topublic/.htaccess:RewriteEngine On,RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}], then route everything that is not a file toindex.php. - No systemd: run the worker from cron every minute:
php bin/worker.php --until-empty --max-seconds=55(seedeploy/crontab.txt). - Run the migrations once from SSH, or from the host's "run PHP script" tool:
php bin/migrate.php.
#App Store checklist
What reviewers check, and what ShopiKit already does for you:
- Shopify-managed install and token exchange; the app opens right after install, without extra login
- Session-token authentication on every request; App Bridge and Polaris loaded from Shopify's CDN, first in the page
frame-ancestorsCSP for clickjacking protection- The 3 mandatory compliance webhooks, HMAC-verified, answered quickly, data deleted on
shop/redact - Billing through the Billing API only; plan changes and cancellation available inside the app; test charges on development stores
- Theme changes only through a theme app extension (nothing written into theme files)
- Expiring offline tokens with refresh
What you still do before submitting:
- Request only the scopes your app really uses, and explain each in the listing.
- Review the privacy policy at
/privacyand the terms at/termsfor your app, and set the company and support email in /admin/settings. - Test install, every page, plan subscribe and cancel, uninstall and reinstall on a fresh development store, with
APP_ENV=production. - Prepare the listing: icon 1200ร1200, screenshots, a screencast showing setup and the main features, a test store or instructions for the reviewer.
- No errors in the browser console and no broken links in the app; the app must work in the Shopify mobile app too.
#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.