Repository files navigation

Shopify Admin API

Shopify Admin API for Node.js is a promise-driven NodeJS library built to help developers easily authenticate and make calls against the Shopify API. It is forked from the deprecated Shopify-Prime library.

Shopify Admin API is complete with full TypeScript definitions for all classes, interfaces and functions, and provides many quality of life improvements over most other Node Shopify libs. Tired of using undocumented libs that haven't been updated in ages, expect you to know all of the URL paths, and are little more than a basic wrapper over Node's http library? Give Shopify Admin API a try!

Installation

Shopify Admin API can be installed from NPM:

npm install shopify-admin-api --save

After installation, import Shopify Admin API via Node's require or ES6 import syntax:

//via requireconstShopify=require("shopify-admin-api");//via ES6import*asShopifyfrom"shopify-admin-api";

Tests

To run the tests on your locale machine you need a Shopify test shop in which you have created a private app, then you have to copy the credentials of the private app in the .env file in this project root directory. You can use the .env-example as a template:

cp .env-example .env
editor-of-your-choice .env

Now the test can be started:

yarn run build
yarn run test

Typescript declarations

Using TypeScript? The TypeScript compiler will automatically pull in Shopify Admin API definitions for you when you install Shopify Admin API, as long as you're using TypeScript 2+. Interfaces and extra types are available under the Interfaces, Enums and Options exports from the main "shopify-admin-api" module.

import{Shops}from"shopify-admin-api";// Typescript interfaces — not real JS objects:import{Interfaces,Enums,Options}from"shopify-admin-api";constshop: InterfacesShop=awaitnewShops(shopDomain,shopAccessToken).get(shopId);

Finally, because Shopify Admin API uses async/await and promises, you'll need to set your tsconfig.json's target to "es6". While not strictly necessary, Typescript won't know about the Promise type and will default all services' return types to any if you don't set your target to es6.

Async/await and promises

All Shopify Admin API functions are implemented as async/awaitable promises. You'll need Node.js v4 and above to use Shopify Admin API, as Node v3 and below don't support the generators needed for async/await.

Because async/await implements a promise-like interface in ES6, you can use the functions in this library in two different ways:

With async/await:

//1. async/awaitconstshop=awaitshops.get();//Do something with the shop

With promises:

constshop=shops.get().then((shop)=>{//Do something with the shop.});

Both methods are supported and the results won't differ. The only difference is an awaited method will throw an error if the method fails, where a promise would just fail silently unless you use .catch.

For the sake of being concise, all examples in this doc will use async/await.

A work-in-progress

This library is still pretty new. It currently suppports the following Shopify APIs:

More functionality will be added each week until it reachs full parity with Shopify's REST API.

Using Shopify Admin API with a public Shopify app

Note: All instances of shopAccessToken in the examples below do not refer to your Shopify API key. An access token is the token returned after authenticating and authorizing a Shopify app installation with a real Shopify store.

All instances of shopDomain refer to your users' *.myshopify.com URL (although their custom domain should work too).

import{Charges}from"shopify-admin-api";constchargeService=newCharges(shopDomain,shopAccessToken);

Using Shopify Admin API with a private Shopify app

Shopify Admin API should work out of the box with your private Shopify application, all you need to do is replace the shopAccessToken with your private app's password when initializing a service:

import{Orders}from"shopify-admin-api";constorderService=newOrders(shopDomain,privateAppPassword)

If you just need an access token for a private Shopify app, or for running the tests in this library, refer to the Tests section above.

Authorization and authentication

Ensure a given URL is a valid Shopify URL

This is a convenience method that validates whether a given URL is a valid Shopify shop. It's great for ensuring you don't redirect a user to an incorrect URL when you need them to authorize your app installation, and is ideally used in conjuction with .buildAuthorizationUrl.

Shopify Admin API will call the given URL and check for an X-ShopId header in the response. That header is present on all Shopify shops and its existence signals that the URL is indeed a Shopify URL.

Note, however, that this feature is undocumented by Shopify and may break at any time. Use at your own discretion.

import{Auth}from"shopify-admin-api";consturlFromUser="https://example.myshopify.com";constisValidUrl=awaitAuth.isValidMyShopifyDomain(urlFromUser).

Build an authorization URL

Redirect your users to this authorization URL, where they'll be prompted to install your app to their Shopify store.

import{Auth}from"shopify-admin-api";//This is the user's store URL.constusersShopifyUrl="https://example.myshopify.com";//An optional URL to redirect the user to after they've confirmed app installation.//If you don't specify a redirect url, Shopify will redirect to your app's default URL.constredirectUrl="https://example.com/my/redirect/url";//An array of the Shopify access scopes your application needs to run.constscopes=["read_orders","write_orders"];//Build the URL and send your user to it where they'll be prompted to install your app.constauthUrl=awaitAuth.buildAuthorizationUrl(scopes,usersShopifyUrl,yourShopifyApiKey,redirectUrl);

Authorize an installation and generate an access token

Once you've sent a user to the authorization URL and they've confirmed your app installation, they'll be redirected back to your application at either the default app URL, or the redirect URL you passed in when building the authorization URL.

The access token you receive after authorizing should be stored in your database. You'll need it to access the shop's resources (e.g. orders, customers, fulfillments, etc.)

import{Auth}from"shopify-admin-api";// The querystring will have several parameters you need for authorization.// Refer to your server framework docs for details on getting a request querystring.constcode=request.QueryString["code"];constshopUrl=request.QueryString["shop"];constaccessToken=awaitAuth.authorize(code,shopUrl,shopifyApiKey,shopifySecretKey)

Determine if a request is authentic

Any (non-webhook, non-proxy-page) request coming from Shopify will have a querystring paramater called 'hmac' that you can use to verify that the request is authentic. This hmac value is a hash of all querystring parameters and your app's secret key.

Pass the entire querystring to .isAuthenticRequest to verify the request.

import{Auth}from"shopify-admin-api";constqs=request.QueryString;constisAuthentic=awaitAuth.isAuthenticRequest(qs,shopifySecretKey);if(isAuthentic){//Request is authentic.}else{//Request is not authentic and should not be acted on.}

Determine if a proxy page request is authentic

Nearly identical to authenticating normal requests, a proxy page request only differs in the way the querystring is formatted to calculate the hmac signature. All proxy page requests coming from Shopify will have a querystring parameter named signature that you can use to verify the request. This signature is a hash of all querystring parameters and your app's secret key.

import{Auth}from"shopify-admin-api";constqs=request.QueryString;constisAuthentic=awaitAuth.isAuthenticProxyRequest(qs,shopifySecretKey);if(isAuthentic){//Request is authentic.}else{//Request is not authentic and should not be acted on.}

Determine if a webhook request is authentic

Any webhook request coming from Shopify will have a header called 'X-Shopify-Hmac-SHA256' that you can use to verify that the webhook is authentic. The header is a hash of the entire request body and your app's secret key.

Pass that header and the request body string to .isAuthenticWebhook to verify the request.

import{Auth}from"shopify-admin-api";consthmacHeader=request.QueryString["X-Shopify-Hmac-SHA256"];constbody=request.body.toString();constisAuthentic=awaitAuth.isAuthenticWebhook(hmacHeader,body,shopifySecretKey);if(isAuthentic){//Webhook is authentic.}else{//Webhook is not authentic and should not be acted on.}

You can also pass in the request body as a string, rather than using the input stream. However, the request body string needs to be identical to the way it was sent from Shopify. If it has been modified, the verification will fail.

Recurring Application Charges (monthly subscriptions)

The Shopify billing API lets you create a recurring charge on a shop owner's account, letting them pay you on a monthly basis for using your application.

Create a recurring charge

import{RecurringCharges}from"shopify-admin-api";constservice=newRecurringCharges(shopDomain,shopAccessToken);letcharge={
Name ="Lorem Ipsum Plan",
Price =12.34,
Test =true,//Marks this charge as a test, meaning it won't charge the shop owner.
TrialDays =21//Don't charge the user for 21 days}charge=awaitservice.create(charge);

Retrieve a recurring charge

import{RecurringCharges}from"shopify-admin-api";constservice=newRecurringCharges(shopDomain,shopAccessToken);constcharge=awaitservice.get(chargeId);

Listing recurring charges

import{RecurringCharges}from"shopify-admin-api";constservice=newRecurringCharges(shopDomain,shopAccessToken);constlist=awaitservice.list();

Activating a charge

Creating a charge does not actually charge the shop owner or even start their free trial. You need to send them to the charge's confirmation_url, have them accept the charge, then activate it.

import{RecurringCharges}from"shopify-admin-api";constservice=newRecurringCharges(shopDomain,shopAccessToken);awaitservice.activate(chargeId);

Deleting a charge

Charges cannot be deleted unless they've been activated. Shopify automatically deletes pending charges after 48 hours pass without activation.

import{RecurringCharges}from"shopify-admin-api";constservice=newRecurringCharges(shopDomain,shopAccessToken);awaitservice.delete(chargeId);

One-time application charges

Just like with the above recurring charges, the Shopify billing API lets you create a one-time application charge on the shop owner's account. One-time charges cannot be deleted.

Create a one-time charge

import{Charges}from"shopify-admin-api";constservice=newCharges(shopDomain,shopAccessToken);letcharge={
Name ="Lorem Ipsum Charge",
Price =12.34,
Test =true,//Marks this charge as a test, meaning it won't charge the shop owner.}charge=awaitservice.create(charge);

Retrieve a one-time charge

import{Charges}from"shopify-admin-api";constservice=newCharges(shopDomain,shopAccessToken);constcharge=awaitservice.get(chargeId);

Listing one-time charges

import{Charges}from"shopify-admin-api";constservice=newCharges(shopDomain,shopAccessToken);constlist=service.list();

Activating a charge

Just like recurring charges, creating a one-time charge does not actually charge the shop owner. You need to send them to the charge's ConfirmationUrl, have them accept the charge, then activate it.

import{Charges}from"shopify-admin-api";constservice=newCharges(shopDomain,shopAccessToken);awaitservice.activate(chargeId);

Usage charges

Shopify's Usage Charges let you set a capped amount on a recurring application charge, and only charge for usage. For example, you can create a charge that's capped at $100.00 per month, and then charge e.g. $1.00 for every 1000 emails your user sends using your app.

To create a usage charge, you first need to create a recurring charge with a capped_amount value and a terms string. Your customers will see the terms when activating the recurring charge, so set it to something they can read like "$1.00 per 1000 emails".

Creating a usage charge

import{UsageCharges}from"shopify-admin-api";constservice=newUsageCharges(shopDomain,shopAccessToken);constcharge=awaitservice.create(recurringChargeId,{description: "Used 1000 emails",price: 1.00});

Getting a usage charge

import{UsageCharges}from"shopify-admin-api";constservice=newUsageCharges(shopDomain,shopAccessToken);constcharge=awaitservice.get(recurringChargeId,usageChargeId);

Listing usage charges

import{UsageCharges}from"shopify-admin-api";constservice=newUsageCharges(shopDomain,shopAccessToken);constlist=awaitservice.list(recurringChargeId);

Shops

Retrieving shop information

import{Shops}from"shopify-admin-api";constservice=newShops(shopDomain,shopAccessToken);constshop=awaitservice.get();

Uninstalling your app

In cases where user intervention is not required, you can send a request to a Shopify shop to force it to uninstall your application. After sending this request, the shop access token will be immediately revoked and invalidated.

Uninstalling an application is an irreversible operation. Be entirely sure that you no longer need to make API calls for the shop in which the application has been installed.

Uninstalling an application also performs various cleanup tasks within Shopify. Registered Webhooks, ScriptTags and App Links will be destroyed as part of this operation. Also if an application is uninstalled during key rotation, both the old and new Access Tokens will be rendered useless.

import{Shops}from"shopify-admin-api";constservice=newShops(shopDomain,shopAccessToken);awaitshop.forceUninstallApp();

Webhooks

Creating a webhook

import{Webhooks}from"shopify-admin-api";constservice=newWebhooks(shopDomain,shopAccessToken);letwebhook={
address ="https://my.webhook.url.com/path",
topic ="themes/publish",};webhook=awaitservice.create(webhook);

Retrieving a webhook

import{Webhooks}from"shopify-admin-api";constservice=newWebhooks(shopDomain,shopAccessToken);constwebhook=awaitservice.get(webhookId);

Updating a webhook

import{Webhooks}from"shopify-admin-api";constservice=newWebhooks(shopDomain,shopAccessToken);constwebhook=awaitservice.update(webhookId,{address: "https://my.webhook.url.com/new/path"});

Deleting a webhook

import{Webhooks}from"shopify-admin-api";constservice=newWebhooks(shopDomain,shopAccessToken);awaitservice.delete(webhookId);

Counting webhooks

import{Webhooks}from"shopify-admin-api";constservice=newWebhooks(shopDomain,shopAccessToken);constcount=awaitservice.count();

Listing webhooks

import{Webhooks}from"shopify-admin-api";constservice=newWebhooks(shopDomain,shopAccessToken);constwebhooks=awaitservice.list();

Script Tags

Script tags let you add remote javascript tags that are loaded into the pages of a shop's storefront, letting you dynamically change the functionality of their shop without manually editing their store's template.

Creating a script tag

import{ScriptTags}from"shopify-admin-api";constservice=newScriptTags(shopDomain,shopAccessToken);lettag={event: "onload",src: "https://example.com/my-javascript-file.js",display_scope: "all"}tag=awaitservice.create(tag);

Retrieving a script tag

import{ScriptTags}from"shopify-admin-api";constservice=newScriptTags(shopDomain,shopAccessToken);consttag=awaitservice.get(tagId);

Updating a script tag

import{ScriptTags}from"shopify-admin-api";constservice=newScriptTags(shopDomain,shopAccessToken);lettag=awaitservice.get(tagId);tag=awaitservice.update(tag.id,{src: "https://example.com/my-new-javascript-file.js"});

Deleting a script tag

import{ScriptTags}from"shopify-admin-api";constservice=newScriptTags(shopDomain,shopAccessToken);awaitservice.delete(tagId);

Counting script tags

import{ScriptTags}from"shopify-admin-api";constservice=newScriptTags(shopDomain,shopAccessToken);letcount=awaitservice.count();//Optionally filter the count to only those tags with a specific Srccount=awaitservice.count({src: "https://example.com/my-filtered-url.js"});

Listing script tags

import{ScriptTags,ScriptTag}from"shopify-admin-api";constservice=newScriptTags(shopDomain,shopAccessToken);lettags=awaitservice.list();//Optionally filter the list to only those tags with a specific Srctags=awaitservice.list({src: "https://example.com/my-filtered-url.js"});

Customers

The Customer resource stores information about a shop's customers, such as their contact details, their order history, and whether they've agreed to receive email marketing.

Listing Customers

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);letcustomers=awaitservice.list();// Optionally, filter the list for new customersletcustomers=awaitservice.list({limit: 10,since_id: customerId});

Searching Customers

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);letsearch=awaitservice.search({query: 'Bob country:United States'});

Getting count of Customers

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);letcount=awaitservice.count();

Creating a Customer

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);letcustomer=awaitservice.create({email: "customer@myshopify.com",first_name: "Jane",last_name: "Doe"});

Updating a Customer

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);letcustomer=awaitservice.update({email: "newemail@myshopify.com"});

Deleting a Customer

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);letcustomer=awaitservice.delete(123456789);

Generating activation URL

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);leturl=awaitservice.createActivationUrl(123456789);// => https://domain.myshopify.comcom/account/activate/XXXXXX/XXXXXXXXXXXXX

Inviting a Customer

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);constinvite=awaitservice.invite();// Optionally, send a custom inviteconstinvite=awaitservice.invite({to: "alternateemail@gmail.com",from: "fromemail@myshopify.com",subject: "Welcome!",custom_message: "My custom message"});

Orders

Creating an Order

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);constorder=awaitservice.create({billing_address: {address1: "123 4th Street",city: "Minneapolis",province: "Minnesota",province_code: "MN",zip: "55401",phone: "555-555-5555",first_name: "John",last_name: "Doe",company: "Tomorrow Corporation",country: "United States",country_code: "US",default: true,},line_items: [{name: "Test Line Item",title: "Test Line Item Title",quantity: 2,price: 5},{name: "Test Line Item 2",title: "Test Line Item Title 2",quantity: 2,price: 5}],financial_status: "paid",total_price: 5.00,email: Date.now()+"@gmail.com",note: "Test note about the customer.",});

Getting an Order

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);constorder=awaitservice.get(id);

Updating an Order

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);letorder=awaitservice.get(id);order.note="Updated note";order=awaitservice.update(id,order);

Listing Orders

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);constorders=awaitservice.list();

Counting Orders

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);constorderCount=awaitservice.count();

Deleting an Order

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);awaitservice.delete(id);

Closing an Order

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);constorder=awaitservice.close(id);

Opening an Order

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);constorder=awaitservice.open(id);

Canceling an Order

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);awaitservice.cancel(id,{reason: "customer"});

Application Credits

Shopify's Application Credit API lets you offer credits for payments your app customers have made via the Application Charge, Recurring Application Charge, and Usage Charge APIs.

The total amount of all Application Credits created by an application must not exceed:

  1. Total amount paid to the application by the shop owner in the last 30 days.
  2. Total amount of pending receivables in the partner account associated with the application.

Additionally, Application Credits cannot be used by private applications.

Creating an Application Credit

import{ApplicationCredits}from"shopify-admin-api";constservice=newApplicationCredits(shopDomain,shopAccessToken);constcredit=awaitservice.create({description: "Refund for Foo",amount: 10.00});

Getting an Application Credit

import{ApplicationCredits}from"shopify-admin-api";constservice=newApplicationCredits(shopDomain,shopAccessToken);constcredit=awaitservice.get(id);

Listing Application Credits

import{ApplicationCredits}from"shopify-admin-api";constservice=newApplicationCredits(shopDomain,shopAccessToken);constcredits=awaitservice.list();

Blogs

In addition to an online storefront, Shopify shops come with a built-in blogging engine, allowing a shop to have one or more blogs. This class is for interacting with blogs themselves, not blog posts.

Creating a Blog

import{Blogs}from"shopify-admin-api";constservice=newBlogs(shopDomain,shopAccessToken)constblog=awaitservice.create({title: "My new blog",})

Getting a Blog

import{Blogs}from"shopify-admin-api";constservice=newBlogs(shopDomain,shopAccessToken)constblog=awaitservice.get(blogId);

Updating a Blog

import{Blogs}from"shopify-admin-api";constservice=newBlogs(shopDomain,shopAccessToken)constblog=awaitservice.update(blogId,{title: "My updated blog title"})

Listing Blogs

import{Blogs}from"shopify-admin-api";constservice=newBlogs(shopDomain,shopAccessToken)constblogs=awaitservice.list();

Counting Blogs

import{Blogs}from"shopify-admin-api";constservice=newBlogs(shopDomain,shopAccessToken)constcount=awaitservice.count();

Deleting a Blog

import{Blogs}from"shopify-admin-api";constservice=newBlogs(shopDomain,shopAccessToken)awaitservice.delete(blogId);

Articles

Articles are objects representing a blog post. Each article belongs to a Blog.

Creating an Article

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);constarticle=awaitservice.create(blogId,{title: "My new Article title",author: "John Smith",tags: "This Post, Has Been Tagged",body_html: "<h1>Hello world!</h1>",image: {attachment: "R0lGODlhAQABAIAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==\n"}})

Getting an Article

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);constarticle=awaitservice.get(blogId,articleId);

Updating an Article

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);constarticle=awaitservice.update(blogId,articleId,{title: "My updated title"})

Listing Articles

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);constarticles=awaitservice.list(blogId);

Counting Articles

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);constcount=awaitservice.count(blogId);

Deleting an Article

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);awaitservice.delete(blogId,articleId);

Listing all Article authors

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);constauthors=awaitservice.listAuthors();console.log(authors);// ['John Doe', 'Jane Doe']

Listing all Article tags

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);consttags=awaitservice.listTags();console.log(tags);// ['Tag One', 'Tag Two']

Listing all Article tags for a blog

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);consttags=awaitservice.listTagsForBlog(blogId);console.log(tags);// ['Tag One', 'Tag Two']

About

Shopify Admin API is a NodeJS library built to help developers easily authenticate and make calls against the Shopify Admin API. It is forked from the deprecated Shopify-Prime library.

Topics

Resources

Stars

11 stars

Watchers

3 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Repository files navigation

Shopify Admin API

