@inferencebureau/apps-sdk 0.2.1 → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -1
- package/dist/index.d.ts +99 -0
- package/dist/index.js +97 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -74,7 +74,9 @@ with a key linked to the app.
|
|
|
74
74
|
Entry points:
|
|
75
75
|
|
|
76
76
|
- `@inferencebureau/apps-sdk`: metadata types, action helpers, `createClient`, `createShopifyClient`,
|
|
77
|
-
`verifyShopifySession`, `verifyProxyRequest`,
|
|
77
|
+
`verifyShopifySession`, `verifyProxyRequest`, Shopify Billing for public apps (`requestSubscription`,
|
|
78
|
+
`activeSubscriptions`, `recordUsage`, `cancelSubscription`, `managedPricingUrl`), and the errors they throw
|
|
79
|
+
(`ApiError`, `ShopifyError`, `ShopifyBillingError`).
|
|
78
80
|
- `@inferencebureau/apps-sdk/runtime`: `handleAction`, the signed `/_ib/actions` route every build adds.
|
|
79
81
|
- `@inferencebureau/apps-sdk/browser`: for an embedded admin page's client code: `sessionFetch`,
|
|
80
82
|
`shopifySessionToken`, `isPreview`, `previewSession`.
|
package/dist/index.d.ts
CHANGED
|
@@ -230,6 +230,8 @@ export declare function createClient(o?: ClientOptions): Api;
|
|
|
230
230
|
*/
|
|
231
231
|
export interface ShopifyClient {
|
|
232
232
|
shop: string;
|
|
233
|
+
/** The environment the client calls from (IB_ENVIRONMENT): Billing makes test charges outside production. */
|
|
234
|
+
environment?: string;
|
|
233
235
|
/** Runs an Admin GraphQL query or mutation and returns its `data`; GraphQL errors throw ShopifyError. */
|
|
234
236
|
graphql<T = any>(query: string, variables?: Record<string, unknown>): Promise<T>;
|
|
235
237
|
}
|
|
@@ -239,6 +241,103 @@ export declare class ShopifyError extends Error {
|
|
|
239
241
|
}
|
|
240
242
|
/** The Admin API for `shop`, as the environment (the same options as createClient). */
|
|
241
243
|
export declare function createShopifyClient(shop: string, o?: ClientOptions): ShopifyClient;
|
|
244
|
+
export interface Money {
|
|
245
|
+
amount: number | string;
|
|
246
|
+
currencyCode: string;
|
|
247
|
+
}
|
|
248
|
+
export interface SubscriptionRequest {
|
|
249
|
+
/** What the merchant sees on Shopify's approval page and their bill. */
|
|
250
|
+
name: string;
|
|
251
|
+
/** Where Shopify sends the merchant after they approve or decline (an embedded page of the app). */
|
|
252
|
+
returnUrl: string;
|
|
253
|
+
/** A fixed charge each period. */
|
|
254
|
+
recurring?: {
|
|
255
|
+
price: Money;
|
|
256
|
+
interval?: "EVERY_30_DAYS" | "ANNUAL";
|
|
257
|
+
};
|
|
258
|
+
/** Usage charges up to a cap each 30 days, recorded with `recordUsage`. `terms` is shown to the merchant. */
|
|
259
|
+
usage?: {
|
|
260
|
+
cappedAmount: Money;
|
|
261
|
+
terms: string;
|
|
262
|
+
};
|
|
263
|
+
trialDays?: number;
|
|
264
|
+
/** What happens to an active subscription: by default Shopify decides (upgrade now, downgrade at period end). */
|
|
265
|
+
replacementBehavior?: "APPLY_IMMEDIATELY" | "APPLY_ON_NEXT_BILLING_CYCLE" | "STANDARD";
|
|
266
|
+
/** Force a test charge, or (in production on a real store only) a real one. */
|
|
267
|
+
test?: boolean;
|
|
268
|
+
}
|
|
269
|
+
export interface AppSubscription {
|
|
270
|
+
id: string;
|
|
271
|
+
name: string;
|
|
272
|
+
status: string;
|
|
273
|
+
test: boolean;
|
|
274
|
+
trialDays: number;
|
|
275
|
+
currentPeriodEnd: string | null;
|
|
276
|
+
createdAt: string;
|
|
277
|
+
lineItems: {
|
|
278
|
+
id: string;
|
|
279
|
+
recurring?: {
|
|
280
|
+
price: Money;
|
|
281
|
+
interval: string;
|
|
282
|
+
};
|
|
283
|
+
usage?: {
|
|
284
|
+
cappedAmount: Money;
|
|
285
|
+
balanceUsed: Money;
|
|
286
|
+
terms: string;
|
|
287
|
+
};
|
|
288
|
+
}[];
|
|
289
|
+
}
|
|
290
|
+
export declare class ShopifyBillingError extends Error {
|
|
291
|
+
readonly userErrors: {
|
|
292
|
+
field?: string[] | null;
|
|
293
|
+
message: string;
|
|
294
|
+
}[];
|
|
295
|
+
constructor(message: string, userErrors?: {
|
|
296
|
+
field?: string[] | null;
|
|
297
|
+
message: string;
|
|
298
|
+
}[]);
|
|
299
|
+
}
|
|
300
|
+
/**
|
|
301
|
+
* Whether a charge for this store is a test charge: always outside production, and in production on a development
|
|
302
|
+
* store (Shopify's `partnerDevelopment` plan), unless `test` says otherwise.
|
|
303
|
+
*/
|
|
304
|
+
export declare function isTestCharge(shopify: ShopifyClient, test?: boolean): Promise<boolean>;
|
|
305
|
+
/**
|
|
306
|
+
* Starts a subscription and returns Shopify's `confirmationUrl`: redirect the merchant there (from an embedded page,
|
|
307
|
+
* open it at the top level) to approve. It's active once they do: `activeSubscriptions` or the synced model says so.
|
|
308
|
+
*/
|
|
309
|
+
export declare function requestSubscription(shopify: ShopifyClient, plan: SubscriptionRequest): Promise<{
|
|
310
|
+
confirmationUrl: string;
|
|
311
|
+
subscriptionId: string;
|
|
312
|
+
test: boolean;
|
|
313
|
+
}>;
|
|
314
|
+
/** The store's active subscriptions to this app (usually one), with each line's price or usage cap and balance. */
|
|
315
|
+
export declare function activeSubscriptions(shopify: ShopifyClient): Promise<AppSubscription[]>;
|
|
316
|
+
/**
|
|
317
|
+
* Charges usage on a subscription's usage line: the active one's unless `lineItemId` names another. Pass an
|
|
318
|
+
* `idempotencyKey` (an order id, a job id) so a retried action doesn't charge twice. Shopify refuses a charge past
|
|
319
|
+
* the line's cap; raise it with a new subscription (`replacementBehavior: "APPLY_IMMEDIATELY"`).
|
|
320
|
+
*/
|
|
321
|
+
export declare function recordUsage(shopify: ShopifyClient, charge: {
|
|
322
|
+
price: Money;
|
|
323
|
+
description: string;
|
|
324
|
+
idempotencyKey?: string;
|
|
325
|
+
lineItemId?: string;
|
|
326
|
+
}): Promise<{
|
|
327
|
+
id: string;
|
|
328
|
+
}>;
|
|
329
|
+
/** Cancels a subscription; `prorate` refunds the unused part of the period. */
|
|
330
|
+
export declare function cancelSubscription(shopify: ShopifyClient, id: string, o?: {
|
|
331
|
+
prorate?: boolean;
|
|
332
|
+
}): Promise<{
|
|
333
|
+
id: string;
|
|
334
|
+
status: string;
|
|
335
|
+
}>;
|
|
336
|
+
/**
|
|
337
|
+
* Shopify's plan page for an app on managed pricing (plans set in the Partner Dashboard): where to send a merchant
|
|
338
|
+
* to pick or change their plan. `appHandle` is the app's handle in the Partner Dashboard.
|
|
339
|
+
*/
|
|
340
|
+
export declare function managedPricingUrl(shop: string, appHandle: string): string;
|
|
242
341
|
export interface ShopifySession {
|
|
243
342
|
/** The store the admin page is open in (x.myshopify.com). */
|
|
244
343
|
shop: string;
|
package/dist/index.js
CHANGED
|
@@ -152,6 +152,7 @@ export function createShopifyClient(shop, o = {}) {
|
|
|
152
152
|
const f = o.fetch ?? fetch;
|
|
153
153
|
return {
|
|
154
154
|
shop,
|
|
155
|
+
environment,
|
|
155
156
|
async graphql(query, variables = {}) {
|
|
156
157
|
const res = await f(`${url}/v1/apps/${encodeURIComponent(app)}/environments/${encodeURIComponent(environment)}/shopify/graphql`, {
|
|
157
158
|
method: "POST", headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, body: JSON.stringify({ shop, query, variables }),
|
|
@@ -165,6 +166,102 @@ export function createShopifyClient(shop, o = {}) {
|
|
|
165
166
|
},
|
|
166
167
|
};
|
|
167
168
|
}
|
|
169
|
+
export class ShopifyBillingError extends Error {
|
|
170
|
+
userErrors;
|
|
171
|
+
constructor(message, userErrors = []) {
|
|
172
|
+
super(message);
|
|
173
|
+
this.userErrors = userErrors;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
const money = (m) => ({ amount: Number(m.amount), currencyCode: m.currencyCode });
|
|
177
|
+
const userErrorsOf = (what, errors) => {
|
|
178
|
+
if (errors?.length)
|
|
179
|
+
throw new ShopifyBillingError(`Shopify didn't ${what}: ${errors.map((e) => e.message).join("; ")}`, errors);
|
|
180
|
+
};
|
|
181
|
+
/**
|
|
182
|
+
* Whether a charge for this store is a test charge: always outside production, and in production on a development
|
|
183
|
+
* store (Shopify's `partnerDevelopment` plan), unless `test` says otherwise.
|
|
184
|
+
*/
|
|
185
|
+
export async function isTestCharge(shopify, test) {
|
|
186
|
+
if ((shopify.environment ?? "development") !== "production")
|
|
187
|
+
return true;
|
|
188
|
+
if (test !== undefined)
|
|
189
|
+
return test;
|
|
190
|
+
const data = await shopify.graphql(`query BillingShopPlan { shop { plan { partnerDevelopment } } }`);
|
|
191
|
+
return data.shop.plan.partnerDevelopment;
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Starts a subscription and returns Shopify's `confirmationUrl`: redirect the merchant there (from an embedded page,
|
|
195
|
+
* open it at the top level) to approve. It's active once they do: `activeSubscriptions` or the synced model says so.
|
|
196
|
+
*/
|
|
197
|
+
export async function requestSubscription(shopify, plan) {
|
|
198
|
+
if (!plan.recurring && !plan.usage)
|
|
199
|
+
throw new ShopifyBillingError("A subscription needs a recurring price, usage charges, or both.");
|
|
200
|
+
const lineItems = [
|
|
201
|
+
...(plan.recurring ? [{ plan: { appRecurringPricingDetails: { price: money(plan.recurring.price), interval: plan.recurring.interval ?? "EVERY_30_DAYS" } } }] : []),
|
|
202
|
+
...(plan.usage ? [{ plan: { appUsagePricingDetails: { cappedAmount: money(plan.usage.cappedAmount), terms: plan.usage.terms } } }] : []),
|
|
203
|
+
];
|
|
204
|
+
const test = await isTestCharge(shopify, plan.test);
|
|
205
|
+
const data = await shopify.graphql(`
|
|
206
|
+
mutation BillingSubscribe($name: String!, $lineItems: [AppSubscriptionLineItemInput!]!, $returnUrl: URL!, $trialDays: Int, $test: Boolean, $replacementBehavior: AppSubscriptionReplacementBehavior) {
|
|
207
|
+
appSubscriptionCreate(name: $name, lineItems: $lineItems, returnUrl: $returnUrl, trialDays: $trialDays, test: $test, replacementBehavior: $replacementBehavior) {
|
|
208
|
+
confirmationUrl appSubscription { id } userErrors { field message }
|
|
209
|
+
}
|
|
210
|
+
}`, { name: plan.name, lineItems, returnUrl: plan.returnUrl, trialDays: plan.trialDays ?? null, test, replacementBehavior: plan.replacementBehavior ?? null });
|
|
211
|
+
userErrorsOf("start the subscription", data.appSubscriptionCreate.userErrors);
|
|
212
|
+
if (!data.appSubscriptionCreate.confirmationUrl || !data.appSubscriptionCreate.appSubscription)
|
|
213
|
+
throw new ShopifyBillingError("Shopify didn't return a confirmation URL.");
|
|
214
|
+
return { confirmationUrl: data.appSubscriptionCreate.confirmationUrl, subscriptionId: data.appSubscriptionCreate.appSubscription.id, test };
|
|
215
|
+
}
|
|
216
|
+
const SUBSCRIPTION = `id name status test trialDays currentPeriodEnd createdAt
|
|
217
|
+
lineItems { id plan { pricingDetails { __typename
|
|
218
|
+
... on AppRecurringPricing { price { amount currencyCode } interval }
|
|
219
|
+
... on AppUsagePricing { cappedAmount { amount currencyCode } balanceUsed { amount currencyCode } terms } } } }`;
|
|
220
|
+
const subscriptionOf = (s) => ({
|
|
221
|
+
...s,
|
|
222
|
+
lineItems: s.lineItems.map((l) => {
|
|
223
|
+
const d = l.plan.pricingDetails;
|
|
224
|
+
return d.__typename === "AppUsagePricing" ? { id: l.id, usage: { cappedAmount: d.cappedAmount, balanceUsed: d.balanceUsed, terms: d.terms ?? "" } } : { id: l.id, recurring: { price: d.price, interval: d.interval ?? "EVERY_30_DAYS" } };
|
|
225
|
+
}),
|
|
226
|
+
});
|
|
227
|
+
/** The store's active subscriptions to this app (usually one), with each line's price or usage cap and balance. */
|
|
228
|
+
export async function activeSubscriptions(shopify) {
|
|
229
|
+
const data = await shopify.graphql(`query BillingActive { currentAppInstallation { activeSubscriptions { ${SUBSCRIPTION} } } }`);
|
|
230
|
+
return data.currentAppInstallation.activeSubscriptions.map(subscriptionOf);
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* Charges usage on a subscription's usage line: the active one's unless `lineItemId` names another. Pass an
|
|
234
|
+
* `idempotencyKey` (an order id, a job id) so a retried action doesn't charge twice. Shopify refuses a charge past
|
|
235
|
+
* the line's cap; raise it with a new subscription (`replacementBehavior: "APPLY_IMMEDIATELY"`).
|
|
236
|
+
*/
|
|
237
|
+
export async function recordUsage(shopify, charge) {
|
|
238
|
+
let line = charge.lineItemId;
|
|
239
|
+
if (!line) {
|
|
240
|
+
line = (await activeSubscriptions(shopify)).flatMap((s) => s.lineItems).find((l) => l.usage)?.id;
|
|
241
|
+
if (!line)
|
|
242
|
+
throw new ShopifyBillingError(`${shopify.shop} has no active subscription with usage charges.`);
|
|
243
|
+
}
|
|
244
|
+
const data = await shopify.graphql(`
|
|
245
|
+
mutation BillingUsage($line: ID!, $price: MoneyInput!, $description: String!, $key: String) {
|
|
246
|
+
appUsageRecordCreate(subscriptionLineItemId: $line, price: $price, description: $description, idempotencyKey: $key) { appUsageRecord { id } userErrors { field message } }
|
|
247
|
+
}`, { line, price: money(charge.price), description: charge.description, key: charge.idempotencyKey ?? null });
|
|
248
|
+
userErrorsOf("record the usage charge", data.appUsageRecordCreate.userErrors);
|
|
249
|
+
return { id: data.appUsageRecordCreate.appUsageRecord.id };
|
|
250
|
+
}
|
|
251
|
+
/** Cancels a subscription; `prorate` refunds the unused part of the period. */
|
|
252
|
+
export async function cancelSubscription(shopify, id, o = {}) {
|
|
253
|
+
const data = await shopify.graphql(`
|
|
254
|
+
mutation BillingCancel($id: ID!, $prorate: Boolean) { appSubscriptionCancel(id: $id, prorate: $prorate) { appSubscription { id status } userErrors { field message } } }`, { id, prorate: o.prorate ?? false });
|
|
255
|
+
userErrorsOf("cancel the subscription", data.appSubscriptionCancel.userErrors);
|
|
256
|
+
return data.appSubscriptionCancel.appSubscription;
|
|
257
|
+
}
|
|
258
|
+
/**
|
|
259
|
+
* Shopify's plan page for an app on managed pricing (plans set in the Partner Dashboard): where to send a merchant
|
|
260
|
+
* to pick or change their plan. `appHandle` is the app's handle in the Partner Dashboard.
|
|
261
|
+
*/
|
|
262
|
+
export function managedPricingUrl(shop, appHandle) {
|
|
263
|
+
return `https://admin.shopify.com/store/${shop.replace(/\.myshopify\.com$/, "")}/charges/${encodeURIComponent(appHandle)}/pricing_plans`;
|
|
264
|
+
}
|
|
168
265
|
/**
|
|
169
266
|
* The store and staff member behind a request from one of the app's pages in the Shopify admin, or null when it
|
|
170
267
|
* carries no valid session token. App Bridge's `shopify.idToken()` gives the page its token; send it as
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@inferencebureau/apps-sdk",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.2",
|
|
4
4
|
"description": "The SDK an Inference Bureau app's code imports: action helpers, metadata types, the records API client and a test harness for its actions.",
|
|
5
5
|
"license": "UNLICENSED",
|
|
6
6
|
"keywords": [
|