Shopify Admin API for Node.js is a promise-driven NodeJS library built to help developers easily authenticate and make calls against the Shopify API. It is forked from the deprecated Shopify-Prime library.

Shopify Admin API is complete with full TypeScript definitions for all classes, interfaces and functions, and provides many quality of life improvements over most other Node Shopify libs. Tired of using undocumented libs that haven't been updated in ages, expect you to know all of the URL paths, and are little more than a basic wrapper over Node's http library? Give Shopify Admin API a try!

Installation

Shopify Admin API can be installed from NPM:

npm install shopify-admin-api --save

After installation, import Shopify Admin API via Node's require or ES6 import syntax:

//via requireconstShopify=require("shopify-admin-api");//via ES6import*asShopifyfrom"shopify-admin-api";

Tests

To run the tests on your locale machine you need a Shopify test shop in which you have created a private app, then you have to copy the credentials of the private app in the .env file in this project root directory. You can use the .env-example as a template:

cp .env-example .env
editor-of-your-choice .env

Now the test can be started:

yarn run build
yarn run test

Typescript declarations

Using TypeScript? The TypeScript compiler will automatically pull in Shopify Admin API definitions for you when you install Shopify Admin API, as long as you're using TypeScript 2+. Interfaces and extra types are available under the Interfaces, Enums and Options exports from the main "shopify-admin-api" module.

import{Shops}from"shopify-admin-api";// Typescript interfaces — not real JS objects:import{Interfaces,Enums,Options}from"shopify-admin-api";constshop: InterfacesShop=awaitnewShops(shopDomain,shopAccessToken).get(shopId);

Finally, because Shopify Admin API uses async/await and promises, you'll need to set your tsconfig.json's target to "es6". While not strictly necessary, Typescript won't know about the Promise type and will default all services' return types to any if you don't set your target to es6.

Async/await and promises

All Shopify Admin API functions are implemented as async/awaitable promises. You'll need Node.js v4 and above to use Shopify Admin API, as Node v3 and below don't support the generators needed for async/await.

Because async/await implements a promise-like interface in ES6, you can use the functions in this library in two different ways:

With async/await:

//1. async/awaitconstshop=awaitshops.get();//Do something with the shop

With promises:

constshop=shops.get().then((shop)=>{//Do something with the shop.});

Both methods are supported and the results won't differ. The only difference is an awaited method will throw an error if the method fails, where a promise would just fail silently unless you use .catch.

For the sake of being concise, all examples in this doc will use async/await.

A work-in-progress

This library is still pretty new. It currently suppports the following Shopify APIs:

More functionality will be added each week until it reachs full parity with Shopify's REST API.

Using Shopify Admin API with a public Shopify app

Note: All instances of shopAccessToken in the examples below do not refer to your Shopify API key. An access token is the token returned after authenticating and authorizing a Shopify app installation with a real Shopify store.

All instances of shopDomain refer to your users' *.myshopify.com URL (although their custom domain should work too).

import{Charges}from"shopify-admin-api";constchargeService=newCharges(shopDomain,shopAccessToken);

Using Shopify Admin API with a private Shopify app

Shopify Admin API should work out of the box with your private Shopify application, all you need to do is replace the shopAccessToken with your private app's password when initializing a service:

import{Orders}from"shopify-admin-api";constorderService=newOrders(shopDomain,privateAppPassword)

If you just need an access token for a private Shopify app, or for running the tests in this library, refer to the Tests section above.

Authorization and authentication

Ensure a given URL is a valid Shopify URL

This is a convenience method that validates whether a given URL is a valid Shopify shop. It's great for ensuring you don't redirect a user to an incorrect URL when you need them to authorize your app installation, and is ideally used in conjuction with .buildAuthorizationUrl.

Shopify Admin API will call the given URL and check for an X-ShopId header in the response. That header is present on all Shopify shops and its existence signals that the URL is indeed a Shopify URL.

Note, however, that this feature is undocumented by Shopify and may break at any time. Use at your own discretion.

import{Auth}from"shopify-admin-api";consturlFromUser="https://example.myshopify.com";constisValidUrl=awaitAuth.isValidMyShopifyDomain(urlFromUser).

Build an authorization URL

Redirect your users to this authorization URL, where they'll be prompted to install your app to their Shopify store.

import{Auth}from"shopify-admin-api";//This is the user's store URL.constusersShopifyUrl="https://example.myshopify.com";//An optional URL to redirect the user to after they've confirmed app installation.//If you don't specify a redirect url, Shopify will redirect to your app's default URL.constredirectUrl="https://example.com/my/redirect/url";//An array of the Shopify access scopes your application needs to run.constscopes=["read_orders","write_orders"];//Build the URL and send your user to it where they'll be prompted to install your app.constauthUrl=awaitAuth.buildAuthorizationUrl(scopes,usersShopifyUrl,yourShopifyApiKey,redirectUrl);

Authorize an installation and generate an access token

Once you've sent a user to the authorization URL and they've confirmed your app installation, they'll be redirected back to your application at either the default app URL, or the redirect URL you passed in when building the authorization URL.

The access token you receive after authorizing should be stored in your database. You'll need it to access the shop's resources (e.g. orders, customers, fulfillments, etc.)

import{Auth}from"shopify-admin-api";// The querystring will have several parameters you need for authorization.// Refer to your server framework docs for details on getting a request querystring.constcode=request.QueryString["code"];constshopUrl=request.QueryString["shop"];constaccessToken=awaitAuth.authorize(code,shopUrl,shopifyApiKey,shopifySecretKey)

Determine if a request is authentic

Any (non-webhook, non-proxy-page) request coming from Shopify will have a querystring paramater called 'hmac' that you can use to verify that the request is authentic. This hmac value is a hash of all querystring parameters and your app's secret key.

Pass the entire querystring to .isAuthenticRequest to verify the request.

import{Auth}from"shopify-admin-api";constqs=request.QueryString;constisAuthentic=awaitAuth.isAuthenticRequest(qs,shopifySecretKey);if(isAuthentic){//Request is authentic.}else{//Request is not authentic and should not be acted on.}

Determine if a proxy page request is authentic

Nearly identical to authenticating normal requests, a proxy page request only differs in the way the querystring is formatted to calculate the hmac signature. All proxy page requests coming from Shopify will have a querystring parameter named signature that you can use to verify the request. This signature is a hash of all querystring parameters and your app's secret key.

import{Auth}from"shopify-admin-api";constqs=request.QueryString;constisAuthentic=awaitAuth.isAuthenticProxyRequest(qs,shopifySecretKey);if(isAuthentic){//Request is authentic.}else{//Request is not authentic and should not be acted on.}

Determine if a webhook request is authentic

Any webhook request coming from Shopify will have a header called 'X-Shopify-Hmac-SHA256' that you can use to verify that the webhook is authentic. The header is a hash of the entire request body and your app's secret key.

Pass that header and the request body string to .isAuthenticWebhook to verify the request.

import{Auth}from"shopify-admin-api";consthmacHeader=request.QueryString["X-Shopify-Hmac-SHA256"];constbody=request.body.toString();constisAuthentic=awaitAuth.isAuthenticWebhook(hmacHeader,body,shopifySecretKey);if(isAuthentic){//Webhook is authentic.}else{//Webhook is not authentic and should not be acted on.}

You can also pass in the request body as a string, rather than using the input stream. However, the request body string needs to be identical to the way it was sent from Shopify. If it has been modified, the verification will fail.

Recurring Application Charges (monthly subscriptions)

The Shopify billing API lets you create a recurring charge on a shop owner's account, letting them pay you on a monthly basis for using your application.

Create a recurring charge

import{RecurringCharges}from"shopify-admin-api";constservice=newRecurringCharges(shopDomain,shopAccessToken);letcharge={
Name ="Lorem Ipsum Plan",
Price =12.34,
Test =true,//Marks this charge as a test, meaning it won't charge the shop owner.
TrialDays =21//Don't charge the user for 21 days}charge=awaitservice.create(charge);

Retrieve a recurring charge

import{RecurringCharges}from"shopify-admin-api";constservice=newRecurringCharges(shopDomain,shopAccessToken);constcharge=awaitservice.get(chargeId);

Listing recurring charges

import{RecurringCharges}from"shopify-admin-api";constservice=newRecurringCharges(shopDomain,shopAccessToken);constlist=awaitservice.list();

Activating a charge

Creating a charge does not actually charge the shop owner or even start their free trial. You need to send them to the charge's confirmation_url, have them accept the charge, then activate it.

import{RecurringCharges}from"shopify-admin-api";constservice=newRecurringCharges(shopDomain,shopAccessToken);awaitservice.activate(chargeId);

Deleting a charge

Charges cannot be deleted unless they've been activated. Shopify automatically deletes pending charges after 48 hours pass without activation.

import{RecurringCharges}from"shopify-admin-api";constservice=newRecurringCharges(shopDomain,shopAccessToken);awaitservice.delete(chargeId);

One-time application charges

Just like with the above recurring charges, the Shopify billing API lets you create a one-time application charge on the shop owner's account. One-time charges cannot be deleted.

Create a one-time charge

import{Charges}from"shopify-admin-api";constservice=newCharges(shopDomain,shopAccessToken);letcharge={
Name ="Lorem Ipsum Charge",
Price =12.34,
Test =true,//Marks this charge as a test, meaning it won't charge the shop owner.}charge=awaitservice.create(charge);

Retrieve a one-time charge

import{Charges}from"shopify-admin-api";constservice=newCharges(shopDomain,shopAccessToken);constcharge=awaitservice.get(chargeId);

Listing one-time charges

import{Charges}from"shopify-admin-api";constservice=newCharges(shopDomain,shopAccessToken);constlist=service.list();

Activating a charge

Just like recurring charges, creating a one-time charge does not actually charge the shop owner. You need to send them to the charge's ConfirmationUrl, have them accept the charge, then activate it.

import{Charges}from"shopify-admin-api";constservice=newCharges(shopDomain,shopAccessToken);awaitservice.activate(chargeId);

Usage charges

Shopify's Usage Charges let you set a capped amount on a recurring application charge, and only charge for usage. For example, you can create a charge that's capped at $100.00 per month, and then charge e.g. $1.00 for every 1000 emails your user sends using your app.

To create a usage charge, you first need to create a recurring charge with a capped_amount value and a terms string. Your customers will see the terms when activating the recurring charge, so set it to something they can read like "$1.00 per 1000 emails".

Creating a usage charge

import{UsageCharges}from"shopify-admin-api";constservice=newUsageCharges(shopDomain,shopAccessToken);constcharge=awaitservice.create(recurringChargeId,{description: "Used 1000 emails",price: 1.00});

Getting a usage charge

import{UsageCharges}from"shopify-admin-api";constservice=newUsageCharges(shopDomain,shopAccessToken);constcharge=awaitservice.get(recurringChargeId,usageChargeId);

Listing usage charges

import{UsageCharges}from"shopify-admin-api";constservice=newUsageCharges(shopDomain,shopAccessToken);constlist=awaitservice.list(recurringChargeId);

Shops

Retrieving shop information

import{Shops}from"shopify-admin-api";constservice=newShops(shopDomain,shopAccessToken);constshop=awaitservice.get();

Uninstalling your app

In cases where user intervention is not required, you can send a request to a Shopify shop to force it to uninstall your application. After sending this request, the shop access token will be immediately revoked and invalidated.

Uninstalling an application is an irreversible operation. Be entirely sure that you no longer need to make API calls for the shop in which the application has been installed.

Uninstalling an application also performs various cleanup tasks within Shopify. Registered Webhooks, ScriptTags and App Links will be destroyed as part of this operation. Also if an application is uninstalled during key rotation, both the old and new Access Tokens will be rendered useless.

import{Shops}from"shopify-admin-api";constservice=newShops(shopDomain,shopAccessToken);awaitshop.forceUninstallApp();

Webhooks

Creating a webhook

import{Webhooks}from"shopify-admin-api";constservice=newWebhooks(shopDomain,shopAccessToken);letwebhook={
address ="https://my.webhook.url.com/path",
topic ="themes/publish",};webhook=awaitservice.create(webhook);

Retrieving a webhook

import{Webhooks}from"shopify-admin-api";constservice=newWebhooks(shopDomain,shopAccessToken);constwebhook=awaitservice.get(webhookId);

Updating a webhook

import{Webhooks}from"shopify-admin-api";constservice=newWebhooks(shopDomain,shopAccessToken);constwebhook=awaitservice.update(webhookId,{address: "https://my.webhook.url.com/new/path"});

Deleting a webhook

import{Webhooks}from"shopify-admin-api";constservice=newWebhooks(shopDomain,shopAccessToken);awaitservice.delete(webhookId);

Counting webhooks

import{Webhooks}from"shopify-admin-api";constservice=newWebhooks(shopDomain,shopAccessToken);constcount=awaitservice.count();

Listing webhooks

import{Webhooks}from"shopify-admin-api";constservice=newWebhooks(shopDomain,shopAccessToken);constwebhooks=awaitservice.list();

Script Tags

Script tags let you add remote javascript tags that are loaded into the pages of a shop's storefront, letting you dynamically change the functionality of their shop without manually editing their store's template.

Creating a script tag

import{ScriptTags}from"shopify-admin-api";constservice=newScriptTags(shopDomain,shopAccessToken);lettag={event: "onload",src: "https://example.com/my-javascript-file.js",display_scope: "all"}tag=awaitservice.create(tag);

Retrieving a script tag

import{ScriptTags}from"shopify-admin-api";constservice=newScriptTags(shopDomain,shopAccessToken);consttag=awaitservice.get(tagId);

Updating a script tag

import{ScriptTags}from"shopify-admin-api";constservice=newScriptTags(shopDomain,shopAccessToken);lettag=awaitservice.get(tagId);tag=awaitservice.update(tag.id,{src: "https://example.com/my-new-javascript-file.js"});

Deleting a script tag

import{ScriptTags}from"shopify-admin-api";constservice=newScriptTags(shopDomain,shopAccessToken);awaitservice.delete(tagId);

Counting script tags

import{ScriptTags}from"shopify-admin-api";constservice=newScriptTags(shopDomain,shopAccessToken);letcount=awaitservice.count();//Optionally filter the count to only those tags with a specific Srccount=awaitservice.count({src: "https://example.com/my-filtered-url.js"});

Listing script tags

import{ScriptTags,ScriptTag}from"shopify-admin-api";constservice=newScriptTags(shopDomain,shopAccessToken);lettags=awaitservice.list();//Optionally filter the list to only those tags with a specific Srctags=awaitservice.list({src: "https://example.com/my-filtered-url.js"});

Customers

The Customer resource stores information about a shop's customers, such as their contact details, their order history, and whether they've agreed to receive email marketing.

Listing Customers

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);letcustomers=awaitservice.list();// Optionally, filter the list for new customersletcustomers=awaitservice.list({limit: 10,since_id: customerId});

Searching Customers

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);letsearch=awaitservice.search({query: 'Bob country:United States'});

Getting count of Customers

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);letcount=awaitservice.count();

Creating a Customer

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);letcustomer=awaitservice.create({email: "customer@myshopify.com",first_name: "Jane",last_name: "Doe"});

Updating a Customer

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);letcustomer=awaitservice.update({email: "newemail@myshopify.com"});

Deleting a Customer

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);letcustomer=awaitservice.delete(123456789);

Generating activation URL

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);leturl=awaitservice.createActivationUrl(123456789);// => https://domain.myshopify.comcom/account/activate/XXXXXX/XXXXXXXXXXXXX

Inviting a Customer

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);constinvite=awaitservice.invite();// Optionally, send a custom inviteconstinvite=awaitservice.invite({to: "alternateemail@gmail.com",from: "fromemail@myshopify.com",subject: "Welcome!",custom_message: "My custom message"});

Orders

Creating an Order

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);constorder=awaitservice.create({billing_address: {address1: "123 4th Street",city: "Minneapolis",province: "Minnesota",province_code: "MN",zip: "55401",phone: "555-555-5555",first_name: "John",last_name: "Doe",company: "Tomorrow Corporation",country: "United States",country_code: "US",default: true,},line_items: [{name: "Test Line Item",title: "Test Line Item Title",quantity: 2,price: 5},{name: "Test Line Item 2",title: "Test Line Item Title 2",quantity: 2,price: 5}],financial_status: "paid",total_price: 5.00,email: Date.now()+"@gmail.com",note: "Test note about the customer.",});

Getting an Order

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);constorder=awaitservice.get(id);

Updating an Order

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);letorder=awaitservice.get(id);order.note="Updated note";order=awaitservice.update(id,order);

Listing Orders

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);constorders=awaitservice.list();

Counting Orders

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);constorderCount=awaitservice.count();

Deleting an Order

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);awaitservice.delete(id);

Closing an Order

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);constorder=awaitservice.close(id);

Opening an Order

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);constorder=awaitservice.open(id);

Canceling an Order

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);awaitservice.cancel(id,{reason: "customer"});

Application Credits

Shopify's Application Credit API lets you offer credits for payments your app customers have made via the Application Charge, Recurring Application Charge, and Usage Charge APIs.

The total amount of all Application Credits created by an application must not exceed:

  1. Total amount paid to the application by the shop owner in the last 30 days.
  2. Total amount of pending receivables in the partner account associated with the application.

Additionally, Application Credits cannot be used by private applications.

Creating an Application Credit

import{ApplicationCredits}from"shopify-admin-api";constservice=newApplicationCredits(shopDomain,shopAccessToken);constcredit=awaitservice.create({description: "Refund for Foo",amount: 10.00});

Getting an Application Credit

import{ApplicationCredits}from"shopify-admin-api";constservice=newApplicationCredits(shopDomain,shopAccessToken);constcredit=awaitservice.get(id);

Listing Application Credits

import{ApplicationCredits}from"shopify-admin-api";constservice=newApplicationCredits(shopDomain,shopAccessToken);constcredits=awaitservice.list();

Blogs

In addition to an online storefront, Shopify shops come with a built-in blogging engine, allowing a shop to have one or more blogs. This class is for interacting with blogs themselves, not blog posts.

Creating a Blog

import{Blogs}from"shopify-admin-api";constservice=newBlogs(shopDomain,shopAccessToken)constblog=awaitservice.create({title: "My new blog",})

Getting a Blog

import{Blogs}from"shopify-admin-api";constservice=newBlogs(shopDomain,shopAccessToken)constblog=awaitservice.get(blogId);

Updating a Blog

import{Blogs}from"shopify-admin-api";constservice=newBlogs(shopDomain,shopAccessToken)constblog=awaitservice.update(blogId,{title: "My updated blog title"})

Listing Blogs

import{Blogs}from"shopify-admin-api";constservice=newBlogs(shopDomain,shopAccessToken)constblogs=awaitservice.list();

Counting Blogs

import{Blogs}from"shopify-admin-api";constservice=newBlogs(shopDomain,shopAccessToken)constcount=awaitservice.count();

Deleting a Blog

import{Blogs}from"shopify-admin-api";constservice=newBlogs(shopDomain,shopAccessToken)awaitservice.delete(blogId);

Articles

Articles are objects representing a blog post. Each article belongs to a Blog.

Creating an Article

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);constarticle=awaitservice.create(blogId,{title: "My new Article title",author: "John Smith",tags: "This Post, Has Been Tagged",body_html: "<h1>Hello world!</h1>",image: {attachment: "R0lGODlhAQABAIAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==\n"}})

Getting an Article

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);constarticle=awaitservice.get(blogId,articleId);

Updating an Article

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);constarticle=awaitservice.update(blogId,articleId,{title: "My updated title"})

Listing Articles

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);constarticles=awaitservice.list(blogId);

Counting Articles

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);constcount=awaitservice.count(blogId);

Deleting an Article

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);awaitservice.delete(blogId,articleId);

Listing all Article authors

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);constauthors=awaitservice.listAuthors();console.log(authors);// ['John Doe', 'Jane Doe']

Listing all Article tags

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);consttags=awaitservice.listTags();console.log(tags);// ['Tag One', 'Tag Two']

Listing all Article tags for a blog

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);consttags=awaitservice.listTagsForBlog(blogId);console.log(tags);// ['Tag One', 'Tag Two']

About

Shopify Admin API is a NodeJS library built to help developers easily authenticate and make calls against the Shopify Admin API. It is forked from the deprecated Shopify-Prime library.

Topics

Resources

Stars

11 stars

Watchers

3 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

Shopify Admin API

Shopify Admin API for Node.js is a promise-driven NodeJS library built to help developers easily authenticate and make calls against the Shopify API. It is forked from the deprecated Shopify-Prime library.

Shopify Admin API is complete with full TypeScript definitions for all classes, interfaces and functions, and provides many quality of life improvements over most other Node Shopify libs. Tired of using undocumented libs that haven't been updated in ages, expect you to know all of the URL paths, and are little more than a basic wrapper over Node's http library? Give Shopify Admin API a try!

Installation

Shopify Admin API can be installed from NPM:

npm install shopify-admin-api --save

After installation, import Shopify Admin API via Node's require or ES6 import syntax:

//via requireconstShopify=require("shopify-admin-api");//via ES6import*asShopifyfrom"shopify-admin-api";

Tests

To run the tests on your locale machine you need a Shopify test shop in which you have created a private app, then you have to copy the credentials of the private app in the .env file in this project root directory. You can use the .env-example as a template:

cp .env-example .env
editor-of-your-choice .env

Now the test can be started:

yarn run build
yarn run test

Typescript declarations

Using TypeScript? The TypeScript compiler will automatically pull in Shopify Admin API definitions for you when you install Shopify Admin API, as long as you're using TypeScript 2+. Interfaces and extra types are available under the Interfaces, Enums and Options exports from the main "shopify-admin-api" module.

import{Shops}from"shopify-admin-api";// Typescript interfaces — not real JS objects:import{Interfaces,Enums,Options}from"shopify-admin-api";constshop: InterfacesShop=awaitnewShops(shopDomain,shopAccessToken).get(shopId);

Finally, because Shopify Admin API uses async/await and promises, you'll need to set your tsconfig.json's target to "es6". While not strictly necessary, Typescript won't know about the Promise type and will default all services' return types to any if you don't set your target to es6.

Async/await and promises

All Shopify Admin API functions are implemented as async/awaitable promises. You'll need Node.js v4 and above to use Shopify Admin API, as Node v3 and below don't support the generators needed for async/await.

Because async/await implements a promise-like interface in ES6, you can use the functions in this library in two different ways:

With async/await:

//1. async/awaitconstshop=awaitshops.get();//Do something with the shop

With promises:

constshop=shops.get().then((shop)=>{//Do something with the shop.});

Both methods are supported and the results won't differ. The only difference is an awaited method will throw an error if the method fails, where a promise would just fail silently unless you use .catch.

For the sake of being concise, all examples in this doc will use async/await.

A work-in-progress

This library is still pretty new. It currently suppports the following Shopify APIs:

More functionality will be added each week until it reachs full parity with Shopify's REST API.

Using Shopify Admin API with a public Shopify app

Note: All instances of shopAccessToken in the examples below do not refer to your Shopify API key. An access token is the token returned after authenticating and authorizing a Shopify app installation with a real Shopify store.

All instances of shopDomain refer to your users' *.myshopify.com URL (although their custom domain should work too).

import{Charges}from"shopify-admin-api";constchargeService=newCharges(shopDomain,shopAccessToken);

Using Shopify Admin API with a private Shopify app

Shopify Admin API should work out of the box with your private Shopify application, all you need to do is replace the shopAccessToken with your private app's password when initializing a service:

import{Orders}from"shopify-admin-api";constorderService=newOrders(shopDomain,privateAppPassword)

If you just need an access token for a private Shopify app, or for running the tests in this library, refer to the Tests section above.

Authorization and authentication

Ensure a given URL is a valid Shopify URL

This is a convenience method that validates whether a given URL is a valid Shopify shop. It's great for ensuring you don't redirect a user to an incorrect URL when you need them to authorize your app installation, and is ideally used in conjuction with .buildAuthorizationUrl.

Shopify Admin API will call the given URL and check for an X-ShopId header in the response. That header is present on all Shopify shops and its existence signals that the URL is indeed a Shopify URL.

Note, however, that this feature is undocumented by Shopify and may break at any time. Use at your own discretion.

import{Auth}from"shopify-admin-api";consturlFromUser="https://example.myshopify.com";constisValidUrl=awaitAuth.isValidMyShopifyDomain(urlFromUser).

Build an authorization URL

Redirect your users to this authorization URL, where they'll be prompted to install your app to their Shopify store.

import{Auth}from"shopify-admin-api";//This is the user's store URL.constusersShopifyUrl="https://example.myshopify.com";//An optional URL to redirect the user to after they've confirmed app installation.//If you don't specify a redirect url, Shopify will redirect to your app's default URL.constredirectUrl="https://example.com/my/redirect/url";//An array of the Shopify access scopes your application needs to run.constscopes=["read_orders","write_orders"];//Build the URL and send your user to it where they'll be prompted to install your app.constauthUrl=awaitAuth.buildAuthorizationUrl(scopes,usersShopifyUrl,yourShopifyApiKey,redirectUrl);

Authorize an installation and generate an access token

Once you've sent a user to the authorization URL and they've confirmed your app installation, they'll be redirected back to your application at either the default app URL, or the redirect URL you passed in when building the authorization URL.

The access token you receive after authorizing should be stored in your database. You'll need it to access the shop's resources (e.g. orders, customers, fulfillments, etc.)

import{Auth}from"shopify-admin-api";// The querystring will have several parameters you need for authorization.// Refer to your server framework docs for details on getting a request querystring.constcode=request.QueryString["code"];constshopUrl=request.QueryString["shop"];constaccessToken=awaitAuth.authorize(code,shopUrl,shopifyApiKey,shopifySecretKey)

Determine if a request is authentic

Any (non-webhook, non-proxy-page) request coming from Shopify will have a querystring paramater called 'hmac' that you can use to verify that the request is authentic. This hmac value is a hash of all querystring parameters and your app's secret key.

Pass the entire querystring to .isAuthenticRequest to verify the request.

import{Auth}from"shopify-admin-api";constqs=request.QueryString;constisAuthentic=awaitAuth.isAuthenticRequest(qs,shopifySecretKey);if(isAuthentic){//Request is authentic.}else{//Request is not authentic and should not be acted on.}

Determine if a proxy page request is authentic

Nearly identical to authenticating normal requests, a proxy page request only differs in the way the querystring is formatted to calculate the hmac signature. All proxy page requests coming from Shopify will have a querystring parameter named signature that you can use to verify the request. This signature is a hash of all querystring parameters and your app's secret key.

import{Auth}from"shopify-admin-api";constqs=request.QueryString;constisAuthentic=awaitAuth.isAuthenticProxyRequest(qs,shopifySecretKey);if(isAuthentic){//Request is authentic.}else{//Request is not authentic and should not be acted on.}

Determine if a webhook request is authentic

Any webhook request coming from Shopify will have a header called 'X-Shopify-Hmac-SHA256' that you can use to verify that the webhook is authentic. The header is a hash of the entire request body and your app's secret key.

Pass that header and the request body string to .isAuthenticWebhook to verify the request.

import{Auth}from"shopify-admin-api";consthmacHeader=request.QueryString["X-Shopify-Hmac-SHA256"];constbody=request.body.toString();constisAuthentic=awaitAuth.isAuthenticWebhook(hmacHeader,body,shopifySecretKey);if(isAuthentic){//Webhook is authentic.}else{//Webhook is not authentic and should not be acted on.}

You can also pass in the request body as a string, rather than using the input stream. However, the request body string needs to be identical to the way it was sent from Shopify. If it has been modified, the verification will fail.

Recurring Application Charges (monthly subscriptions)

The Shopify billing API lets you create a recurring charge on a shop owner's account, letting them pay you on a monthly basis for using your application.

Create a recurring charge

import{RecurringCharges}from"shopify-admin-api";constservice=newRecurringCharges(shopDomain,shopAccessToken);letcharge={
Name ="Lorem Ipsum Plan",
Price =12.34,
Test =true,//Marks this charge as a test, meaning it won't charge the shop owner.
TrialDays =21//Don't charge the user for 21 days}charge=awaitservice.create(charge);

Retrieve a recurring charge

import{RecurringCharges}from"shopify-admin-api";constservice=newRecurringCharges(shopDomain,shopAccessToken);constcharge=awaitservice.get(chargeId);

Listing recurring charges

import{RecurringCharges}from"shopify-admin-api";constservice=newRecurringCharges(shopDomain,shopAccessToken);constlist=awaitservice.list();

Activating a charge

Creating a charge does not actually charge the shop owner or even start their free trial. You need to send them to the charge's confirmation_url, have them accept the charge, then activate it.

import{RecurringCharges}from"shopify-admin-api";constservice=newRecurringCharges(shopDomain,shopAccessToken);awaitservice.activate(chargeId);

Deleting a charge

Charges cannot be deleted unless they've been activated. Shopify automatically deletes pending charges after 48 hours pass without activation.

import{RecurringCharges}from"shopify-admin-api";constservice=newRecurringCharges(shopDomain,shopAccessToken);awaitservice.delete(chargeId);

One-time application charges

Just like with the above recurring charges, the Shopify billing API lets you create a one-time application charge on the shop owner's account. One-time charges cannot be deleted.

Create a one-time charge

import{Charges}from"shopify-admin-api";constservice=newCharges(shopDomain,shopAccessToken);letcharge={
Name ="Lorem Ipsum Charge",
Price =12.34,
Test =true,//Marks this charge as a test, meaning it won't charge the shop owner.}charge=awaitservice.create(charge);

Retrieve a one-time charge

import{Charges}from"shopify-admin-api";constservice=newCharges(shopDomain,shopAccessToken);constcharge=awaitservice.get(chargeId);

Listing one-time charges

import{Charges}from"shopify-admin-api";constservice=newCharges(shopDomain,shopAccessToken);constlist=service.list();

Activating a charge

Just like recurring charges, creating a one-time charge does not actually charge the shop owner. You need to send them to the charge's ConfirmationUrl, have them accept the charge, then activate it.

import{Charges}from"shopify-admin-api";constservice=newCharges(shopDomain,shopAccessToken);awaitservice.activate(chargeId);

Usage charges

Shopify's Usage Charges let you set a capped amount on a recurring application charge, and only charge for usage. For example, you can create a charge that's capped at $100.00 per month, and then charge e.g. $1.00 for every 1000 emails your user sends using your app.

To create a usage charge, you first need to create a recurring charge with a capped_amount value and a terms string. Your customers will see the terms when activating the recurring charge, so set it to something they can read like "$1.00 per 1000 emails".

Creating a usage charge

import{UsageCharges}from"shopify-admin-api";constservice=newUsageCharges(shopDomain,shopAccessToken);constcharge=awaitservice.create(recurringChargeId,{description: "Used 1000 emails",price: 1.00});

Getting a usage charge

import{UsageCharges}from"shopify-admin-api";constservice=newUsageCharges(shopDomain,shopAccessToken);constcharge=awaitservice.get(recurringChargeId,usageChargeId);

Listing usage charges

import{UsageCharges}from"shopify-admin-api";constservice=newUsageCharges(shopDomain,shopAccessToken);constlist=awaitservice.list(recurringChargeId);

Shops

Retrieving shop information

import{Shops}from"shopify-admin-api";constservice=newShops(shopDomain,shopAccessToken);constshop=awaitservice.get();

Uninstalling your app

In cases where user intervention is not required, you can send a request to a Shopify shop to force it to uninstall your application. After sending this request, the shop access token will be immediately revoked and invalidated.

Uninstalling an application is an irreversible operation. Be entirely sure that you no longer need to make API calls for the shop in which the application has been installed.

Uninstalling an application also performs various cleanup tasks within Shopify. Registered Webhooks, ScriptTags and App Links will be destroyed as part of this operation. Also if an application is uninstalled during key rotation, both the old and new Access Tokens will be rendered useless.

import{Shops}from"shopify-admin-api";constservice=newShops(shopDomain,shopAccessToken);awaitshop.forceUninstallApp();

Webhooks

Creating a webhook

import{Webhooks}from"shopify-admin-api";constservice=newWebhooks(shopDomain,shopAccessToken);letwebhook={
address ="https://my.webhook.url.com/path",
topic ="themes/publish",};webhook=awaitservice.create(webhook);

Retrieving a webhook

import{Webhooks}from"shopify-admin-api";constservice=newWebhooks(shopDomain,shopAccessToken);constwebhook=awaitservice.get(webhookId);

Updating a webhook

import{Webhooks}from"shopify-admin-api";constservice=newWebhooks(shopDomain,shopAccessToken);constwebhook=awaitservice.update(webhookId,{address: "https://my.webhook.url.com/new/path"});

Deleting a webhook

import{Webhooks}from"shopify-admin-api";constservice=newWebhooks(shopDomain,shopAccessToken);awaitservice.delete(webhookId);

Counting webhooks

import{Webhooks}from"shopify-admin-api";constservice=newWebhooks(shopDomain,shopAccessToken);constcount=awaitservice.count();

Listing webhooks

import{Webhooks}from"shopify-admin-api";constservice=newWebhooks(shopDomain,shopAccessToken);constwebhooks=awaitservice.list();

Script Tags

Script tags let you add remote javascript tags that are loaded into the pages of a shop's storefront, letting you dynamically change the functionality of their shop without manually editing their store's template.

Creating a script tag

import{ScriptTags}from"shopify-admin-api";constservice=newScriptTags(shopDomain,shopAccessToken);lettag={event: "onload",src: "https://example.com/my-javascript-file.js",display_scope: "all"}tag=awaitservice.create(tag);

Retrieving a script tag

import{ScriptTags}from"shopify-admin-api";constservice=newScriptTags(shopDomain,shopAccessToken);consttag=awaitservice.get(tagId);

Updating a script tag

import{ScriptTags}from"shopify-admin-api";constservice=newScriptTags(shopDomain,shopAccessToken);lettag=awaitservice.get(tagId);tag=awaitservice.update(tag.id,{src: "https://example.com/my-new-javascript-file.js"});

Deleting a script tag

import{ScriptTags}from"shopify-admin-api";constservice=newScriptTags(shopDomain,shopAccessToken);awaitservice.delete(tagId);

Counting script tags

import{ScriptTags}from"shopify-admin-api";constservice=newScriptTags(shopDomain,shopAccessToken);letcount=awaitservice.count();//Optionally filter the count to only those tags with a specific Srccount=awaitservice.count({src: "https://example.com/my-filtered-url.js"});

Listing script tags

import{ScriptTags,ScriptTag}from"shopify-admin-api";constservice=newScriptTags(shopDomain,shopAccessToken);lettags=awaitservice.list();//Optionally filter the list to only those tags with a specific Srctags=awaitservice.list({src: "https://example.com/my-filtered-url.js"});

Customers

The Customer resource stores information about a shop's customers, such as their contact details, their order history, and whether they've agreed to receive email marketing.

Listing Customers

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);letcustomers=awaitservice.list();// Optionally, filter the list for new customersletcustomers=awaitservice.list({limit: 10,since_id: customerId});

Searching Customers

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);letsearch=awaitservice.search({query: 'Bob country:United States'});

Getting count of Customers

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);letcount=awaitservice.count();

Creating a Customer

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);letcustomer=awaitservice.create({email: "customer@myshopify.com",first_name: "Jane",last_name: "Doe"});

Updating a Customer

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);letcustomer=awaitservice.update({email: "newemail@myshopify.com"});

Deleting a Customer

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);letcustomer=awaitservice.delete(123456789);

Generating activation URL

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);leturl=awaitservice.createActivationUrl(123456789);// => https://domain.myshopify.comcom/account/activate/XXXXXX/XXXXXXXXXXXXX

Inviting a Customer

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);constinvite=awaitservice.invite();// Optionally, send a custom inviteconstinvite=awaitservice.invite({to: "alternateemail@gmail.com",from: "fromemail@myshopify.com",subject: "Welcome!",custom_message: "My custom message"});

Orders

Creating an Order

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);constorder=awaitservice.create({billing_address: {address1: "123 4th Street",city: "Minneapolis",province: "Minnesota",province_code: "MN",zip: "55401",phone: "555-555-5555",first_name: "John",last_name: "Doe",company: "Tomorrow Corporation",country: "United States",country_code: "US",default: true,},line_items: [{name: "Test Line Item",title: "Test Line Item Title",quantity: 2,price: 5},{name: "Test Line Item 2",title: "Test Line Item Title 2",quantity: 2,price: 5}],financial_status: "paid",total_price: 5.00,email: Date.now()+"@gmail.com",note: "Test note about the customer.",});

Getting an Order

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);constorder=awaitservice.get(id);

Updating an Order

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);letorder=awaitservice.get(id);order.note="Updated note";order=awaitservice.update(id,order);

Listing Orders

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);constorders=awaitservice.list();

Counting Orders

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);constorderCount=awaitservice.count();

Deleting an Order

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);awaitservice.delete(id);

Closing an Order

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);constorder=awaitservice.close(id);

Opening an Order

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);constorder=awaitservice.open(id);

Canceling an Order

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);awaitservice.cancel(id,{reason: "customer"});

Application Credits

Shopify's Application Credit API lets you offer credits for payments your app customers have made via the Application Charge, Recurring Application Charge, and Usage Charge APIs.

The total amount of all Application Credits created by an application must not exceed:

  1. Total amount paid to the application by the shop owner in the last 30 days.
  2. Total amount of pending receivables in the partner account associated with the application.

Additionally, Application Credits cannot be used by private applications.

Creating an Application Credit

import{ApplicationCredits}from"shopify-admin-api";constservice=newApplicationCredits(shopDomain,shopAccessToken);constcredit=awaitservice.create({description: "Refund for Foo",amount: 10.00});

Getting an Application Credit

import{ApplicationCredits}from"shopify-admin-api";constservice=newApplicationCredits(shopDomain,shopAccessToken);constcredit=awaitservice.get(id);

Listing Application Credits

import{ApplicationCredits}from"shopify-admin-api";constservice=newApplicationCredits(shopDomain,shopAccessToken);constcredits=awaitservice.list();

Blogs

In addition to an online storefront, Shopify shops come with a built-in blogging engine, allowing a shop to have one or more blogs. This class is for interacting with blogs themselves, not blog posts.

Creating a Blog

import{Blogs}from"shopify-admin-api";constservice=newBlogs(shopDomain,shopAccessToken)constblog=awaitservice.create({title: "My new blog",})

Getting a Blog

import{Blogs}from"shopify-admin-api";constservice=newBlogs(shopDomain,shopAccessToken)constblog=awaitservice.get(blogId);

Updating a Blog

import{Blogs}from"shopify-admin-api";constservice=newBlogs(shopDomain,shopAccessToken)constblog=awaitservice.update(blogId,{title: "My updated blog title"})

Listing Blogs

import{Blogs}from"shopify-admin-api";constservice=newBlogs(shopDomain,shopAccessToken)constblogs=awaitservice.list();

Counting Blogs

import{Blogs}from"shopify-admin-api";constservice=newBlogs(shopDomain,shopAccessToken)constcount=awaitservice.count();

Deleting a Blog

import{Blogs}from"shopify-admin-api";constservice=newBlogs(shopDomain,shopAccessToken)awaitservice.delete(blogId);

Articles

Articles are objects representing a blog post. Each article belongs to a Blog.

Creating an Article

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);constarticle=awaitservice.create(blogId,{title: "My new Article title",author: "John Smith",tags: "This Post, Has Been Tagged",body_html: "<h1>Hello world!</h1>",image: {attachment: "R0lGODlhAQABAIAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==\n"}})

Getting an Article

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);constarticle=awaitservice.get(blogId,articleId);

Updating an Article

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);constarticle=awaitservice.update(blogId,articleId,{title: "My updated title"})

Listing Articles

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);constarticles=awaitservice.list(blogId);

Counting Articles

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);constcount=awaitservice.count(blogId);

Deleting an Article

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);awaitservice.delete(blogId,articleId);

Listing all Article authors

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);constauthors=awaitservice.listAuthors();console.log(authors);// ['John Doe', 'Jane Doe']

Listing all Article tags

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);consttags=awaitservice.listTags();console.log(tags);// ['Tag One', 'Tag Two']

Listing all Article tags for a blog

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);consttags=awaitservice.listTagsForBlog(blogId);console.log(tags);// ['Tag One', 'Tag Two']

About

Shopify Admin API is a NodeJS library built to help developers easily authenticate and make calls against the Shopify Admin API. It is forked from the deprecated Shopify-Prime library.

Topics

Resources

Stars

11 stars

Watchers

3 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

Shopify Admin API

Shopify Admin API for Node.js is a promise-driven NodeJS library built to help developers easily authenticate and make calls against the Shopify API. It is forked from the deprecated Shopify-Prime library.

Shopify Admin API is complete with full TypeScript definitions for all classes, interfaces and functions, and provides many quality of life improvements over most other Node Shopify libs. Tired of using undocumented libs that haven't been updated in ages, expect you to know all of the URL paths, and are little more than a basic wrapper over Node's http library? Give Shopify Admin API a try!

Installation

Shopify Admin API can be installed from NPM:

npm install shopify-admin-api --save

After installation, import Shopify Admin API via Node's require or ES6 import syntax:

//via requireconstShopify=require("shopify-admin-api");//via ES6import*asShopifyfrom"shopify-admin-api";

Tests

To run the tests on your locale machine you need a Shopify test shop in which you have created a private app, then you have to copy the credentials of the private app in the .env file in this project root directory. You can use the .env-example as a template:

cp .env-example .env
editor-of-your-choice .env

Now the test can be started:

yarn run build
yarn run test

Typescript declarations

Using TypeScript? The TypeScript compiler will automatically pull in Shopify Admin API definitions for you when you install Shopify Admin API, as long as you're using TypeScript 2+. Interfaces and extra types are available under the Interfaces, Enums and Options exports from the main "shopify-admin-api" module.

import{Shops}from"shopify-admin-api";// Typescript interfaces — not real JS objects:import{Interfaces,Enums,Options}from"shopify-admin-api";constshop: InterfacesShop=awaitnewShops(shopDomain,shopAccessToken).get(shopId);

Finally, because Shopify Admin API uses async/await and promises, you'll need to set your tsconfig.json's target to "es6". While not strictly necessary, Typescript won't know about the Promise type and will default all services' return types to any if you don't set your target to es6.

Async/await and promises

All Shopify Admin API functions are implemented as async/awaitable promises. You'll need Node.js v4 and above to use Shopify Admin API, as Node v3 and below don't support the generators needed for async/await.

Because async/await implements a promise-like interface in ES6, you can use the functions in this library in two different ways:

With async/await:

//1. async/awaitconstshop=awaitshops.get();//Do something with the shop

With promises:

constshop=shops.get().then((shop)=>{//Do something with the shop.});

Both methods are supported and the results won't differ. The only difference is an awaited method will throw an error if the method fails, where a promise would just fail silently unless you use .catch.

For the sake of being concise, all examples in this doc will use async/await.

A work-in-progress

This library is still pretty new. It currently suppports the following Shopify APIs:

More functionality will be added each week until it reachs full parity with Shopify's REST API.

Using Shopify Admin API with a public Shopify app

Note: All instances of shopAccessToken in the examples below do not refer to your Shopify API key. An access token is the token returned after authenticating and authorizing a Shopify app installation with a real Shopify store.

All instances of shopDomain refer to your users' *.myshopify.com URL (although their custom domain should work too).

import{Charges}from"shopify-admin-api";constchargeService=newCharges(shopDomain,shopAccessToken);

Using Shopify Admin API with a private Shopify app

Shopify Admin API should work out of the box with your private Shopify application, all you need to do is replace the shopAccessToken with your private app's password when initializing a service:

import{Orders}from"shopify-admin-api";constorderService=newOrders(shopDomain,privateAppPassword)

If you just need an access token for a private Shopify app, or for running the tests in this library, refer to the Tests section above.

Authorization and authentication

Ensure a given URL is a valid Shopify URL

This is a convenience method that validates whether a given URL is a valid Shopify shop. It's great for ensuring you don't redirect a user to an incorrect URL when you need them to authorize your app installation, and is ideally used in conjuction with .buildAuthorizationUrl.

Shopify Admin API will call the given URL and check for an X-ShopId header in the response. That header is present on all Shopify shops and its existence signals that the URL is indeed a Shopify URL.

Note, however, that this feature is undocumented by Shopify and may break at any time. Use at your own discretion.

import{Auth}from"shopify-admin-api";consturlFromUser="https://example.myshopify.com";constisValidUrl=awaitAuth.isValidMyShopifyDomain(urlFromUser).

Build an authorization URL

Redirect your users to this authorization URL, where they'll be prompted to install your app to their Shopify store.

import{Auth}from"shopify-admin-api";//This is the user's store URL.constusersShopifyUrl="https://example.myshopify.com";//An optional URL to redirect the user to after they've confirmed app installation.//If you don't specify a redirect url, Shopify will redirect to your app's default URL.constredirectUrl="https://example.com/my/redirect/url";//An array of the Shopify access scopes your application needs to run.constscopes=["read_orders","write_orders"];//Build the URL and send your user to it where they'll be prompted to install your app.constauthUrl=awaitAuth.buildAuthorizationUrl(scopes,usersShopifyUrl,yourShopifyApiKey,redirectUrl);

Authorize an installation and generate an access token

Once you've sent a user to the authorization URL and they've confirmed your app installation, they'll be redirected back to your application at either the default app URL, or the redirect URL you passed in when building the authorization URL.

The access token you receive after authorizing should be stored in your database. You'll need it to access the shop's resources (e.g. orders, customers, fulfillments, etc.)

import{Auth}from"shopify-admin-api";// The querystring will have several parameters you need for authorization.// Refer to your server framework docs for details on getting a request querystring.constcode=request.QueryString["code"];constshopUrl=request.QueryString["shop"];constaccessToken=awaitAuth.authorize(code,shopUrl,shopifyApiKey,shopifySecretKey)

Determine if a request is authentic

Any (non-webhook, non-proxy-page) request coming from Shopify will have a querystring paramater called 'hmac' that you can use to verify that the request is authentic. This hmac value is a hash of all querystring parameters and your app's secret key.

Pass the entire querystring to .isAuthenticRequest to verify the request.

import{Auth}from"shopify-admin-api";constqs=request.QueryString;constisAuthentic=awaitAuth.isAuthenticRequest(qs,shopifySecretKey);if(isAuthentic){//Request is authentic.}else{//Request is not authentic and should not be acted on.}

Determine if a proxy page request is authentic

Nearly identical to authenticating normal requests, a proxy page request only differs in the way the querystring is formatted to calculate the hmac signature. All proxy page requests coming from Shopify will have a querystring parameter named signature that you can use to verify the request. This signature is a hash of all querystring parameters and your app's secret key.

import{Auth}from"shopify-admin-api";constqs=request.QueryString;constisAuthentic=awaitAuth.isAuthenticProxyRequest(qs,shopifySecretKey);if(isAuthentic){//Request is authentic.}else{//Request is not authentic and should not be acted on.}

Determine if a webhook request is authentic

Any webhook request coming from Shopify will have a header called 'X-Shopify-Hmac-SHA256' that you can use to verify that the webhook is authentic. The header is a hash of the entire request body and your app's secret key.

Pass that header and the request body string to .isAuthenticWebhook to verify the request.

import{Auth}from"shopify-admin-api";consthmacHeader=request.QueryString["X-Shopify-Hmac-SHA256"];constbody=request.body.toString();constisAuthentic=awaitAuth.isAuthenticWebhook(hmacHeader,body,shopifySecretKey);if(isAuthentic){//Webhook is authentic.}else{//Webhook is not authentic and should not be acted on.}

You can also pass in the request body as a string, rather than using the input stream. However, the request body string needs to be identical to the way it was sent from Shopify. If it has been modified, the verification will fail.

Recurring Application Charges (monthly subscriptions)

The Shopify billing API lets you create a recurring charge on a shop owner's account, letting them pay you on a monthly basis for using your application.

Create a recurring charge

import{RecurringCharges}from"shopify-admin-api";constservice=newRecurringCharges(shopDomain,shopAccessToken);letcharge={
Name ="Lorem Ipsum Plan",
Price =12.34,
Test =true,//Marks this charge as a test, meaning it won't charge the shop owner.
TrialDays =21//Don't charge the user for 21 days}charge=awaitservice.create(charge);

Retrieve a recurring charge

import{RecurringCharges}from"shopify-admin-api";constservice=newRecurringCharges(shopDomain,shopAccessToken);constcharge=awaitservice.get(chargeId);

Listing recurring charges

import{RecurringCharges}from"shopify-admin-api";constservice=newRecurringCharges(shopDomain,shopAccessToken);constlist=awaitservice.list();

Activating a charge

Creating a charge does not actually charge the shop owner or even start their free trial. You need to send them to the charge's confirmation_url, have them accept the charge, then activate it.

import{RecurringCharges}from"shopify-admin-api";constservice=newRecurringCharges(shopDomain,shopAccessToken);awaitservice.activate(chargeId);

Deleting a charge

Charges cannot be deleted unless they've been activated. Shopify automatically deletes pending charges after 48 hours pass without activation.

import{RecurringCharges}from"shopify-admin-api";constservice=newRecurringCharges(shopDomain,shopAccessToken);awaitservice.delete(chargeId);

One-time application charges

Just like with the above recurring charges, the Shopify billing API lets you create a one-time application charge on the shop owner's account. One-time charges cannot be deleted.

Create a one-time charge

import{Charges}from"shopify-admin-api";constservice=newCharges(shopDomain,shopAccessToken);letcharge={
Name ="Lorem Ipsum Charge",
Price =12.34,
Test =true,//Marks this charge as a test, meaning it won't charge the shop owner.}charge=awaitservice.create(charge);

Retrieve a one-time charge

import{Charges}from"shopify-admin-api";constservice=newCharges(shopDomain,shopAccessToken);constcharge=awaitservice.get(chargeId);

Listing one-time charges

import{Charges}from"shopify-admin-api";constservice=newCharges(shopDomain,shopAccessToken);constlist=service.list();

Activating a charge

Just like recurring charges, creating a one-time charge does not actually charge the shop owner. You need to send them to the charge's ConfirmationUrl, have them accept the charge, then activate it.

import{Charges}from"shopify-admin-api";constservice=newCharges(shopDomain,shopAccessToken);awaitservice.activate(chargeId);

Usage charges

Shopify's Usage Charges let you set a capped amount on a recurring application charge, and only charge for usage. For example, you can create a charge that's capped at $100.00 per month, and then charge e.g. $1.00 for every 1000 emails your user sends using your app.

To create a usage charge, you first need to create a recurring charge with a capped_amount value and a terms string. Your customers will see the terms when activating the recurring charge, so set it to something they can read like "$1.00 per 1000 emails".

Creating a usage charge

import{UsageCharges}from"shopify-admin-api";constservice=newUsageCharges(shopDomain,shopAccessToken);constcharge=awaitservice.create(recurringChargeId,{description: "Used 1000 emails",price: 1.00});

Getting a usage charge

import{UsageCharges}from"shopify-admin-api";constservice=newUsageCharges(shopDomain,shopAccessToken);constcharge=awaitservice.get(recurringChargeId,usageChargeId);

Listing usage charges

import{UsageCharges}from"shopify-admin-api";constservice=newUsageCharges(shopDomain,shopAccessToken);constlist=awaitservice.list(recurringChargeId);

Shops

Retrieving shop information

import{Shops}from"shopify-admin-api";constservice=newShops(shopDomain,shopAccessToken);constshop=awaitservice.get();

Uninstalling your app

In cases where user intervention is not required, you can send a request to a Shopify shop to force it to uninstall your application. After sending this request, the shop access token will be immediately revoked and invalidated.

Uninstalling an application is an irreversible operation. Be entirely sure that you no longer need to make API calls for the shop in which the application has been installed.

Uninstalling an application also performs various cleanup tasks within Shopify. Registered Webhooks, ScriptTags and App Links will be destroyed as part of this operation. Also if an application is uninstalled during key rotation, both the old and new Access Tokens will be rendered useless.

import{Shops}from"shopify-admin-api";constservice=newShops(shopDomain,shopAccessToken);awaitshop.forceUninstallApp();

Webhooks

Creating a webhook

import{Webhooks}from"shopify-admin-api";constservice=newWebhooks(shopDomain,shopAccessToken);letwebhook={
address ="https://my.webhook.url.com/path",
topic ="themes/publish",};webhook=awaitservice.create(webhook);

Retrieving a webhook

import{Webhooks}from"shopify-admin-api";constservice=newWebhooks(shopDomain,shopAccessToken);constwebhook=awaitservice.get(webhookId);

Updating a webhook

import{Webhooks}from"shopify-admin-api";constservice=newWebhooks(shopDomain,shopAccessToken);constwebhook=awaitservice.update(webhookId,{address: "https://my.webhook.url.com/new/path"});

Deleting a webhook

import{Webhooks}from"shopify-admin-api";constservice=newWebhooks(shopDomain,shopAccessToken);awaitservice.delete(webhookId);

Counting webhooks

import{Webhooks}from"shopify-admin-api";constservice=newWebhooks(shopDomain,shopAccessToken);constcount=awaitservice.count();

Listing webhooks

import{Webhooks}from"shopify-admin-api";constservice=newWebhooks(shopDomain,shopAccessToken);constwebhooks=awaitservice.list();

Script Tags

Script tags let you add remote javascript tags that are loaded into the pages of a shop's storefront, letting you dynamically change the functionality of their shop without manually editing their store's template.

Creating a script tag

import{ScriptTags}from"shopify-admin-api";constservice=newScriptTags(shopDomain,shopAccessToken);lettag={event: "onload",src: "https://example.com/my-javascript-file.js",display_scope: "all"}tag=awaitservice.create(tag);

Retrieving a script tag

import{ScriptTags}from"shopify-admin-api";constservice=newScriptTags(shopDomain,shopAccessToken);consttag=awaitservice.get(tagId);

Updating a script tag

import{ScriptTags}from"shopify-admin-api";constservice=newScriptTags(shopDomain,shopAccessToken);lettag=awaitservice.get(tagId);tag=awaitservice.update(tag.id,{src: "https://example.com/my-new-javascript-file.js"});

Deleting a script tag

import{ScriptTags}from"shopify-admin-api";constservice=newScriptTags(shopDomain,shopAccessToken);awaitservice.delete(tagId);

Counting script tags

import{ScriptTags}from"shopify-admin-api";constservice=newScriptTags(shopDomain,shopAccessToken);letcount=awaitservice.count();//Optionally filter the count to only those tags with a specific Srccount=awaitservice.count({src: "https://example.com/my-filtered-url.js"});

Listing script tags

import{ScriptTags,ScriptTag}from"shopify-admin-api";constservice=newScriptTags(shopDomain,shopAccessToken);lettags=awaitservice.list();//Optionally filter the list to only those tags with a specific Srctags=awaitservice.list({src: "https://example.com/my-filtered-url.js"});

Customers

The Customer resource stores information about a shop's customers, such as their contact details, their order history, and whether they've agreed to receive email marketing.

Listing Customers

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);letcustomers=awaitservice.list();// Optionally, filter the list for new customersletcustomers=awaitservice.list({limit: 10,since_id: customerId});

Searching Customers

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);letsearch=awaitservice.search({query: 'Bob country:United States'});

Getting count of Customers

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);letcount=awaitservice.count();

Creating a Customer

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);letcustomer=awaitservice.create({email: "customer@myshopify.com",first_name: "Jane",last_name: "Doe"});

Updating a Customer

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);letcustomer=awaitservice.update({email: "newemail@myshopify.com"});

Deleting a Customer

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);letcustomer=awaitservice.delete(123456789);

Generating activation URL

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);leturl=awaitservice.createActivationUrl(123456789);// => https://domain.myshopify.comcom/account/activate/XXXXXX/XXXXXXXXXXXXX

Inviting a Customer

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);constinvite=awaitservice.invite();// Optionally, send a custom inviteconstinvite=awaitservice.invite({to: "alternateemail@gmail.com",from: "fromemail@myshopify.com",subject: "Welcome!",custom_message: "My custom message"});

Orders

Creating an Order

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);constorder=awaitservice.create({billing_address: {address1: "123 4th Street",city: "Minneapolis",province: "Minnesota",province_code: "MN",zip: "55401",phone: "555-555-5555",first_name: "John",last_name: "Doe",company: "Tomorrow Corporation",country: "United States",country_code: "US",default: true,},line_items: [{name: "Test Line Item",title: "Test Line Item Title",quantity: 2,price: 5},{name: "Test Line Item 2",title: "Test Line Item Title 2",quantity: 2,price: 5}],financial_status: "paid",total_price: 5.00,email: Date.now()+"@gmail.com",note: "Test note about the customer.",});

Getting an Order

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);constorder=awaitservice.get(id);

Updating an Order

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);letorder=awaitservice.get(id);order.note="Updated note";order=awaitservice.update(id,order);

Listing Orders

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);constorders=awaitservice.list();

Counting Orders

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);constorderCount=awaitservice.count();

Deleting an Order

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);awaitservice.delete(id);

Closing an Order

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);constorder=awaitservice.close(id);

Opening an Order

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);constorder=awaitservice.open(id);

Canceling an Order

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);awaitservice.cancel(id,{reason: "customer"});

Application Credits

Shopify's Application Credit API lets you offer credits for payments your app customers have made via the Application Charge, Recurring Application Charge, and Usage Charge APIs.

The total amount of all Application Credits created by an application must not exceed:

  1. Total amount paid to the application by the shop owner in the last 30 days.
  2. Total amount of pending receivables in the partner account associated with the application.

Additionally, Application Credits cannot be used by private applications.

Creating an Application Credit

import{ApplicationCredits}from"shopify-admin-api";constservice=newApplicationCredits(shopDomain,shopAccessToken);constcredit=awaitservice.create({description: "Refund for Foo",amount: 10.00});

Getting an Application Credit

import{ApplicationCredits}from"shopify-admin-api";constservice=newApplicationCredits(shopDomain,shopAccessToken);constcredit=awaitservice.get(id);

Listing Application Credits

import{ApplicationCredits}from"shopify-admin-api";constservice=newApplicationCredits(shopDomain,shopAccessToken);constcredits=awaitservice.list();

Blogs

In addition to an online storefront, Shopify shops come with a built-in blogging engine, allowing a shop to have one or more blogs. This class is for interacting with blogs themselves, not blog posts.

Creating a Blog

import{Blogs}from"shopify-admin-api";constservice=newBlogs(shopDomain,shopAccessToken)constblog=awaitservice.create({title: "My new blog",})

Getting a Blog

import{Blogs}from"shopify-admin-api";constservice=newBlogs(shopDomain,shopAccessToken)constblog=awaitservice.get(blogId);

Updating a Blog

import{Blogs}from"shopify-admin-api";constservice=newBlogs(shopDomain,shopAccessToken)constblog=awaitservice.update(blogId,{title: "My updated blog title"})

Listing Blogs

import{Blogs}from"shopify-admin-api";constservice=newBlogs(shopDomain,shopAccessToken)constblogs=awaitservice.list();

Counting Blogs

import{Blogs}from"shopify-admin-api";constservice=newBlogs(shopDomain,shopAccessToken)constcount=awaitservice.count();

Deleting a Blog

import{Blogs}from"shopify-admin-api";constservice=newBlogs(shopDomain,shopAccessToken)awaitservice.delete(blogId);

Articles

Articles are objects representing a blog post. Each article belongs to a Blog.

Creating an Article

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);constarticle=awaitservice.create(blogId,{title: "My new Article title",author: "John Smith",tags: "This Post, Has Been Tagged",body_html: "<h1>Hello world!</h1>",image: {attachment: "R0lGODlhAQABAIAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==\n"}})

Getting an Article

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);constarticle=awaitservice.get(blogId,articleId);

Updating an Article

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);constarticle=awaitservice.update(blogId,articleId,{title: "My updated title"})

Listing Articles

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);constarticles=awaitservice.list(blogId);

Counting Articles

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);constcount=awaitservice.count(blogId);

Deleting an Article

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);awaitservice.delete(blogId,articleId);

Listing all Article authors

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);constauthors=awaitservice.listAuthors();console.log(authors);// ['John Doe', 'Jane Doe']

Listing all Article tags

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);consttags=awaitservice.listTags();console.log(tags);// ['Tag One', 'Tag Two']

Listing all Article tags for a blog

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);consttags=awaitservice.listTagsForBlog(blogId);console.log(tags);// ['Tag One', 'Tag Two']

About

Shopify Admin API is a NodeJS library built to help developers easily authenticate and make calls against the Shopify Admin API. It is forked from the deprecated Shopify-Prime library.

Topics

Resources

Stars

11 stars

Watchers

3 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Repository files navigation

Shopify Admin API

Shopify Admin API for Node.js is a promise-driven NodeJS library built to help developers easily authenticate and make calls against the Shopify API. It is forked from the deprecated Shopify-Prime library.

Shopify Admin API is complete with full TypeScript definitions for all classes, interfaces and functions, and provides many quality of life improvements over most other Node Shopify libs. Tired of using undocumented libs that haven't been updated in ages, expect you to know all of the URL paths, and are little more than a basic wrapper over Node's http library? Give Shopify Admin API a try!

Installation

Shopify Admin API can be installed from NPM:

npm install shopify-admin-api --save

After installation, import Shopify Admin API via Node's require or ES6 import syntax:

//via requireconstShopify=require("shopify-admin-api");//via ES6import*asShopifyfrom"shopify-admin-api";

Tests

To run the tests on your locale machine you need a Shopify test shop in which you have created a private app, then you have to copy the credentials of the private app in the .env file in this project root directory. You can use the .env-example as a template:

cp .env-example .env
editor-of-your-choice .env

Now the test can be started:

yarn run build
yarn run test

Typescript declarations

Using TypeScript? The TypeScript compiler will automatically pull in Shopify Admin API definitions for you when you install Shopify Admin API, as long as you're using TypeScript 2+. Interfaces and extra types are available under the Interfaces, Enums and Options exports from the main "shopify-admin-api" module.

import{Shops}from"shopify-admin-api";// Typescript interfaces — not real JS objects:import{Interfaces,Enums,Options}from"shopify-admin-api";constshop: InterfacesShop=awaitnewShops(shopDomain,shopAccessToken).get(shopId);

Finally, because Shopify Admin API uses async/await and promises, you'll need to set your tsconfig.json's target to "es6". While not strictly necessary, Typescript won't know about the Promise type and will default all services' return types to any if you don't set your target to es6.

Async/await and promises

All Shopify Admin API functions are implemented as async/awaitable promises. You'll need Node.js v4 and above to use Shopify Admin API, as Node v3 and below don't support the generators needed for async/await.

Because async/await implements a promise-like interface in ES6, you can use the functions in this library in two different ways:

With async/await:

//1. async/awaitconstshop=awaitshops.get();//Do something with the shop

With promises:

constshop=shops.get().then((shop)=>{//Do something with the shop.});

Both methods are supported and the results won't differ. The only difference is an awaited method will throw an error if the method fails, where a promise would just fail silently unless you use .catch.

For the sake of being concise, all examples in this doc will use async/await.

A work-in-progress

This library is still pretty new. It currently suppports the following Shopify APIs:

More functionality will be added each week until it reachs full parity with Shopify's REST API.

Using Shopify Admin API with a public Shopify app

Note: All instances of shopAccessToken in the examples below do not refer to your Shopify API key. An access token is the token returned after authenticating and authorizing a Shopify app installation with a real Shopify store.

All instances of shopDomain refer to your users' *.myshopify.com URL (although their custom domain should work too).

import{Charges}from"shopify-admin-api";constchargeService=newCharges(shopDomain,shopAccessToken);

Using Shopify Admin API with a private Shopify app

Shopify Admin API should work out of the box with your private Shopify application, all you need to do is replace the shopAccessToken with your private app's password when initializing a service:

import{Orders}from"shopify-admin-api";constorderService=newOrders(shopDomain,privateAppPassword)

If you just need an access token for a private Shopify app, or for running the tests in this library, refer to the Tests section above.

Authorization and authentication

Ensure a given URL is a valid Shopify URL

This is a convenience method that validates whether a given URL is a valid Shopify shop. It's great for ensuring you don't redirect a user to an incorrect URL when you need them to authorize your app installation, and is ideally used in conjuction with .buildAuthorizationUrl.

Shopify Admin API will call the given URL and check for an X-ShopId header in the response. That header is present on all Shopify shops and its existence signals that the URL is indeed a Shopify URL.

Note, however, that this feature is undocumented by Shopify and may break at any time. Use at your own discretion.

import{Auth}from"shopify-admin-api";consturlFromUser="https://example.myshopify.com";constisValidUrl=awaitAuth.isValidMyShopifyDomain(urlFromUser).

Build an authorization URL

Redirect your users to this authorization URL, where they'll be prompted to install your app to their Shopify store.

import{Auth}from"shopify-admin-api";//This is the user's store URL.constusersShopifyUrl="https://example.myshopify.com";//An optional URL to redirect the user to after they've confirmed app installation.//If you don't specify a redirect url, Shopify will redirect to your app's default URL.constredirectUrl="https://example.com/my/redirect/url";//An array of the Shopify access scopes your application needs to run.constscopes=["read_orders","write_orders"];//Build the URL and send your user to it where they'll be prompted to install your app.constauthUrl=awaitAuth.buildAuthorizationUrl(scopes,usersShopifyUrl,yourShopifyApiKey,redirectUrl);

Authorize an installation and generate an access token

Once you've sent a user to the authorization URL and they've confirmed your app installation, they'll be redirected back to your application at either the default app URL, or the redirect URL you passed in when building the authorization URL.

The access token you receive after authorizing should be stored in your database. You'll need it to access the shop's resources (e.g. orders, customers, fulfillments, etc.)

import{Auth}from"shopify-admin-api";// The querystring will have several parameters you need for authorization.// Refer to your server framework docs for details on getting a request querystring.constcode=request.QueryString["code"];constshopUrl=request.QueryString["shop"];constaccessToken=awaitAuth.authorize(code,shopUrl,shopifyApiKey,shopifySecretKey)

Determine if a request is authentic

Any (non-webhook, non-proxy-page) request coming from Shopify will have a querystring paramater called 'hmac' that you can use to verify that the request is authentic. This hmac value is a hash of all querystring parameters and your app's secret key.

Pass the entire querystring to .isAuthenticRequest to verify the request.

import{Auth}from"shopify-admin-api";constqs=request.QueryString;constisAuthentic=awaitAuth.isAuthenticRequest(qs,shopifySecretKey);if(isAuthentic){//Request is authentic.}else{//Request is not authentic and should not be acted on.}

Determine if a proxy page request is authentic

Nearly identical to authenticating normal requests, a proxy page request only differs in the way the querystring is formatted to calculate the hmac signature. All proxy page requests coming from Shopify will have a querystring parameter named signature that you can use to verify the request. This signature is a hash of all querystring parameters and your app's secret key.

import{Auth}from"shopify-admin-api";constqs=request.QueryString;constisAuthentic=awaitAuth.isAuthenticProxyRequest(qs,shopifySecretKey);if(isAuthentic){//Request is authentic.}else{//Request is not authentic and should not be acted on.}

Determine if a webhook request is authentic

Any webhook request coming from Shopify will have a header called 'X-Shopify-Hmac-SHA256' that you can use to verify that the webhook is authentic. The header is a hash of the entire request body and your app's secret key.

Pass that header and the request body string to .isAuthenticWebhook to verify the request.

import{Auth}from"shopify-admin-api";consthmacHeader=request.QueryString["X-Shopify-Hmac-SHA256"];constbody=request.body.toString();constisAuthentic=awaitAuth.isAuthenticWebhook(hmacHeader,body,shopifySecretKey);if(isAuthentic){//Webhook is authentic.}else{//Webhook is not authentic and should not be acted on.}

You can also pass in the request body as a string, rather than using the input stream. However, the request body string needs to be identical to the way it was sent from Shopify. If it has been modified, the verification will fail.

Recurring Application Charges (monthly subscriptions)

The Shopify billing API lets you create a recurring charge on a shop owner's account, letting them pay you on a monthly basis for using your application.

Create a recurring charge

import{RecurringCharges}from"shopify-admin-api";constservice=newRecurringCharges(shopDomain,shopAccessToken);letcharge={
Name ="Lorem Ipsum Plan",
Price =12.34,
Test =true,//Marks this charge as a test, meaning it won't charge the shop owner.
TrialDays =21//Don't charge the user for 21 days}charge=awaitservice.create(charge);

Retrieve a recurring charge

import{RecurringCharges}from"shopify-admin-api";constservice=newRecurringCharges(shopDomain,shopAccessToken);constcharge=awaitservice.get(chargeId);

Listing recurring charges

import{RecurringCharges}from"shopify-admin-api";constservice=newRecurringCharges(shopDomain,shopAccessToken);constlist=awaitservice.list();

Activating a charge

Creating a charge does not actually charge the shop owner or even start their free trial. You need to send them to the charge's confirmation_url, have them accept the charge, then activate it.

import{RecurringCharges}from"shopify-admin-api";constservice=newRecurringCharges(shopDomain,shopAccessToken);awaitservice.activate(chargeId);

Deleting a charge

Charges cannot be deleted unless they've been activated. Shopify automatically deletes pending charges after 48 hours pass without activation.

import{RecurringCharges}from"shopify-admin-api";constservice=newRecurringCharges(shopDomain,shopAccessToken);awaitservice.delete(chargeId);

One-time application charges

Just like with the above recurring charges, the Shopify billing API lets you create a one-time application charge on the shop owner's account. One-time charges cannot be deleted.

Create a one-time charge

import{Charges}from"shopify-admin-api";constservice=newCharges(shopDomain,shopAccessToken);letcharge={
Name ="Lorem Ipsum Charge",
Price =12.34,
Test =true,//Marks this charge as a test, meaning it won't charge the shop owner.}charge=awaitservice.create(charge);

Retrieve a one-time charge

import{Charges}from"shopify-admin-api";constservice=newCharges(shopDomain,shopAccessToken);constcharge=awaitservice.get(chargeId);

Listing one-time charges

import{Charges}from"shopify-admin-api";constservice=newCharges(shopDomain,shopAccessToken);constlist=service.list();

Activating a charge

Just like recurring charges, creating a one-time charge does not actually charge the shop owner. You need to send them to the charge's ConfirmationUrl, have them accept the charge, then activate it.

import{Charges}from"shopify-admin-api";constservice=newCharges(shopDomain,shopAccessToken);awaitservice.activate(chargeId);

Usage charges

Shopify's Usage Charges let you set a capped amount on a recurring application charge, and only charge for usage. For example, you can create a charge that's capped at $100.00 per month, and then charge e.g. $1.00 for every 1000 emails your user sends using your app.

To create a usage charge, you first need to create a recurring charge with a capped_amount value and a terms string. Your customers will see the terms when activating the recurring charge, so set it to something they can read like "$1.00 per 1000 emails".

Creating a usage charge

import{UsageCharges}from"shopify-admin-api";constservice=newUsageCharges(shopDomain,shopAccessToken);constcharge=awaitservice.create(recurringChargeId,{description: "Used 1000 emails",price: 1.00});

Getting a usage charge

import{UsageCharges}from"shopify-admin-api";constservice=newUsageCharges(shopDomain,shopAccessToken);constcharge=awaitservice.get(recurringChargeId,usageChargeId);

Listing usage charges

import{UsageCharges}from"shopify-admin-api";constservice=newUsageCharges(shopDomain,shopAccessToken);constlist=awaitservice.list(recurringChargeId);

Shops

Retrieving shop information

import{Shops}from"shopify-admin-api";constservice=newShops(shopDomain,shopAccessToken);constshop=awaitservice.get();

Uninstalling your app

In cases where user intervention is not required, you can send a request to a Shopify shop to force it to uninstall your application. After sending this request, the shop access token will be immediately revoked and invalidated.

Uninstalling an application is an irreversible operation. Be entirely sure that you no longer need to make API calls for the shop in which the application has been installed.

Uninstalling an application also performs various cleanup tasks within Shopify. Registered Webhooks, ScriptTags and App Links will be destroyed as part of this operation. Also if an application is uninstalled during key rotation, both the old and new Access Tokens will be rendered useless.

import{Shops}from"shopify-admin-api";constservice=newShops(shopDomain,shopAccessToken);awaitshop.forceUninstallApp();

Webhooks

Creating a webhook

import{Webhooks}from"shopify-admin-api";constservice=newWebhooks(shopDomain,shopAccessToken);letwebhook={
address ="https://my.webhook.url.com/path",
topic ="themes/publish",};webhook=awaitservice.create(webhook);

Retrieving a webhook

import{Webhooks}from"shopify-admin-api";constservice=newWebhooks(shopDomain,shopAccessToken);constwebhook=awaitservice.get(webhookId);

Updating a webhook

import{Webhooks}from"shopify-admin-api";constservice=newWebhooks(shopDomain,shopAccessToken);constwebhook=awaitservice.update(webhookId,{address: "https://my.webhook.url.com/new/path"});

Deleting a webhook

import{Webhooks}from"shopify-admin-api";constservice=newWebhooks(shopDomain,shopAccessToken);awaitservice.delete(webhookId);

Counting webhooks

import{Webhooks}from"shopify-admin-api";constservice=newWebhooks(shopDomain,shopAccessToken);constcount=awaitservice.count();

Listing webhooks

import{Webhooks}from"shopify-admin-api";constservice=newWebhooks(shopDomain,shopAccessToken);constwebhooks=awaitservice.list();

Script Tags

Script tags let you add remote javascript tags that are loaded into the pages of a shop's storefront, letting you dynamically change the functionality of their shop without manually editing their store's template.

Creating a script tag

import{ScriptTags}from"shopify-admin-api";constservice=newScriptTags(shopDomain,shopAccessToken);lettag={event: "onload",src: "https://example.com/my-javascript-file.js",display_scope: "all"}tag=awaitservice.create(tag);

Retrieving a script tag

import{ScriptTags}from"shopify-admin-api";constservice=newScriptTags(shopDomain,shopAccessToken);consttag=awaitservice.get(tagId);

Updating a script tag

import{ScriptTags}from"shopify-admin-api";constservice=newScriptTags(shopDomain,shopAccessToken);lettag=awaitservice.get(tagId);tag=awaitservice.update(tag.id,{src: "https://example.com/my-new-javascript-file.js"});

Deleting a script tag

import{ScriptTags}from"shopify-admin-api";constservice=newScriptTags(shopDomain,shopAccessToken);awaitservice.delete(tagId);

Counting script tags

import{ScriptTags}from"shopify-admin-api";constservice=newScriptTags(shopDomain,shopAccessToken);letcount=awaitservice.count();//Optionally filter the count to only those tags with a specific Srccount=awaitservice.count({src: "https://example.com/my-filtered-url.js"});

Listing script tags

import{ScriptTags,ScriptTag}from"shopify-admin-api";constservice=newScriptTags(shopDomain,shopAccessToken);lettags=awaitservice.list();//Optionally filter the list to only those tags with a specific Srctags=awaitservice.list({src: "https://example.com/my-filtered-url.js"});

Customers

The Customer resource stores information about a shop's customers, such as their contact details, their order history, and whether they've agreed to receive email marketing.

Listing Customers

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);letcustomers=awaitservice.list();// Optionally, filter the list for new customersletcustomers=awaitservice.list({limit: 10,since_id: customerId});

Searching Customers

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);letsearch=awaitservice.search({query: 'Bob country:United States'});

Getting count of Customers

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);letcount=awaitservice.count();

Creating a Customer

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);letcustomer=awaitservice.create({email: "customer@myshopify.com",first_name: "Jane",last_name: "Doe"});

Updating a Customer

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);letcustomer=awaitservice.update({email: "newemail@myshopify.com"});

Deleting a Customer

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);letcustomer=awaitservice.delete(123456789);

Generating activation URL

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);leturl=awaitservice.createActivationUrl(123456789);// => https://domain.myshopify.comcom/account/activate/XXXXXX/XXXXXXXXXXXXX

Inviting a Customer

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);constinvite=awaitservice.invite();// Optionally, send a custom inviteconstinvite=awaitservice.invite({to: "alternateemail@gmail.com",from: "fromemail@myshopify.com",subject: "Welcome!",custom_message: "My custom message"});

Orders

Creating an Order

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);constorder=awaitservice.create({billing_address: {address1: "123 4th Street",city: "Minneapolis",province: "Minnesota",province_code: "MN",zip: "55401",phone: "555-555-5555",first_name: "John",last_name: "Doe",company: "Tomorrow Corporation",country: "United States",country_code: "US",default: true,},line_items: [{name: "Test Line Item",title: "Test Line Item Title",quantity: 2,price: 5},{name: "Test Line Item 2",title: "Test Line Item Title 2",quantity: 2,price: 5}],financial_status: "paid",total_price: 5.00,email: Date.now()+"@gmail.com",note: "Test note about the customer.",});

Getting an Order

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);constorder=awaitservice.get(id);

Updating an Order

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);letorder=awaitservice.get(id);order.note="Updated note";order=awaitservice.update(id,order);

Listing Orders

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);constorders=awaitservice.list();

Counting Orders

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);constorderCount=awaitservice.count();

Deleting an Order

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);awaitservice.delete(id);

Closing an Order

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);constorder=awaitservice.close(id);

Opening an Order

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);constorder=awaitservice.open(id);

Canceling an Order

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);awaitservice.cancel(id,{reason: "customer"});

Application Credits

Shopify's Application Credit API lets you offer credits for payments your app customers have made via the Application Charge, Recurring Application Charge, and Usage Charge APIs.

The total amount of all Application Credits created by an application must not exceed:

  1. Total amount paid to the application by the shop owner in the last 30 days.
  2. Total amount of pending receivables in the partner account associated with the application.

Additionally, Application Credits cannot be used by private applications.

Creating an Application Credit

import{ApplicationCredits}from"shopify-admin-api";constservice=newApplicationCredits(shopDomain,shopAccessToken);constcredit=awaitservice.create({description: "Refund for Foo",amount: 10.00});

Getting an Application Credit

import{ApplicationCredits}from"shopify-admin-api";constservice=newApplicationCredits(shopDomain,shopAccessToken);constcredit=awaitservice.get(id);

Listing Application Credits

import{ApplicationCredits}from"shopify-admin-api";constservice=newApplicationCredits(shopDomain,shopAccessToken);constcredits=awaitservice.list();

Blogs

In addition to an online storefront, Shopify shops come with a built-in blogging engine, allowing a shop to have one or more blogs. This class is for interacting with blogs themselves, not blog posts.

Creating a Blog

import{Blogs}from"shopify-admin-api";constservice=newBlogs(shopDomain,shopAccessToken)constblog=awaitservice.create({title: "My new blog",})

Getting a Blog

import{Blogs}from"shopify-admin-api";constservice=newBlogs(shopDomain,shopAccessToken)constblog=awaitservice.get(blogId);

Updating a Blog

import{Blogs}from"shopify-admin-api";constservice=newBlogs(shopDomain,shopAccessToken)constblog=awaitservice.update(blogId,{title: "My updated blog title"})

Listing Blogs

import{Blogs}from"shopify-admin-api";constservice=newBlogs(shopDomain,shopAccessToken)constblogs=awaitservice.list();

Counting Blogs

import{Blogs}from"shopify-admin-api";constservice=newBlogs(shopDomain,shopAccessToken)constcount=awaitservice.count();

Deleting a Blog

import{Blogs}from"shopify-admin-api";constservice=newBlogs(shopDomain,shopAccessToken)awaitservice.delete(blogId);

Articles

Articles are objects representing a blog post. Each article belongs to a Blog.

Creating an Article

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);constarticle=awaitservice.create(blogId,{title: "My new Article title",author: "John Smith",tags: "This Post, Has Been Tagged",body_html: "<h1>Hello world!</h1>",image: {attachment: "R0lGODlhAQABAIAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==\n"}})

Getting an Article

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);constarticle=awaitservice.get(blogId,articleId);

Updating an Article

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);constarticle=awaitservice.update(blogId,articleId,{title: "My updated title"})

Listing Articles

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);constarticles=awaitservice.list(blogId);

Counting Articles

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);constcount=awaitservice.count(blogId);

Deleting an Article

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);awaitservice.delete(blogId,articleId);

Listing all Article authors

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);constauthors=awaitservice.listAuthors();console.log(authors);// ['John Doe', 'Jane Doe']

Listing all Article tags

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);consttags=awaitservice.listTags();console.log(tags);// ['Tag One', 'Tag Two']

Listing all Article tags for a blog

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);consttags=awaitservice.listTagsForBlog(blogId);console.log(tags);// ['Tag One', 'Tag Two']

About

Shopify Admin API is a NodeJS library built to help developers easily authenticate and make calls against the Shopify Admin API. It is forked from the deprecated Shopify-Prime library.

Topics

Resources

Stars

11 stars

Watchers

3 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

Shopify Admin API

Shopify Admin API for Node.js is a promise-driven NodeJS library built to help developers easily authenticate and make calls against the Shopify API. It is forked from the deprecated Shopify-Prime library.

Shopify Admin API is complete with full TypeScript definitions for all classes, interfaces and functions, and provides many quality of life improvements over most other Node Shopify libs. Tired of using undocumented libs that haven't been updated in ages, expect you to know all of the URL paths, and are little more than a basic wrapper over Node's http library? Give Shopify Admin API a try!

Installation

Shopify Admin API can be installed from NPM:

npm install shopify-admin-api --save

After installation, import Shopify Admin API via Node's require or ES6 import syntax:

//via requireconstShopify=require("shopify-admin-api");//via ES6import*asShopifyfrom"shopify-admin-api";

Tests

To run the tests on your locale machine you need a Shopify test shop in which you have created a private app, then you have to copy the credentials of the private app in the .env file in this project root directory. You can use the .env-example as a template:

cp .env-example .env
editor-of-your-choice .env

Now the test can be started:

yarn run build
yarn run test

Typescript declarations

Using TypeScript? The TypeScript compiler will automatically pull in Shopify Admin API definitions for you when you install Shopify Admin API, as long as you're using TypeScript 2+. Interfaces and extra types are available under the Interfaces, Enums and Options exports from the main "shopify-admin-api" module.

import{Shops}from"shopify-admin-api";// Typescript interfaces — not real JS objects:import{Interfaces,Enums,Options}from"shopify-admin-api";constshop: InterfacesShop=awaitnewShops(shopDomain,shopAccessToken).get(shopId);

Finally, because Shopify Admin API uses async/await and promises, you'll need to set your tsconfig.json's target to "es6". While not strictly necessary, Typescript won't know about the Promise type and will default all services' return types to any if you don't set your target to es6.

Async/await and promises

All Shopify Admin API functions are implemented as async/awaitable promises. You'll need Node.js v4 and above to use Shopify Admin API, as Node v3 and below don't support the generators needed for async/await.

Because async/await implements a promise-like interface in ES6, you can use the functions in this library in two different ways:

With async/await:

//1. async/awaitconstshop=awaitshops.get();//Do something with the shop

With promises:

constshop=shops.get().then((shop)=>{//Do something with the shop.});

Both methods are supported and the results won't differ. The only difference is an awaited method will throw an error if the method fails, where a promise would just fail silently unless you use .catch.

For the sake of being concise, all examples in this doc will use async/await.

A work-in-progress

This library is still pretty new. It currently suppports the following Shopify APIs:

More functionality will be added each week until it reachs full parity with Shopify's REST API.

Using Shopify Admin API with a public Shopify app

Note: All instances of shopAccessToken in the examples below do not refer to your Shopify API key. An access token is the token returned after authenticating and authorizing a Shopify app installation with a real Shopify store.

All instances of shopDomain refer to your users' *.myshopify.com URL (although their custom domain should work too).

import{Charges}from"shopify-admin-api";constchargeService=newCharges(shopDomain,shopAccessToken);

Using Shopify Admin API with a private Shopify app

Shopify Admin API should work out of the box with your private Shopify application, all you need to do is replace the shopAccessToken with your private app's password when initializing a service:

import{Orders}from"shopify-admin-api";constorderService=newOrders(shopDomain,privateAppPassword)

If you just need an access token for a private Shopify app, or for running the tests in this library, refer to the Tests section above.

Authorization and authentication

Ensure a given URL is a valid Shopify URL

This is a convenience method that validates whether a given URL is a valid Shopify shop. It's great for ensuring you don't redirect a user to an incorrect URL when you need them to authorize your app installation, and is ideally used in conjuction with .buildAuthorizationUrl.

Shopify Admin API will call the given URL and check for an X-ShopId header in the response. That header is present on all Shopify shops and its existence signals that the URL is indeed a Shopify URL.

Note, however, that this feature is undocumented by Shopify and may break at any time. Use at your own discretion.

import{Auth}from"shopify-admin-api";consturlFromUser="https://example.myshopify.com";constisValidUrl=awaitAuth.isValidMyShopifyDomain(urlFromUser).

Build an authorization URL

Redirect your users to this authorization URL, where they'll be prompted to install your app to their Shopify store.

import{Auth}from"shopify-admin-api";//This is the user's store URL.constusersShopifyUrl="https://example.myshopify.com";//An optional URL to redirect the user to after they've confirmed app installation.//If you don't specify a redirect url, Shopify will redirect to your app's default URL.constredirectUrl="https://example.com/my/redirect/url";//An array of the Shopify access scopes your application needs to run.constscopes=["read_orders","write_orders"];//Build the URL and send your user to it where they'll be prompted to install your app.constauthUrl=awaitAuth.buildAuthorizationUrl(scopes,usersShopifyUrl,yourShopifyApiKey,redirectUrl);

Authorize an installation and generate an access token

Once you've sent a user to the authorization URL and they've confirmed your app installation, they'll be redirected back to your application at either the default app URL, or the redirect URL you passed in when building the authorization URL.

The access token you receive after authorizing should be stored in your database. You'll need it to access the shop's resources (e.g. orders, customers, fulfillments, etc.)

import{Auth}from"shopify-admin-api";// The querystring will have several parameters you need for authorization.// Refer to your server framework docs for details on getting a request querystring.constcode=request.QueryString["code"];constshopUrl=request.QueryString["shop"];constaccessToken=awaitAuth.authorize(code,shopUrl,shopifyApiKey,shopifySecretKey)

Determine if a request is authentic

Any (non-webhook, non-proxy-page) request coming from Shopify will have a querystring paramater called 'hmac' that you can use to verify that the request is authentic. This hmac value is a hash of all querystring parameters and your app's secret key.

Pass the entire querystring to .isAuthenticRequest to verify the request.

import{Auth}from"shopify-admin-api";constqs=request.QueryString;constisAuthentic=awaitAuth.isAuthenticRequest(qs,shopifySecretKey);if(isAuthentic){//Request is authentic.}else{//Request is not authentic and should not be acted on.}

Determine if a proxy page request is authentic

Nearly identical to authenticating normal requests, a proxy page request only differs in the way the querystring is formatted to calculate the hmac signature. All proxy page requests coming from Shopify will have a querystring parameter named signature that you can use to verify the request. This signature is a hash of all querystring parameters and your app's secret key.

import{Auth}from"shopify-admin-api";constqs=request.QueryString;constisAuthentic=awaitAuth.isAuthenticProxyRequest(qs,shopifySecretKey);if(isAuthentic){//Request is authentic.}else{//Request is not authentic and should not be acted on.}

Determine if a webhook request is authentic

Any webhook request coming from Shopify will have a header called 'X-Shopify-Hmac-SHA256' that you can use to verify that the webhook is authentic. The header is a hash of the entire request body and your app's secret key.

Pass that header and the request body string to .isAuthenticWebhook to verify the request.

import{Auth}from"shopify-admin-api";consthmacHeader=request.QueryString["X-Shopify-Hmac-SHA256"];constbody=request.body.toString();constisAuthentic=awaitAuth.isAuthenticWebhook(hmacHeader,body,shopifySecretKey);if(isAuthentic){//Webhook is authentic.}else{//Webhook is not authentic and should not be acted on.}

You can also pass in the request body as a string, rather than using the input stream. However, the request body string needs to be identical to the way it was sent from Shopify. If it has been modified, the verification will fail.

Recurring Application Charges (monthly subscriptions)

The Shopify billing API lets you create a recurring charge on a shop owner's account, letting them pay you on a monthly basis for using your application.

Create a recurring charge

import{RecurringCharges}from"shopify-admin-api";constservice=newRecurringCharges(shopDomain,shopAccessToken);letcharge={
Name ="Lorem Ipsum Plan",
Price =12.34,
Test =true,//Marks this charge as a test, meaning it won't charge the shop owner.
TrialDays =21//Don't charge the user for 21 days}charge=awaitservice.create(charge);

Retrieve a recurring charge

import{RecurringCharges}from"shopify-admin-api";constservice=newRecurringCharges(shopDomain,shopAccessToken);constcharge=awaitservice.get(chargeId);

Listing recurring charges

import{RecurringCharges}from"shopify-admin-api";constservice=newRecurringCharges(shopDomain,shopAccessToken);constlist=awaitservice.list();

Activating a charge

Creating a charge does not actually charge the shop owner or even start their free trial. You need to send them to the charge's confirmation_url, have them accept the charge, then activate it.

import{RecurringCharges}from"shopify-admin-api";constservice=newRecurringCharges(shopDomain,shopAccessToken);awaitservice.activate(chargeId);

Deleting a charge

Charges cannot be deleted unless they've been activated. Shopify automatically deletes pending charges after 48 hours pass without activation.

import{RecurringCharges}from"shopify-admin-api";constservice=newRecurringCharges(shopDomain,shopAccessToken);awaitservice.delete(chargeId);

One-time application charges

Just like with the above recurring charges, the Shopify billing API lets you create a one-time application charge on the shop owner's account. One-time charges cannot be deleted.

Create a one-time charge

import{Charges}from"shopify-admin-api";constservice=newCharges(shopDomain,shopAccessToken);letcharge={
Name ="Lorem Ipsum Charge",
Price =12.34,
Test =true,//Marks this charge as a test, meaning it won't charge the shop owner.}charge=awaitservice.create(charge);

Retrieve a one-time charge

import{Charges}from"shopify-admin-api";constservice=newCharges(shopDomain,shopAccessToken);constcharge=awaitservice.get(chargeId);

Listing one-time charges

import{Charges}from"shopify-admin-api";constservice=newCharges(shopDomain,shopAccessToken);constlist=service.list();

Activating a charge

Just like recurring charges, creating a one-time charge does not actually charge the shop owner. You need to send them to the charge's ConfirmationUrl, have them accept the charge, then activate it.

import{Charges}from"shopify-admin-api";constservice=newCharges(shopDomain,shopAccessToken);awaitservice.activate(chargeId);

Usage charges

Shopify's Usage Charges let you set a capped amount on a recurring application charge, and only charge for usage. For example, you can create a charge that's capped at $100.00 per month, and then charge e.g. $1.00 for every 1000 emails your user sends using your app.

To create a usage charge, you first need to create a recurring charge with a capped_amount value and a terms string. Your customers will see the terms when activating the recurring charge, so set it to something they can read like "$1.00 per 1000 emails".

Creating a usage charge

import{UsageCharges}from"shopify-admin-api";constservice=newUsageCharges(shopDomain,shopAccessToken);constcharge=awaitservice.create(recurringChargeId,{description: "Used 1000 emails",price: 1.00});

Getting a usage charge

import{UsageCharges}from"shopify-admin-api";constservice=newUsageCharges(shopDomain,shopAccessToken);constcharge=awaitservice.get(recurringChargeId,usageChargeId);

Listing usage charges

import{UsageCharges}from"shopify-admin-api";constservice=newUsageCharges(shopDomain,shopAccessToken);constlist=awaitservice.list(recurringChargeId);

Shops

Retrieving shop information

import{Shops}from"shopify-admin-api";constservice=newShops(shopDomain,shopAccessToken);constshop=awaitservice.get();

Uninstalling your app

In cases where user intervention is not required, you can send a request to a Shopify shop to force it to uninstall your application. After sending this request, the shop access token will be immediately revoked and invalidated.

Uninstalling an application is an irreversible operation. Be entirely sure that you no longer need to make API calls for the shop in which the application has been installed.

Uninstalling an application also performs various cleanup tasks within Shopify. Registered Webhooks, ScriptTags and App Links will be destroyed as part of this operation. Also if an application is uninstalled during key rotation, both the old and new Access Tokens will be rendered useless.

import{Shops}from"shopify-admin-api";constservice=newShops(shopDomain,shopAccessToken);awaitshop.forceUninstallApp();

Webhooks

Creating a webhook

import{Webhooks}from"shopify-admin-api";constservice=newWebhooks(shopDomain,shopAccessToken);letwebhook={
address ="https://my.webhook.url.com/path",
topic ="themes/publish",};webhook=awaitservice.create(webhook);

Retrieving a webhook

import{Webhooks}from"shopify-admin-api";constservice=newWebhooks(shopDomain,shopAccessToken);constwebhook=awaitservice.get(webhookId);

Updating a webhook

import{Webhooks}from"shopify-admin-api";constservice=newWebhooks(shopDomain,shopAccessToken);constwebhook=awaitservice.update(webhookId,{address: "https://my.webhook.url.com/new/path"});

Deleting a webhook

import{Webhooks}from"shopify-admin-api";constservice=newWebhooks(shopDomain,shopAccessToken);awaitservice.delete(webhookId);

Counting webhooks

import{Webhooks}from"shopify-admin-api";constservice=newWebhooks(shopDomain,shopAccessToken);constcount=awaitservice.count();

Listing webhooks

import{Webhooks}from"shopify-admin-api";constservice=newWebhooks(shopDomain,shopAccessToken);constwebhooks=awaitservice.list();

Script Tags

Script tags let you add remote javascript tags that are loaded into the pages of a shop's storefront, letting you dynamically change the functionality of their shop without manually editing their store's template.

Creating a script tag

import{ScriptTags}from"shopify-admin-api";constservice=newScriptTags(shopDomain,shopAccessToken);lettag={event: "onload",src: "https://example.com/my-javascript-file.js",display_scope: "all"}tag=awaitservice.create(tag);

Retrieving a script tag

import{ScriptTags}from"shopify-admin-api";constservice=newScriptTags(shopDomain,shopAccessToken);consttag=awaitservice.get(tagId);

Updating a script tag

import{ScriptTags}from"shopify-admin-api";constservice=newScriptTags(shopDomain,shopAccessToken);lettag=awaitservice.get(tagId);tag=awaitservice.update(tag.id,{src: "https://example.com/my-new-javascript-file.js"});

Deleting a script tag

import{ScriptTags}from"shopify-admin-api";constservice=newScriptTags(shopDomain,shopAccessToken);awaitservice.delete(tagId);

Counting script tags

import{ScriptTags}from"shopify-admin-api";constservice=newScriptTags(shopDomain,shopAccessToken);letcount=awaitservice.count();//Optionally filter the count to only those tags with a specific Srccount=awaitservice.count({src: "https://example.com/my-filtered-url.js"});

Listing script tags

import{ScriptTags,ScriptTag}from"shopify-admin-api";constservice=newScriptTags(shopDomain,shopAccessToken);lettags=awaitservice.list();//Optionally filter the list to only those tags with a specific Srctags=awaitservice.list({src: "https://example.com/my-filtered-url.js"});

Customers

The Customer resource stores information about a shop's customers, such as their contact details, their order history, and whether they've agreed to receive email marketing.

Listing Customers

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);letcustomers=awaitservice.list();// Optionally, filter the list for new customersletcustomers=awaitservice.list({limit: 10,since_id: customerId});

Searching Customers

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);letsearch=awaitservice.search({query: 'Bob country:United States'});

Getting count of Customers

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);letcount=awaitservice.count();

Creating a Customer

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);letcustomer=awaitservice.create({email: "customer@myshopify.com",first_name: "Jane",last_name: "Doe"});

Updating a Customer

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);letcustomer=awaitservice.update({email: "newemail@myshopify.com"});

Deleting a Customer

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);letcustomer=awaitservice.delete(123456789);

Generating activation URL

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);leturl=awaitservice.createActivationUrl(123456789);// => https://domain.myshopify.comcom/account/activate/XXXXXX/XXXXXXXXXXXXX

Inviting a Customer

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);constinvite=awaitservice.invite();// Optionally, send a custom inviteconstinvite=awaitservice.invite({to: "alternateemail@gmail.com",from: "fromemail@myshopify.com",subject: "Welcome!",custom_message: "My custom message"});

Orders

Creating an Order

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);constorder=awaitservice.create({billing_address: {address1: "123 4th Street",city: "Minneapolis",province: "Minnesota",province_code: "MN",zip: "55401",phone: "555-555-5555",first_name: "John",last_name: "Doe",company: "Tomorrow Corporation",country: "United States",country_code: "US",default: true,},line_items: [{name: "Test Line Item",title: "Test Line Item Title",quantity: 2,price: 5},{name: "Test Line Item 2",title: "Test Line Item Title 2",quantity: 2,price: 5}],financial_status: "paid",total_price: 5.00,email: Date.now()+"@gmail.com",note: "Test note about the customer.",});

Getting an Order

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);constorder=awaitservice.get(id);

Updating an Order

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);letorder=awaitservice.get(id);order.note="Updated note";order=awaitservice.update(id,order);

Listing Orders

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);constorders=awaitservice.list();

Counting Orders

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);constorderCount=awaitservice.count();

Deleting an Order

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);awaitservice.delete(id);

Closing an Order

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);constorder=awaitservice.close(id);

Opening an Order

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);constorder=awaitservice.open(id);

Canceling an Order

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);awaitservice.cancel(id,{reason: "customer"});

Application Credits

Shopify's Application Credit API lets you offer credits for payments your app customers have made via the Application Charge, Recurring Application Charge, and Usage Charge APIs.

The total amount of all Application Credits created by an application must not exceed:

  1. Total amount paid to the application by the shop owner in the last 30 days.
  2. Total amount of pending receivables in the partner account associated with the application.

Additionally, Application Credits cannot be used by private applications.

Creating an Application Credit

import{ApplicationCredits}from"shopify-admin-api";constservice=newApplicationCredits(shopDomain,shopAccessToken);constcredit=awaitservice.create({description: "Refund for Foo",amount: 10.00});

Getting an Application Credit

import{ApplicationCredits}from"shopify-admin-api";constservice=newApplicationCredits(shopDomain,shopAccessToken);constcredit=awaitservice.get(id);

Listing Application Credits

import{ApplicationCredits}from"shopify-admin-api";constservice=newApplicationCredits(shopDomain,shopAccessToken);constcredits=awaitservice.list();

Blogs

In addition to an online storefront, Shopify shops come with a built-in blogging engine, allowing a shop to have one or more blogs. This class is for interacting with blogs themselves, not blog posts.

Creating a Blog

import{Blogs}from"shopify-admin-api";constservice=newBlogs(shopDomain,shopAccessToken)constblog=awaitservice.create({title: "My new blog",})

Getting a Blog

import{Blogs}from"shopify-admin-api";constservice=newBlogs(shopDomain,shopAccessToken)constblog=awaitservice.get(blogId);

Updating a Blog

import{Blogs}from"shopify-admin-api";constservice=newBlogs(shopDomain,shopAccessToken)constblog=awaitservice.update(blogId,{title: "My updated blog title"})

Listing Blogs

import{Blogs}from"shopify-admin-api";constservice=newBlogs(shopDomain,shopAccessToken)constblogs=awaitservice.list();

Counting Blogs

import{Blogs}from"shopify-admin-api";constservice=newBlogs(shopDomain,shopAccessToken)constcount=awaitservice.count();

Deleting a Blog

import{Blogs}from"shopify-admin-api";constservice=newBlogs(shopDomain,shopAccessToken)awaitservice.delete(blogId);

Articles

Articles are objects representing a blog post. Each article belongs to a Blog.

Creating an Article

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);constarticle=awaitservice.create(blogId,{title: "My new Article title",author: "John Smith",tags: "This Post, Has Been Tagged",body_html: "<h1>Hello world!</h1>",image: {attachment: "R0lGODlhAQABAIAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==\n"}})

Getting an Article

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);constarticle=awaitservice.get(blogId,articleId);

Updating an Article

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);constarticle=awaitservice.update(blogId,articleId,{title: "My updated title"})

Listing Articles

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);constarticles=awaitservice.list(blogId);

Counting Articles

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);constcount=awaitservice.count(blogId);

Deleting an Article

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);awaitservice.delete(blogId,articleId);

Listing all Article authors

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);constauthors=awaitservice.listAuthors();console.log(authors);// ['John Doe', 'Jane Doe']

Listing all Article tags

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);consttags=awaitservice.listTags();console.log(tags);// ['Tag One', 'Tag Two']

Listing all Article tags for a blog

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);consttags=awaitservice.listTagsForBlog(blogId);console.log(tags);// ['Tag One', 'Tag Two']

About

Shopify Admin API is a NodeJS library built to help developers easily authenticate and make calls against the Shopify Admin API. It is forked from the deprecated Shopify-Prime library.

Topics

Resources

Stars

11 stars

Watchers

3 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

Shopify Admin API

Shopify Admin API for Node.js is a promise-driven NodeJS library built to help developers easily authenticate and make calls against the Shopify API. It is forked from the deprecated Shopify-Prime library.

Shopify Admin API is complete with full TypeScript definitions for all classes, interfaces and functions, and provides many quality of life improvements over most other Node Shopify libs. Tired of using undocumented libs that haven't been updated in ages, expect you to know all of the URL paths, and are little more than a basic wrapper over Node's http library? Give Shopify Admin API a try!

Installation

Shopify Admin API can be installed from NPM:

npm install shopify-admin-api --save

After installation, import Shopify Admin API via Node's require or ES6 import syntax:

//via requireconstShopify=require("shopify-admin-api");//via ES6import*asShopifyfrom"shopify-admin-api";

Tests

To run the tests on your locale machine you need a Shopify test shop in which you have created a private app, then you have to copy the credentials of the private app in the .env file in this project root directory. You can use the .env-example as a template:

cp .env-example .env
editor-of-your-choice .env

Now the test can be started:

yarn run build
yarn run test

Typescript declarations

Using TypeScript? The TypeScript compiler will automatically pull in Shopify Admin API definitions for you when you install Shopify Admin API, as long as you're using TypeScript 2+. Interfaces and extra types are available under the Interfaces, Enums and Options exports from the main "shopify-admin-api" module.

import{Shops}from"shopify-admin-api";// Typescript interfaces — not real JS objects:import{Interfaces,Enums,Options}from"shopify-admin-api";constshop: InterfacesShop=awaitnewShops(shopDomain,shopAccessToken).get(shopId);

Finally, because Shopify Admin API uses async/await and promises, you'll need to set your tsconfig.json's target to "es6". While not strictly necessary, Typescript won't know about the Promise type and will default all services' return types to any if you don't set your target to es6.

Async/await and promises

All Shopify Admin API functions are implemented as async/awaitable promises. You'll need Node.js v4 and above to use Shopify Admin API, as Node v3 and below don't support the generators needed for async/await.

Because async/await implements a promise-like interface in ES6, you can use the functions in this library in two different ways:

With async/await:

//1. async/awaitconstshop=awaitshops.get();//Do something with the shop

With promises:

constshop=shops.get().then((shop)=>{//Do something with the shop.});

Both methods are supported and the results won't differ. The only difference is an awaited method will throw an error if the method fails, where a promise would just fail silently unless you use .catch.

For the sake of being concise, all examples in this doc will use async/await.

A work-in-progress

This library is still pretty new. It currently suppports the following Shopify APIs:

More functionality will be added each week until it reachs full parity with Shopify's REST API.

Using Shopify Admin API with a public Shopify app

Note: All instances of shopAccessToken in the examples below do not refer to your Shopify API key. An access token is the token returned after authenticating and authorizing a Shopify app installation with a real Shopify store.

All instances of shopDomain refer to your users' *.myshopify.com URL (although their custom domain should work too).

import{Charges}from"shopify-admin-api";constchargeService=newCharges(shopDomain,shopAccessToken);

Using Shopify Admin API with a private Shopify app

Shopify Admin API should work out of the box with your private Shopify application, all you need to do is replace the shopAccessToken with your private app's password when initializing a service:

import{Orders}from"shopify-admin-api";constorderService=newOrders(shopDomain,privateAppPassword)

If you just need an access token for a private Shopify app, or for running the tests in this library, refer to the Tests section above.

Authorization and authentication

Ensure a given URL is a valid Shopify URL

This is a convenience method that validates whether a given URL is a valid Shopify shop. It's great for ensuring you don't redirect a user to an incorrect URL when you need them to authorize your app installation, and is ideally used in conjuction with .buildAuthorizationUrl.

Shopify Admin API will call the given URL and check for an X-ShopId header in the response. That header is present on all Shopify shops and its existence signals that the URL is indeed a Shopify URL.

Note, however, that this feature is undocumented by Shopify and may break at any time. Use at your own discretion.

import{Auth}from"shopify-admin-api";consturlFromUser="https://example.myshopify.com";constisValidUrl=awaitAuth.isValidMyShopifyDomain(urlFromUser).

Build an authorization URL

Redirect your users to this authorization URL, where they'll be prompted to install your app to their Shopify store.

import{Auth}from"shopify-admin-api";//This is the user's store URL.constusersShopifyUrl="https://example.myshopify.com";//An optional URL to redirect the user to after they've confirmed app installation.//If you don't specify a redirect url, Shopify will redirect to your app's default URL.constredirectUrl="https://example.com/my/redirect/url";//An array of the Shopify access scopes your application needs to run.constscopes=["read_orders","write_orders"];//Build the URL and send your user to it where they'll be prompted to install your app.constauthUrl=awaitAuth.buildAuthorizationUrl(scopes,usersShopifyUrl,yourShopifyApiKey,redirectUrl);

Authorize an installation and generate an access token

Once you've sent a user to the authorization URL and they've confirmed your app installation, they'll be redirected back to your application at either the default app URL, or the redirect URL you passed in when building the authorization URL.

The access token you receive after authorizing should be stored in your database. You'll need it to access the shop's resources (e.g. orders, customers, fulfillments, etc.)

import{Auth}from"shopify-admin-api";// The querystring will have several parameters you need for authorization.// Refer to your server framework docs for details on getting a request querystring.constcode=request.QueryString["code"];constshopUrl=request.QueryString["shop"];constaccessToken=awaitAuth.authorize(code,shopUrl,shopifyApiKey,shopifySecretKey)

Determine if a request is authentic

Any (non-webhook, non-proxy-page) request coming from Shopify will have a querystring paramater called 'hmac' that you can use to verify that the request is authentic. This hmac value is a hash of all querystring parameters and your app's secret key.

Pass the entire querystring to .isAuthenticRequest to verify the request.

import{Auth}from"shopify-admin-api";constqs=request.QueryString;constisAuthentic=awaitAuth.isAuthenticRequest(qs,shopifySecretKey);if(isAuthentic){//Request is authentic.}else{//Request is not authentic and should not be acted on.}

Determine if a proxy page request is authentic

Nearly identical to authenticating normal requests, a proxy page request only differs in the way the querystring is formatted to calculate the hmac signature. All proxy page requests coming from Shopify will have a querystring parameter named signature that you can use to verify the request. This signature is a hash of all querystring parameters and your app's secret key.

import{Auth}from"shopify-admin-api";constqs=request.QueryString;constisAuthentic=awaitAuth.isAuthenticProxyRequest(qs,shopifySecretKey);if(isAuthentic){//Request is authentic.}else{//Request is not authentic and should not be acted on.}

Determine if a webhook request is authentic

Any webhook request coming from Shopify will have a header called 'X-Shopify-Hmac-SHA256' that you can use to verify that the webhook is authentic. The header is a hash of the entire request body and your app's secret key.

Pass that header and the request body string to .isAuthenticWebhook to verify the request.

import{Auth}from"shopify-admin-api";consthmacHeader=request.QueryString["X-Shopify-Hmac-SHA256"];constbody=request.body.toString();constisAuthentic=awaitAuth.isAuthenticWebhook(hmacHeader,body,shopifySecretKey);if(isAuthentic){//Webhook is authentic.}else{//Webhook is not authentic and should not be acted on.}

You can also pass in the request body as a string, rather than using the input stream. However, the request body string needs to be identical to the way it was sent from Shopify. If it has been modified, the verification will fail.

Recurring Application Charges (monthly subscriptions)

The Shopify billing API lets you create a recurring charge on a shop owner's account, letting them pay you on a monthly basis for using your application.

Create a recurring charge

import{RecurringCharges}from"shopify-admin-api";constservice=newRecurringCharges(shopDomain,shopAccessToken);letcharge={
Name ="Lorem Ipsum Plan",
Price =12.34,
Test =true,//Marks this charge as a test, meaning it won't charge the shop owner.
TrialDays =21//Don't charge the user for 21 days}charge=awaitservice.create(charge);

Retrieve a recurring charge

import{RecurringCharges}from"shopify-admin-api";constservice=newRecurringCharges(shopDomain,shopAccessToken);constcharge=awaitservice.get(chargeId);

Listing recurring charges

import{RecurringCharges}from"shopify-admin-api";constservice=newRecurringCharges(shopDomain,shopAccessToken);constlist=awaitservice.list();

Activating a charge

Creating a charge does not actually charge the shop owner or even start their free trial. You need to send them to the charge's confirmation_url, have them accept the charge, then activate it.

import{RecurringCharges}from"shopify-admin-api";constservice=newRecurringCharges(shopDomain,shopAccessToken);awaitservice.activate(chargeId);

Deleting a charge

Charges cannot be deleted unless they've been activated. Shopify automatically deletes pending charges after 48 hours pass without activation.

import{RecurringCharges}from"shopify-admin-api";constservice=newRecurringCharges(shopDomain,shopAccessToken);awaitservice.delete(chargeId);

One-time application charges

Just like with the above recurring charges, the Shopify billing API lets you create a one-time application charge on the shop owner's account. One-time charges cannot be deleted.

Create a one-time charge

import{Charges}from"shopify-admin-api";constservice=newCharges(shopDomain,shopAccessToken);letcharge={
Name ="Lorem Ipsum Charge",
Price =12.34,
Test =true,//Marks this charge as a test, meaning it won't charge the shop owner.}charge=awaitservice.create(charge);

Retrieve a one-time charge

import{Charges}from"shopify-admin-api";constservice=newCharges(shopDomain,shopAccessToken);constcharge=awaitservice.get(chargeId);

Listing one-time charges

import{Charges}from"shopify-admin-api";constservice=newCharges(shopDomain,shopAccessToken);constlist=service.list();

Activating a charge

Just like recurring charges, creating a one-time charge does not actually charge the shop owner. You need to send them to the charge's ConfirmationUrl, have them accept the charge, then activate it.

import{Charges}from"shopify-admin-api";constservice=newCharges(shopDomain,shopAccessToken);awaitservice.activate(chargeId);

Usage charges

Shopify's Usage Charges let you set a capped amount on a recurring application charge, and only charge for usage. For example, you can create a charge that's capped at $100.00 per month, and then charge e.g. $1.00 for every 1000 emails your user sends using your app.

To create a usage charge, you first need to create a recurring charge with a capped_amount value and a terms string. Your customers will see the terms when activating the recurring charge, so set it to something they can read like "$1.00 per 1000 emails".

Creating a usage charge

import{UsageCharges}from"shopify-admin-api";constservice=newUsageCharges(shopDomain,shopAccessToken);constcharge=awaitservice.create(recurringChargeId,{description: "Used 1000 emails",price: 1.00});

Getting a usage charge

import{UsageCharges}from"shopify-admin-api";constservice=newUsageCharges(shopDomain,shopAccessToken);constcharge=awaitservice.get(recurringChargeId,usageChargeId);

Listing usage charges

import{UsageCharges}from"shopify-admin-api";constservice=newUsageCharges(shopDomain,shopAccessToken);constlist=awaitservice.list(recurringChargeId);

Shops

Retrieving shop information

import{Shops}from"shopify-admin-api";constservice=newShops(shopDomain,shopAccessToken);constshop=awaitservice.get();

Uninstalling your app

In cases where user intervention is not required, you can send a request to a Shopify shop to force it to uninstall your application. After sending this request, the shop access token will be immediately revoked and invalidated.

Uninstalling an application is an irreversible operation. Be entirely sure that you no longer need to make API calls for the shop in which the application has been installed.

Uninstalling an application also performs various cleanup tasks within Shopify. Registered Webhooks, ScriptTags and App Links will be destroyed as part of this operation. Also if an application is uninstalled during key rotation, both the old and new Access Tokens will be rendered useless.

import{Shops}from"shopify-admin-api";constservice=newShops(shopDomain,shopAccessToken);awaitshop.forceUninstallApp();

Webhooks

Creating a webhook

import{Webhooks}from"shopify-admin-api";constservice=newWebhooks(shopDomain,shopAccessToken);letwebhook={
address ="https://my.webhook.url.com/path",
topic ="themes/publish",};webhook=awaitservice.create(webhook);

Retrieving a webhook

import{Webhooks}from"shopify-admin-api";constservice=newWebhooks(shopDomain,shopAccessToken);constwebhook=awaitservice.get(webhookId);

Updating a webhook

import{Webhooks}from"shopify-admin-api";constservice=newWebhooks(shopDomain,shopAccessToken);constwebhook=awaitservice.update(webhookId,{address: "https://my.webhook.url.com/new/path"});

Deleting a webhook

import{Webhooks}from"shopify-admin-api";constservice=newWebhooks(shopDomain,shopAccessToken);awaitservice.delete(webhookId);

Counting webhooks

import{Webhooks}from"shopify-admin-api";constservice=newWebhooks(shopDomain,shopAccessToken);constcount=awaitservice.count();

Listing webhooks

import{Webhooks}from"shopify-admin-api";constservice=newWebhooks(shopDomain,shopAccessToken);constwebhooks=awaitservice.list();

Script Tags

Script tags let you add remote javascript tags that are loaded into the pages of a shop's storefront, letting you dynamically change the functionality of their shop without manually editing their store's template.

Creating a script tag

import{ScriptTags}from"shopify-admin-api";constservice=newScriptTags(shopDomain,shopAccessToken);lettag={event: "onload",src: "https://example.com/my-javascript-file.js",display_scope: "all"}tag=awaitservice.create(tag);

Retrieving a script tag

import{ScriptTags}from"shopify-admin-api";constservice=newScriptTags(shopDomain,shopAccessToken);consttag=awaitservice.get(tagId);

Updating a script tag

import{ScriptTags}from"shopify-admin-api";constservice=newScriptTags(shopDomain,shopAccessToken);lettag=awaitservice.get(tagId);tag=awaitservice.update(tag.id,{src: "https://example.com/my-new-javascript-file.js"});

Deleting a script tag

import{ScriptTags}from"shopify-admin-api";constservice=newScriptTags(shopDomain,shopAccessToken);awaitservice.delete(tagId);

Counting script tags

import{ScriptTags}from"shopify-admin-api";constservice=newScriptTags(shopDomain,shopAccessToken);letcount=awaitservice.count();//Optionally filter the count to only those tags with a specific Srccount=awaitservice.count({src: "https://example.com/my-filtered-url.js"});

Listing script tags

import{ScriptTags,ScriptTag}from"shopify-admin-api";constservice=newScriptTags(shopDomain,shopAccessToken);lettags=awaitservice.list();//Optionally filter the list to only those tags with a specific Srctags=awaitservice.list({src: "https://example.com/my-filtered-url.js"});

Customers

The Customer resource stores information about a shop's customers, such as their contact details, their order history, and whether they've agreed to receive email marketing.

Listing Customers

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);letcustomers=awaitservice.list();// Optionally, filter the list for new customersletcustomers=awaitservice.list({limit: 10,since_id: customerId});

Searching Customers

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);letsearch=awaitservice.search({query: 'Bob country:United States'});

Getting count of Customers

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);letcount=awaitservice.count();

Creating a Customer

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);letcustomer=awaitservice.create({email: "customer@myshopify.com",first_name: "Jane",last_name: "Doe"});

Updating a Customer

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);letcustomer=awaitservice.update({email: "newemail@myshopify.com"});

Deleting a Customer

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);letcustomer=awaitservice.delete(123456789);

Generating activation URL

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);leturl=awaitservice.createActivationUrl(123456789);// => https://domain.myshopify.comcom/account/activate/XXXXXX/XXXXXXXXXXXXX

Inviting a Customer

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);constinvite=awaitservice.invite();// Optionally, send a custom inviteconstinvite=awaitservice.invite({to: "alternateemail@gmail.com",from: "fromemail@myshopify.com",subject: "Welcome!",custom_message: "My custom message"});

Orders

Creating an Order

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);constorder=awaitservice.create({billing_address: {address1: "123 4th Street",city: "Minneapolis",province: "Minnesota",province_code: "MN",zip: "55401",phone: "555-555-5555",first_name: "John",last_name: "Doe",company: "Tomorrow Corporation",country: "United States",country_code: "US",default: true,},line_items: [{name: "Test Line Item",title: "Test Line Item Title",quantity: 2,price: 5},{name: "Test Line Item 2",title: "Test Line Item Title 2",quantity: 2,price: 5}],financial_status: "paid",total_price: 5.00,email: Date.now()+"@gmail.com",note: "Test note about the customer.",});

Getting an Order

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);constorder=awaitservice.get(id);

Updating an Order

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);letorder=awaitservice.get(id);order.note="Updated note";order=awaitservice.update(id,order);

Listing Orders

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);constorders=awaitservice.list();

Counting Orders

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);constorderCount=awaitservice.count();

Deleting an Order

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);awaitservice.delete(id);

Closing an Order

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);constorder=awaitservice.close(id);

Opening an Order

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);constorder=awaitservice.open(id);

Canceling an Order

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);awaitservice.cancel(id,{reason: "customer"});

Application Credits

Shopify's Application Credit API lets you offer credits for payments your app customers have made via the Application Charge, Recurring Application Charge, and Usage Charge APIs.

The total amount of all Application Credits created by an application must not exceed:

  1. Total amount paid to the application by the shop owner in the last 30 days.
  2. Total amount of pending receivables in the partner account associated with the application.

Additionally, Application Credits cannot be used by private applications.

Creating an Application Credit

import{ApplicationCredits}from"shopify-admin-api";constservice=newApplicationCredits(shopDomain,shopAccessToken);constcredit=awaitservice.create({description: "Refund for Foo",amount: 10.00});

Getting an Application Credit

import{ApplicationCredits}from"shopify-admin-api";constservice=newApplicationCredits(shopDomain,shopAccessToken);constcredit=awaitservice.get(id);

Listing Application Credits

import{ApplicationCredits}from"shopify-admin-api";constservice=newApplicationCredits(shopDomain,shopAccessToken);constcredits=awaitservice.list();

Blogs

In addition to an online storefront, Shopify shops come with a built-in blogging engine, allowing a shop to have one or more blogs. This class is for interacting with blogs themselves, not blog posts.

Creating a Blog

import{Blogs}from"shopify-admin-api";constservice=newBlogs(shopDomain,shopAccessToken)constblog=awaitservice.create({title: "My new blog",})

Getting a Blog

import{Blogs}from"shopify-admin-api";constservice=newBlogs(shopDomain,shopAccessToken)constblog=awaitservice.get(blogId);

Updating a Blog

import{Blogs}from"shopify-admin-api";constservice=newBlogs(shopDomain,shopAccessToken)constblog=awaitservice.update(blogId,{title: "My updated blog title"})

Listing Blogs

import{Blogs}from"shopify-admin-api";constservice=newBlogs(shopDomain,shopAccessToken)constblogs=awaitservice.list();

Counting Blogs

import{Blogs}from"shopify-admin-api";constservice=newBlogs(shopDomain,shopAccessToken)constcount=awaitservice.count();

Deleting a Blog

import{Blogs}from"shopify-admin-api";constservice=newBlogs(shopDomain,shopAccessToken)awaitservice.delete(blogId);

Articles

Articles are objects representing a blog post. Each article belongs to a Blog.

Creating an Article

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);constarticle=awaitservice.create(blogId,{title: "My new Article title",author: "John Smith",tags: "This Post, Has Been Tagged",body_html: "<h1>Hello world!</h1>",image: {attachment: "R0lGODlhAQABAIAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==\n"}})

Getting an Article

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);constarticle=awaitservice.get(blogId,articleId);

Updating an Article

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);constarticle=awaitservice.update(blogId,articleId,{title: "My updated title"})

Listing Articles

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);constarticles=awaitservice.list(blogId);

Counting Articles

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);constcount=awaitservice.count(blogId);

Deleting an Article

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);awaitservice.delete(blogId,articleId);

Listing all Article authors

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);constauthors=awaitservice.listAuthors();console.log(authors);// ['John Doe', 'Jane Doe']

Listing all Article tags

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);consttags=awaitservice.listTags();console.log(tags);// ['Tag One', 'Tag Two']

Listing all Article tags for a blog

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);consttags=awaitservice.listTagsForBlog(blogId);console.log(tags);// ['Tag One', 'Tag Two']

About

Shopify Admin API is a NodeJS library built to help developers easily authenticate and make calls against the Shopify Admin API. It is forked from the deprecated Shopify-Prime library.

Topics

Resources

Stars

11 stars

Watchers

3 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Repository files navigation

Shopify Admin API

Shopify Admin API for Node.js is a promise-driven NodeJS library built to help developers easily authenticate and make calls against the Shopify API. It is forked from the deprecated Shopify-Prime library.

Shopify Admin API is complete with full TypeScript definitions for all classes, interfaces and functions, and provides many quality of life improvements over most other Node Shopify libs. Tired of using undocumented libs that haven't been updated in ages, expect you to know all of the URL paths, and are little more than a basic wrapper over Node's http library? Give Shopify Admin API a try!

Installation

Shopify Admin API can be installed from NPM:

npm install shopify-admin-api --save

After installation, import Shopify Admin API via Node's require or ES6 import syntax:

//via requireconstShopify=require("shopify-admin-api");//via ES6import*asShopifyfrom"shopify-admin-api";

Tests

To run the tests on your locale machine you need a Shopify test shop in which you have created a private app, then you have to copy the credentials of the private app in the .env file in this project root directory. You can use the .env-example as a template:

cp .env-example .env
editor-of-your-choice .env

Now the test can be started:

yarn run build
yarn run test

Typescript declarations

Using TypeScript? The TypeScript compiler will automatically pull in Shopify Admin API definitions for you when you install Shopify Admin API, as long as you're using TypeScript 2+. Interfaces and extra types are available under the Interfaces, Enums and Options exports from the main "shopify-admin-api" module.

import{Shops}from"shopify-admin-api";// Typescript interfaces — not real JS objects:import{Interfaces,Enums,Options}from"shopify-admin-api";constshop: InterfacesShop=awaitnewShops(shopDomain,shopAccessToken).get(shopId);

Finally, because Shopify Admin API uses async/await and promises, you'll need to set your tsconfig.json's target to "es6". While not strictly necessary, Typescript won't know about the Promise type and will default all services' return types to any if you don't set your target to es6.

Async/await and promises

All Shopify Admin API functions are implemented as async/awaitable promises. You'll need Node.js v4 and above to use Shopify Admin API, as Node v3 and below don't support the generators needed for async/await.

Because async/await implements a promise-like interface in ES6, you can use the functions in this library in two different ways:

With async/await:

//1. async/awaitconstshop=awaitshops.get();//Do something with the shop

With promises:

constshop=shops.get().then((shop)=>{//Do something with the shop.});

Both methods are supported and the results won't differ. The only difference is an awaited method will throw an error if the method fails, where a promise would just fail silently unless you use .catch.

For the sake of being concise, all examples in this doc will use async/await.

A work-in-progress

This library is still pretty new. It currently suppports the following Shopify APIs:

More functionality will be added each week until it reachs full parity with Shopify's REST API.

Using Shopify Admin API with a public Shopify app

Note: All instances of shopAccessToken in the examples below do not refer to your Shopify API key. An access token is the token returned after authenticating and authorizing a Shopify app installation with a real Shopify store.

All instances of shopDomain refer to your users' *.myshopify.com URL (although their custom domain should work too).

import{Charges}from"shopify-admin-api";constchargeService=newCharges(shopDomain,shopAccessToken);

Using Shopify Admin API with a private Shopify app

Shopify Admin API should work out of the box with your private Shopify application, all you need to do is replace the shopAccessToken with your private app's password when initializing a service:

import{Orders}from"shopify-admin-api";constorderService=newOrders(shopDomain,privateAppPassword)

If you just need an access token for a private Shopify app, or for running the tests in this library, refer to the Tests section above.

Authorization and authentication

Ensure a given URL is a valid Shopify URL

This is a convenience method that validates whether a given URL is a valid Shopify shop. It's great for ensuring you don't redirect a user to an incorrect URL when you need them to authorize your app installation, and is ideally used in conjuction with .buildAuthorizationUrl.

Shopify Admin API will call the given URL and check for an X-ShopId header in the response. That header is present on all Shopify shops and its existence signals that the URL is indeed a Shopify URL.

Note, however, that this feature is undocumented by Shopify and may break at any time. Use at your own discretion.

import{Auth}from"shopify-admin-api";consturlFromUser="https://example.myshopify.com";constisValidUrl=awaitAuth.isValidMyShopifyDomain(urlFromUser).

Build an authorization URL

Redirect your users to this authorization URL, where they'll be prompted to install your app to their Shopify store.

import{Auth}from"shopify-admin-api";//This is the user's store URL.constusersShopifyUrl="https://example.myshopify.com";//An optional URL to redirect the user to after they've confirmed app installation.//If you don't specify a redirect url, Shopify will redirect to your app's default URL.constredirectUrl="https://example.com/my/redirect/url";//An array of the Shopify access scopes your application needs to run.constscopes=["read_orders","write_orders"];//Build the URL and send your user to it where they'll be prompted to install your app.constauthUrl=awaitAuth.buildAuthorizationUrl(scopes,usersShopifyUrl,yourShopifyApiKey,redirectUrl);

Authorize an installation and generate an access token

Once you've sent a user to the authorization URL and they've confirmed your app installation, they'll be redirected back to your application at either the default app URL, or the redirect URL you passed in when building the authorization URL.

The access token you receive after authorizing should be stored in your database. You'll need it to access the shop's resources (e.g. orders, customers, fulfillments, etc.)

import{Auth}from"shopify-admin-api";// The querystring will have several parameters you need for authorization.// Refer to your server framework docs for details on getting a request querystring.constcode=request.QueryString["code"];constshopUrl=request.QueryString["shop"];constaccessToken=awaitAuth.authorize(code,shopUrl,shopifyApiKey,shopifySecretKey)

Determine if a request is authentic

Any (non-webhook, non-proxy-page) request coming from Shopify will have a querystring paramater called 'hmac' that you can use to verify that the request is authentic. This hmac value is a hash of all querystring parameters and your app's secret key.

Pass the entire querystring to .isAuthenticRequest to verify the request.

import{Auth}from"shopify-admin-api";constqs=request.QueryString;constisAuthentic=awaitAuth.isAuthenticRequest(qs,shopifySecretKey);if(isAuthentic){//Request is authentic.}else{//Request is not authentic and should not be acted on.}

Determine if a proxy page request is authentic

Nearly identical to authenticating normal requests, a proxy page request only differs in the way the querystring is formatted to calculate the hmac signature. All proxy page requests coming from Shopify will have a querystring parameter named signature that you can use to verify the request. This signature is a hash of all querystring parameters and your app's secret key.

import{Auth}from"shopify-admin-api";constqs=request.QueryString;constisAuthentic=awaitAuth.isAuthenticProxyRequest(qs,shopifySecretKey);if(isAuthentic){//Request is authentic.}else{//Request is not authentic and should not be acted on.}

Determine if a webhook request is authentic

Any webhook request coming from Shopify will have a header called 'X-Shopify-Hmac-SHA256' that you can use to verify that the webhook is authentic. The header is a hash of the entire request body and your app's secret key.

Pass that header and the request body string to .isAuthenticWebhook to verify the request.

import{Auth}from"shopify-admin-api";consthmacHeader=request.QueryString["X-Shopify-Hmac-SHA256"];constbody=request.body.toString();constisAuthentic=awaitAuth.isAuthenticWebhook(hmacHeader,body,shopifySecretKey);if(isAuthentic){//Webhook is authentic.}else{//Webhook is not authentic and should not be acted on.}

You can also pass in the request body as a string, rather than using the input stream. However, the request body string needs to be identical to the way it was sent from Shopify. If it has been modified, the verification will fail.

Recurring Application Charges (monthly subscriptions)

The Shopify billing API lets you create a recurring charge on a shop owner's account, letting them pay you on a monthly basis for using your application.

Create a recurring charge

import{RecurringCharges}from"shopify-admin-api";constservice=newRecurringCharges(shopDomain,shopAccessToken);letcharge={
Name ="Lorem Ipsum Plan",
Price =12.34,
Test =true,//Marks this charge as a test, meaning it won't charge the shop owner.
TrialDays =21//Don't charge the user for 21 days}charge=awaitservice.create(charge);

Retrieve a recurring charge

import{RecurringCharges}from"shopify-admin-api";constservice=newRecurringCharges(shopDomain,shopAccessToken);constcharge=awaitservice.get(chargeId);

Listing recurring charges

import{RecurringCharges}from"shopify-admin-api";constservice=newRecurringCharges(shopDomain,shopAccessToken);constlist=awaitservice.list();

Activating a charge

Creating a charge does not actually charge the shop owner or even start their free trial. You need to send them to the charge's confirmation_url, have them accept the charge, then activate it.

import{RecurringCharges}from"shopify-admin-api";constservice=newRecurringCharges(shopDomain,shopAccessToken);awaitservice.activate(chargeId);

Deleting a charge

Charges cannot be deleted unless they've been activated. Shopify automatically deletes pending charges after 48 hours pass without activation.

import{RecurringCharges}from"shopify-admin-api";constservice=newRecurringCharges(shopDomain,shopAccessToken);awaitservice.delete(chargeId);

One-time application charges

Just like with the above recurring charges, the Shopify billing API lets you create a one-time application charge on the shop owner's account. One-time charges cannot be deleted.

Create a one-time charge

import{Charges}from"shopify-admin-api";constservice=newCharges(shopDomain,shopAccessToken);letcharge={
Name ="Lorem Ipsum Charge",
Price =12.34,
Test =true,//Marks this charge as a test, meaning it won't charge the shop owner.}charge=awaitservice.create(charge);

Retrieve a one-time charge

import{Charges}from"shopify-admin-api";constservice=newCharges(shopDomain,shopAccessToken);constcharge=awaitservice.get(chargeId);

Listing one-time charges

import{Charges}from"shopify-admin-api";constservice=newCharges(shopDomain,shopAccessToken);constlist=service.list();

Activating a charge

Just like recurring charges, creating a one-time charge does not actually charge the shop owner. You need to send them to the charge's ConfirmationUrl, have them accept the charge, then activate it.

import{Charges}from"shopify-admin-api";constservice=newCharges(shopDomain,shopAccessToken);awaitservice.activate(chargeId);

Usage charges

Shopify's Usage Charges let you set a capped amount on a recurring application charge, and only charge for usage. For example, you can create a charge that's capped at $100.00 per month, and then charge e.g. $1.00 for every 1000 emails your user sends using your app.

To create a usage charge, you first need to create a recurring charge with a capped_amount value and a terms string. Your customers will see the terms when activating the recurring charge, so set it to something they can read like "$1.00 per 1000 emails".

Creating a usage charge

import{UsageCharges}from"shopify-admin-api";constservice=newUsageCharges(shopDomain,shopAccessToken);constcharge=awaitservice.create(recurringChargeId,{description: "Used 1000 emails",price: 1.00});

Getting a usage charge

import{UsageCharges}from"shopify-admin-api";constservice=newUsageCharges(shopDomain,shopAccessToken);constcharge=awaitservice.get(recurringChargeId,usageChargeId);

Listing usage charges

import{UsageCharges}from"shopify-admin-api";constservice=newUsageCharges(shopDomain,shopAccessToken);constlist=awaitservice.list(recurringChargeId);

Shops

Retrieving shop information

import{Shops}from"shopify-admin-api";constservice=newShops(shopDomain,shopAccessToken);constshop=awaitservice.get();

Uninstalling your app

In cases where user intervention is not required, you can send a request to a Shopify shop to force it to uninstall your application. After sending this request, the shop access token will be immediately revoked and invalidated.

Uninstalling an application is an irreversible operation. Be entirely sure that you no longer need to make API calls for the shop in which the application has been installed.

Uninstalling an application also performs various cleanup tasks within Shopify. Registered Webhooks, ScriptTags and App Links will be destroyed as part of this operation. Also if an application is uninstalled during key rotation, both the old and new Access Tokens will be rendered useless.

import{Shops}from"shopify-admin-api";constservice=newShops(shopDomain,shopAccessToken);awaitshop.forceUninstallApp();

Webhooks

Creating a webhook

import{Webhooks}from"shopify-admin-api";constservice=newWebhooks(shopDomain,shopAccessToken);letwebhook={
address ="https://my.webhook.url.com/path",
topic ="themes/publish",};webhook=awaitservice.create(webhook);

Retrieving a webhook

import{Webhooks}from"shopify-admin-api";constservice=newWebhooks(shopDomain,shopAccessToken);constwebhook=awaitservice.get(webhookId);

Updating a webhook

import{Webhooks}from"shopify-admin-api";constservice=newWebhooks(shopDomain,shopAccessToken);constwebhook=awaitservice.update(webhookId,{address: "https://my.webhook.url.com/new/path"});

Deleting a webhook

import{Webhooks}from"shopify-admin-api";constservice=newWebhooks(shopDomain,shopAccessToken);awaitservice.delete(webhookId);

Counting webhooks

import{Webhooks}from"shopify-admin-api";constservice=newWebhooks(shopDomain,shopAccessToken);constcount=awaitservice.count();

Listing webhooks

import{Webhooks}from"shopify-admin-api";constservice=newWebhooks(shopDomain,shopAccessToken);constwebhooks=awaitservice.list();

Script Tags

Script tags let you add remote javascript tags that are loaded into the pages of a shop's storefront, letting you dynamically change the functionality of their shop without manually editing their store's template.

Creating a script tag

import{ScriptTags}from"shopify-admin-api";constservice=newScriptTags(shopDomain,shopAccessToken);lettag={event: "onload",src: "https://example.com/my-javascript-file.js",display_scope: "all"}tag=awaitservice.create(tag);

Retrieving a script tag

import{ScriptTags}from"shopify-admin-api";constservice=newScriptTags(shopDomain,shopAccessToken);consttag=awaitservice.get(tagId);

Updating a script tag

import{ScriptTags}from"shopify-admin-api";constservice=newScriptTags(shopDomain,shopAccessToken);lettag=awaitservice.get(tagId);tag=awaitservice.update(tag.id,{src: "https://example.com/my-new-javascript-file.js"});

Deleting a script tag

import{ScriptTags}from"shopify-admin-api";constservice=newScriptTags(shopDomain,shopAccessToken);awaitservice.delete(tagId);

Counting script tags

import{ScriptTags}from"shopify-admin-api";constservice=newScriptTags(shopDomain,shopAccessToken);letcount=awaitservice.count();//Optionally filter the count to only those tags with a specific Srccount=awaitservice.count({src: "https://example.com/my-filtered-url.js"});

Listing script tags

import{ScriptTags,ScriptTag}from"shopify-admin-api";constservice=newScriptTags(shopDomain,shopAccessToken);lettags=awaitservice.list();//Optionally filter the list to only those tags with a specific Srctags=awaitservice.list({src: "https://example.com/my-filtered-url.js"});

Customers

The Customer resource stores information about a shop's customers, such as their contact details, their order history, and whether they've agreed to receive email marketing.

Listing Customers

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);letcustomers=awaitservice.list();// Optionally, filter the list for new customersletcustomers=awaitservice.list({limit: 10,since_id: customerId});

Searching Customers

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);letsearch=awaitservice.search({query: 'Bob country:United States'});

Getting count of Customers

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);letcount=awaitservice.count();

Creating a Customer

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);letcustomer=awaitservice.create({email: "customer@myshopify.com",first_name: "Jane",last_name: "Doe"});

Updating a Customer

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);letcustomer=awaitservice.update({email: "newemail@myshopify.com"});

Deleting a Customer

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);letcustomer=awaitservice.delete(123456789);

Generating activation URL

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);leturl=awaitservice.createActivationUrl(123456789);// => https://domain.myshopify.comcom/account/activate/XXXXXX/XXXXXXXXXXXXX

Inviting a Customer

import{Customers}from"shopify-admin-api";constservice=newCustomers(shopDomain,shopAccessToken);constinvite=awaitservice.invite();// Optionally, send a custom inviteconstinvite=awaitservice.invite({to: "alternateemail@gmail.com",from: "fromemail@myshopify.com",subject: "Welcome!",custom_message: "My custom message"});

Orders

Creating an Order

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);constorder=awaitservice.create({billing_address: {address1: "123 4th Street",city: "Minneapolis",province: "Minnesota",province_code: "MN",zip: "55401",phone: "555-555-5555",first_name: "John",last_name: "Doe",company: "Tomorrow Corporation",country: "United States",country_code: "US",default: true,},line_items: [{name: "Test Line Item",title: "Test Line Item Title",quantity: 2,price: 5},{name: "Test Line Item 2",title: "Test Line Item Title 2",quantity: 2,price: 5}],financial_status: "paid",total_price: 5.00,email: Date.now()+"@gmail.com",note: "Test note about the customer.",});

Getting an Order

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);constorder=awaitservice.get(id);

Updating an Order

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);letorder=awaitservice.get(id);order.note="Updated note";order=awaitservice.update(id,order);

Listing Orders

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);constorders=awaitservice.list();

Counting Orders

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);constorderCount=awaitservice.count();

Deleting an Order

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);awaitservice.delete(id);

Closing an Order

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);constorder=awaitservice.close(id);

Opening an Order

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);constorder=awaitservice.open(id);

Canceling an Order

import{Orders}from"shopify-admin-api";constservice=newOrders(shopDomain,shopAccessToken);awaitservice.cancel(id,{reason: "customer"});

Application Credits

Shopify's Application Credit API lets you offer credits for payments your app customers have made via the Application Charge, Recurring Application Charge, and Usage Charge APIs.

The total amount of all Application Credits created by an application must not exceed:

  1. Total amount paid to the application by the shop owner in the last 30 days.
  2. Total amount of pending receivables in the partner account associated with the application.

Additionally, Application Credits cannot be used by private applications.

Creating an Application Credit

import{ApplicationCredits}from"shopify-admin-api";constservice=newApplicationCredits(shopDomain,shopAccessToken);constcredit=awaitservice.create({description: "Refund for Foo",amount: 10.00});

Getting an Application Credit

import{ApplicationCredits}from"shopify-admin-api";constservice=newApplicationCredits(shopDomain,shopAccessToken);constcredit=awaitservice.get(id);

Listing Application Credits

import{ApplicationCredits}from"shopify-admin-api";constservice=newApplicationCredits(shopDomain,shopAccessToken);constcredits=awaitservice.list();

Blogs

In addition to an online storefront, Shopify shops come with a built-in blogging engine, allowing a shop to have one or more blogs. This class is for interacting with blogs themselves, not blog posts.

Creating a Blog

import{Blogs}from"shopify-admin-api";constservice=newBlogs(shopDomain,shopAccessToken)constblog=awaitservice.create({title: "My new blog",})

Getting a Blog

import{Blogs}from"shopify-admin-api";constservice=newBlogs(shopDomain,shopAccessToken)constblog=awaitservice.get(blogId);

Updating a Blog

import{Blogs}from"shopify-admin-api";constservice=newBlogs(shopDomain,shopAccessToken)constblog=awaitservice.update(blogId,{title: "My updated blog title"})

Listing Blogs

import{Blogs}from"shopify-admin-api";constservice=newBlogs(shopDomain,shopAccessToken)constblogs=awaitservice.list();

Counting Blogs

import{Blogs}from"shopify-admin-api";constservice=newBlogs(shopDomain,shopAccessToken)constcount=awaitservice.count();

Deleting a Blog

import{Blogs}from"shopify-admin-api";constservice=newBlogs(shopDomain,shopAccessToken)awaitservice.delete(blogId);

Articles

Articles are objects representing a blog post. Each article belongs to a Blog.

Creating an Article

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);constarticle=awaitservice.create(blogId,{title: "My new Article title",author: "John Smith",tags: "This Post, Has Been Tagged",body_html: "<h1>Hello world!</h1>",image: {attachment: "R0lGODlhAQABAIAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==\n"}})

Getting an Article

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);constarticle=awaitservice.get(blogId,articleId);

Updating an Article

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);constarticle=awaitservice.update(blogId,articleId,{title: "My updated title"})

Listing Articles

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);constarticles=awaitservice.list(blogId);

Counting Articles

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);constcount=awaitservice.count(blogId);

Deleting an Article

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);awaitservice.delete(blogId,articleId);

Listing all Article authors

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);constauthors=awaitservice.listAuthors();console.log(authors);// ['John Doe', 'Jane Doe']

Listing all Article tags

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);consttags=awaitservice.listTags();console.log(tags);// ['Tag One', 'Tag Two']

Listing all Article tags for a blog

import{Articles}from"shopify-admin-api";constservice=newArticles(shopDomain,shopAccessToken);consttags=awaitservice.listTagsForBlog(blogId);console.log(tags);// ['Tag One', 'Tag Two']

About

Shopify Admin API is a NodeJS library built to help developers easily authenticate and make calls against the Shopify Admin API. It is forked from the deprecated Shopify-Prime library.

Topics

Resources

Stars

11 stars

Watchers

3 watching

Forks

Releases

Packages

Used by

Contributors

Languages