├── .dependabot └── config.yml ├── .github ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── ISSUE_TEMPLATE.md └── PULL_REQUEST_TEMPLATE.md ├── .gitignore ├── LICENSE.md ├── README.md ├── SECURITY.md ├── components ├── ClientRouter.js └── ResourceList.js ├── next.config.js ├── package-lock.json ├── package.json ├── pages ├── _app.js ├── annotated-layout.js ├── edit-products.js └── index.js ├── server.js └── server └── getSubscriptionUrl.js /.dependabot/config.yml: -------------------------------------------------------------------------------- 1 | version: 1 2 | update_configs: 3 | # Keep package.json up to date as soon as 4 | # new versions are published to the npm registry 5 | - package_manager: "javascript" 6 | directory: "/" 7 | update_schedule: "weekly" 8 | default_reviewers: 9 | - "Shopify/platform-dev-tools-education" 10 | version_requirement_updates: "auto" 11 | -------------------------------------------------------------------------------- /.github/CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, gender identity and expression, level of experience, 9 | nationality, personal appearance, race, religion, or sexual identity and 10 | orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at opensource@shopify.com. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct/ 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | -------------------------------------------------------------------------------- /.github/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to contribute 2 | 3 | ## Creating issues 4 | 5 | Before submitting issues, please have a quick look if there is an existing open issue [here](https://github.com/Shopify/shopify-demo-app-node-react/issues). If no related issue can be found, please open a new issue. 6 | 7 | Please limit issues to bug reports about existing tutorial content. 8 | 9 | If you are looking for information about how to do something not covered in this tutorial, or if you are looking for general support about creating Shopify apps, please post in the Shopify APIs & SDKs section of our Community forums: 10 | 11 | https://community.shopify.com/c/Shopify-APIs-SDKs/bd-p/shopify-apis-and-technology 12 | 13 | ## Opening pull requests 14 | 15 | This repo exists only to provide example code for the [Build a Shopify app with Node and React](https://developers.shopify.com/tutorials/build-a-shopify-app-with-node-and-react/) tutorial. Thank you for taking the time to submit a pull request, but we are not accepting contributions at this time, and all external PRs will be closed without merging. 16 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 8 | 9 | # Bug summary 10 | 11 | Write a short description of the bug here ↓ 12 | 13 | 14 | 15 | ## Expected behavior 16 | 17 | What do you think should happen? 18 | 19 | 20 | 21 | ## Actual behavior 22 | 23 | What actually happens? 24 | 25 | Tip: include an error message (in a `
` tag) if your issue is related to an error 26 | 27 | 28 | 29 | ## Steps to reproduce the problem 30 | 31 | 1. 32 | 1. 33 | 1. 34 | 35 | ## Reduced test case 36 | 37 | The best way to get your bug fixed is to provide a reduced test case. 38 | 39 | 40 | 41 | ## Specifications 42 | 43 | - Browser: 44 | - Device: 45 | - Operating System: 46 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | This repo exists only to provide example code for the [Build a Shopify app with Node and React](https://developers.shopify.com/tutorials/build-a-shopify-app-with-node-and-react/) tutorial. Thank you for taking the time to submit a pull request, but we are not accepting contributions at this time, and all external PRs will be closed without merging. 2 | 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .next 3 | .env 4 | npm-debug.log 5 | .prettierrc 6 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Shopify 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # shopify-demo-app-node-react 2 | [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE.md) 3 | 4 | This repository is deprecated and has been replaced by [Shopify App Node](https://github.com/Shopify/shopify-app-node). 5 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | ## Supported versions 4 | 5 | ### New features 6 | 7 | New features will only be added to the master branch and will not be made available in point releases. 8 | 9 | ### Bug fixes 10 | 11 | Only the latest release series will receive bug fixes. When enough bugs are fixed and its deemed worthy to release a new gem, this is the branch it happens from. 12 | 13 | ### Security issues 14 | 15 | Only the latest release series will receive patches and new versions in case of a security issue. 16 | 17 | ### Severe security issues 18 | 19 | For severe security issues we will provide new versions as above, and also the last major release series will receive patches and new versions. The classification of the security issue is judged by the core team. 20 | 21 | ### Unsupported Release Series 22 | 23 | When a release series is no longer supported, it's your own responsibility to deal with bugs and security issues. If you are not comfortable maintaining your own versions, you should upgrade to a supported version. 24 | 25 | ## Reporting a bug 26 | 27 | All security bugs in shopify repositories should be reported to [our hackerone program](https://hackerone.com/shopify) 28 | Shopify's whitehat program is our way to reward security researchers for finding serious security vulnerabilities in the In Scope properties listed at the bottom of this page, including our core application (all functionality associated with a Shopify store, particularly your-store.myshopify.com/admin) and certain ancillary applications. 29 | 30 | ## Disclosure Policy 31 | 32 | We look forward to working with all security researchers and strive to be respectful, always assume the best and treat others as peers. We expect the same in return from all participants. To achieve this, our team strives to: 33 | 34 | - Reply to all reports within one business day and triage within two business days (if applicable) 35 | - Be as transparent as possible, answering all inquires about our report decisions and adding hackers to duplicate HackerOne reports 36 | - Award bounties within a week of resolution (excluding extenuating circumstances) 37 | - Only close reports as N/A when the issue reported is included in Known Issues, Ineligible Vulnerabilities Types or lacks evidence of a vulnerability 38 | 39 | **The following rules must be followed in order for any rewards to be paid:** 40 | 41 | - You may only test against shops you have created which include your HackerOne YOURHANDLE @ wearehackerone.com registered email address. 42 | - You must not attempt to gain access to, or interact with, any shops other than those created by you. 43 | - The use of commercial scanners is prohibited (e.g., Nessus). 44 | - Rules for reporting must be followed. 45 | - Do not disclose any issues publicly before they have been resolved. 46 | - Shopify reserves the right to modify the rules for this program or deem any submissions invalid at any time. Shopify may cancel the whitehat program without notice at any time. 47 | - Contacting Shopify Support over chat, email or phone about your HackerOne report is not allowed. We may disqualify you from receiving a reward, or from participating in the program altogether. 48 | - You are not an employee of Shopify; employees should report bugs to the internal bug bounty program. 49 | - You hereby represent, warrant and covenant that any content you submit to Shopify is an original work of authorship and that you are legally entitled to grant the rights and privileges conveyed by these terms. You further represent, warrant and covenant that the consent of no other person or entity is or will be necessary for Shopify to use the submitted content. 50 | - By submitting content to Shopify, you irrevocably waive all moral rights which you may have in the content. 51 | - All content submitted by you to Shopify under this program is licensed under the MIT License. 52 | - You must report any discovered vulnerability to Shopify as soon as you have validated the vulnerability. 53 | - Failure to follow any of the foregoing rules will disqualify you from participating in this program. 54 | 55 | ** Please see our [Hackerone Profile](https://hackerone.com/shopify) for full details 56 | 57 | ## Receiving Security Updates 58 | 59 | To receive all general updates to vulnerabilities, please subscribe to our hackerone [Hacktivity](https://hackerone.com/shopify/hacktivity) 60 | -------------------------------------------------------------------------------- /components/ClientRouter.js: -------------------------------------------------------------------------------- 1 | import { withRouter } from 'next/router'; 2 | import {ClientRouter as AppBridgeClientRouter} from '@shopify/app-bridge-react'; 3 | 4 | function ClientRouter(props) { 5 | const {router} = props; 6 | return ; 7 | }; 8 | 9 | export default withRouter(ClientRouter); 10 | -------------------------------------------------------------------------------- /components/ResourceList.js: -------------------------------------------------------------------------------- 1 | import gql from 'graphql-tag'; 2 | import { Query } from 'react-apollo'; 3 | import { 4 | Card, 5 | ResourceList, 6 | Stack, 7 | TextStyle, 8 | Thumbnail, 9 | } from '@shopify/polaris'; 10 | import store from 'store-js'; 11 | import { Redirect } from '@shopify/app-bridge/actions'; 12 | import { Context } from '@shopify/app-bridge-react'; 13 | 14 | const GET_PRODUCTS_BY_ID = gql` 15 | query getProducts($ids: [ID!]!) { 16 | nodes(ids: $ids) { 17 | ... on Product { 18 | title 19 | handle 20 | descriptionHtml 21 | id 22 | images(first: 1) { 23 | edges { 24 | node { 25 | originalSrc 26 | altText 27 | } 28 | } 29 | } 30 | variants(first: 1) { 31 | edges { 32 | node { 33 | price 34 | id 35 | } 36 | } 37 | } 38 | } 39 | } 40 | } 41 | `; 42 | 43 | class ResourceListWithProducts extends React.Component { 44 | static contextType = Context; 45 | 46 | render() { 47 | const app = this.context; 48 | const redirectToProduct = () => { 49 | const redirect = Redirect.create(app); 50 | redirect.dispatch( 51 | Redirect.Action.APP, 52 | '/edit-products', 53 | ); 54 | }; 55 | 56 | const twoWeeksFromNow = new Date(Date.now() + 12096e5).toDateString(); 57 | return ( 58 | 59 | {({ data, loading, error }) => { 60 | if (loading) { return
Loading…
; } 61 | if (error) { return
{error.message}
; } 62 | console.log(data); 63 | return ( 64 | 65 | { 70 | const media = ( 71 | 83 | ); 84 | const price = item.variants.edges[0].node.price; 85 | return ( 86 | { 91 | store.set('item', item); 92 | redirectToProduct(); 93 | } 94 | } 95 | > 96 | 97 | 98 |

99 | 100 | {item.title} 101 | 102 |

103 |
104 | 105 |

${price}

106 |
107 | 108 |

Expires on {twoWeeksFromNow}

109 |
110 |
111 |
112 | ); 113 | }} 114 | /> 115 |
116 | ); 117 | }} 118 |
119 | ); 120 | } 121 | } 122 | 123 | export default ResourceListWithProducts; 124 | -------------------------------------------------------------------------------- /next.config.js: -------------------------------------------------------------------------------- 1 | require("dotenv").config(); 2 | const withCSS = require('@zeit/next-css'); 3 | const webpack = require('webpack'); 4 | 5 | const apiKey = JSON.stringify(process.env.SHOPIFY_API_KEY); 6 | 7 | module.exports = withCSS({ 8 | webpack: (config) => { 9 | const env = { API_KEY: apiKey }; 10 | config.plugins.push(new webpack.DefinePlugin(env)); 11 | return config; 12 | }, 13 | }); 14 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "shopify-demo-app-node-react", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1", 8 | "dev": "node server.js", 9 | "build": "next build", 10 | "start": "NODE_ENV=production node server.js" 11 | }, 12 | "repository": { 13 | "type": "git", 14 | "url": "git+https://github.com/Shopify/shopify-demo-app-node-react.git" 15 | }, 16 | "keywords": [], 17 | "author": "Shopify", 18 | "license": "MIT", 19 | "bugs": { 20 | "url": "https://github.com/Shopify/shopify-demo-app-node-react/issues" 21 | }, 22 | "homepage": "https://github.com/Shopify/shopify-demo-app-node-react#readme", 23 | "dependencies": { 24 | "@shopify/app-bridge": "^1.28.0", 25 | "@shopify/app-bridge-react": "^1.28.0", 26 | "@shopify/koa-shopify-auth": "^3.2.0", 27 | "@shopify/koa-shopify-graphql-proxy": "^4.1.0", 28 | "@shopify/koa-shopify-webhooks": "^2.6.0", 29 | "@shopify/polaris": "^5.15.0", 30 | "@zeit/next-css": "^1.0.1", 31 | "apollo-boost": "^0.4.9", 32 | "dotenv": "^8.2.0", 33 | "graphql": "^14.7.0", 34 | "graphql-tag": "^2.11.0", 35 | "isomorphic-fetch": "^3.0.0", 36 | "js-cookie": "^2.2.1", 37 | "koa": "^2.13.1", 38 | "koa-router": "^10.0.0", 39 | "koa-session": "^6.1.0", 40 | "next": "^10.0.5", 41 | "react": "^16.14.0", 42 | "react-apollo": "^3.1.5", 43 | "react-dom": "^16.14.0", 44 | "store-js": "^2.0.4" 45 | }, 46 | "devDependencies": { 47 | "eslint": "^5.16.0", 48 | "eslint-plugin-react": "^7.22.0", 49 | "eslint-plugin-shopify": "^27.0.1" 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /pages/_app.js: -------------------------------------------------------------------------------- 1 | import App from 'next/app'; 2 | import Head from 'next/head'; 3 | import { AppProvider } from '@shopify/polaris'; 4 | import { Provider } from '@shopify/app-bridge-react'; 5 | import Cookies from "js-cookie"; 6 | import '@shopify/polaris/dist/styles.css'; 7 | import translations from '@shopify/polaris/locales/en.json'; 8 | import ApolloClient from 'apollo-boost'; 9 | import { ApolloProvider } from 'react-apollo'; 10 | import ClientRouter from '../components/ClientRouter'; 11 | 12 | const client = new ApolloClient({ 13 | fetchOptions: { 14 | credentials: 'include', 15 | }, 16 | }); 17 | 18 | class MyApp extends App { 19 | render() { 20 | const { Component, pageProps } = this.props; 21 | const config = { apiKey: API_KEY, shopOrigin: Cookies.get("shopOrigin"), forceRedirect: true }; 22 | 23 | return ( 24 | 25 | 26 | Sample App 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | ); 39 | } 40 | } 41 | 42 | export default MyApp; 43 | -------------------------------------------------------------------------------- /pages/annotated-layout.js: -------------------------------------------------------------------------------- 1 | import { 2 | Button, 3 | Card, 4 | Form, 5 | FormLayout, 6 | Layout, 7 | Page, 8 | SettingToggle, 9 | Stack, 10 | TextField, 11 | TextStyle, 12 | } from '@shopify/polaris'; 13 | 14 | class AnnotatedLayout extends React.Component { 15 | state = { 16 | discount: '10%', 17 | enabled: false, 18 | }; 19 | 20 | render() { 21 | const { discount, enabled } = this.state; 22 | const contentStatus = enabled ? 'Disable' : 'Enable'; 23 | const textStatus = enabled ? 'enabled' : 'disabled'; 24 | 25 | return ( 26 | 27 | 28 | 32 | 33 |
34 | 35 | 41 | 42 | 45 | 46 | 47 |
48 |
49 |
50 | 54 | 61 | This setting is{' '} 62 | {textStatus}. 63 | 64 | 65 |
66 |
67 | ); 68 | } 69 | 70 | handleSubmit = () => { 71 | this.setState({ 72 | discount: this.state.discount, 73 | }); 74 | console.log('submission', this.state); 75 | }; 76 | 77 | handleChange = (field) => { 78 | return (value) => this.setState({ [field]: value }); 79 | }; 80 | 81 | handleToggle = () => { 82 | this.setState(({ enabled }) => { 83 | return { enabled: !enabled }; 84 | }); 85 | }; 86 | } 87 | 88 | export default AnnotatedLayout; 89 | -------------------------------------------------------------------------------- /pages/edit-products.js: -------------------------------------------------------------------------------- 1 | import { 2 | Banner, 3 | Card, 4 | DisplayText, 5 | Form, 6 | FormLayout, 7 | Frame, 8 | Layout, 9 | Page, 10 | PageActions, 11 | TextField, 12 | Toast, 13 | } from '@shopify/polaris'; 14 | import store from 'store-js'; 15 | import gql from 'graphql-tag'; 16 | import { Mutation } from 'react-apollo'; 17 | 18 | const UPDATE_PRICE = gql` 19 | mutation productVariantUpdate($input: ProductVariantInput!) { 20 | productVariantUpdate(input: $input) { 21 | product { 22 | title 23 | } 24 | productVariant { 25 | id 26 | price 27 | } 28 | } 29 | } 30 | `; 31 | 32 | class EditProduct extends React.Component { 33 | state = { 34 | discount: '', 35 | price: '', 36 | variantId: '', 37 | showToast: false, 38 | }; 39 | 40 | componentDidMount() { 41 | this.setState({ discount: this.itemToBeConsumed() }); 42 | } 43 | 44 | render() { 45 | const { name, price, discount, variantId } = this.state; 46 | return ( 47 | 50 | {(handleSubmit, { error, data }) => { 51 | const showError = error && ( 52 | {error.message} 53 | ); 54 | const showToast = data && data.productVariantUpdate && ( 55 | this.setState({ showToast: false })} 58 | /> 59 | ); 60 | return ( 61 | 62 | 63 | 64 | {showToast} 65 | 66 | {showError} 67 | 68 | 69 | {name} 70 |
71 | 72 | 73 | 74 | 81 | 88 | 89 |

90 | This sale price will expire in two weeks 91 |

92 |
93 |
94 | { 99 | const productVariableInput = { 100 | id: variantId, 101 | price: discount, 102 | }; 103 | handleSubmit({ 104 | variables: { input: productVariableInput }, 105 | }); 106 | }, 107 | }, 108 | ]} 109 | secondaryActions={[ 110 | { 111 | content: 'Remove discount', 112 | }, 113 | ]} 114 | /> 115 | 116 |
117 |
118 |
119 | 120 | ); 121 | }} 122 |
123 | ); 124 | } 125 | 126 | handleChange = (field) => { 127 | return (value) => this.setState({ [field]: value }); 128 | }; 129 | 130 | itemToBeConsumed = () => { 131 | const item = store.get('item'); 132 | const price = item.variants.edges[0].node.price; 133 | const variantId = item.variants.edges[0].node.id; 134 | const discounter = price * 0.1; 135 | this.setState({ price, variantId }); 136 | return (price - discounter).toFixed(2); 137 | }; 138 | } 139 | 140 | export default EditProduct; 141 | -------------------------------------------------------------------------------- /pages/index.js: -------------------------------------------------------------------------------- 1 | import { EmptyState, Layout, Page } from '@shopify/polaris'; 2 | import { ResourcePicker, TitleBar } from '@shopify/app-bridge-react'; 3 | import store from 'store-js'; 4 | import ResourceListWithProducts from '../components/ResourceList'; 5 | 6 | const img = 'https://cdn.shopify.com/s/files/1/0757/9955/files/empty-state.svg'; 7 | 8 | class Index extends React.Component { 9 | state = { open: false }; 10 | render() { 11 | const emptyState = !store.get('ids'); 12 | return ( 13 | 14 | this.setState({ open: true }), 19 | }} /> 20 | this.handleSelection(resources)} 25 | onCancel={() => this.setState({ open: false })} 26 | /> 27 | {emptyState ? ( 28 | 29 | this.setState({ open: true }), 34 | }} 35 | image={img} 36 | > 37 |

Select products to change their price temporarily.

38 |
39 |
40 | ) : ( 41 | 42 | )} 43 |
44 | ); 45 | } 46 | 47 | handleSelection = (resources) => { 48 | const idsFromResources = resources.selection.map((product) => product.id); 49 | this.setState({ open: false }); 50 | store.set('ids', idsFromResources); 51 | }; 52 | } 53 | 54 | export default Index; 55 | -------------------------------------------------------------------------------- /server.js: -------------------------------------------------------------------------------- 1 | require('isomorphic-fetch'); 2 | const dotenv = require('dotenv'); 3 | dotenv.config(); 4 | const Koa = require('koa'); 5 | const next = require('next'); 6 | const { default: createShopifyAuth } = require('@shopify/koa-shopify-auth'); 7 | const { verifyRequest } = require('@shopify/koa-shopify-auth'); 8 | const session = require('koa-session'); 9 | const { default: graphQLProxy } = require('@shopify/koa-shopify-graphql-proxy'); 10 | const { ApiVersion } = require('@shopify/koa-shopify-graphql-proxy'); 11 | const Router = require('koa-router'); 12 | const { receiveWebhook, registerWebhook } = require('@shopify/koa-shopify-webhooks'); 13 | const getSubscriptionUrl = require('./server/getSubscriptionUrl'); 14 | 15 | const port = parseInt(process.env.PORT, 10) || 3000; 16 | const dev = process.env.NODE_ENV !== 'production'; 17 | const app = next({ dev }); 18 | const handle = app.getRequestHandler(); 19 | 20 | const { 21 | SHOPIFY_API_SECRET_KEY, 22 | SHOPIFY_API_KEY, 23 | HOST, 24 | } = process.env; 25 | 26 | app.prepare().then(() => { 27 | const server = new Koa(); 28 | const router = new Router(); 29 | server.use(session({ sameSite: 'none', secure: true }, server)); 30 | server.keys = [SHOPIFY_API_SECRET_KEY]; 31 | 32 | server.use( 33 | createShopifyAuth({ 34 | apiKey: SHOPIFY_API_KEY, 35 | secret: SHOPIFY_API_SECRET_KEY, 36 | scopes: ['read_products', 'write_products'], 37 | async afterAuth(ctx) { 38 | const { shop, accessToken } = ctx.session; 39 | ctx.cookies.set("shopOrigin", shop, { 40 | httpOnly: false, 41 | secure: true, 42 | sameSite: 'none' 43 | }); 44 | const registration = await registerWebhook({ 45 | address: `${HOST}/webhooks/products/create`, 46 | topic: 'PRODUCTS_CREATE', 47 | accessToken, 48 | shop, 49 | apiVersion: ApiVersion.July20 50 | }); 51 | 52 | if (registration.success) { 53 | console.log('Successfully registered webhook!'); 54 | } else { 55 | console.log('Failed to register webhook', registration.result); 56 | } 57 | await getSubscriptionUrl(ctx, accessToken, shop); 58 | } 59 | }) 60 | ); 61 | 62 | const webhook = receiveWebhook({ secret: SHOPIFY_API_SECRET_KEY }); 63 | 64 | router.post('/webhooks/products/create', webhook, (ctx) => { 65 | console.log('received webhook: ', ctx.state.webhook); 66 | }); 67 | 68 | server.use(graphQLProxy({ version: ApiVersion.July20 })); 69 | 70 | router.get('(.*)', verifyRequest(), async (ctx) => { 71 | await handle(ctx.req, ctx.res); 72 | ctx.respond = false; 73 | ctx.res.statusCode = 200; 74 | }); 75 | 76 | server.use(router.allowedMethods()); 77 | server.use(router.routes()); 78 | 79 | server.listen(port, () => { 80 | console.log(`> Ready on http://localhost:${port}`); 81 | }); 82 | }); 83 | -------------------------------------------------------------------------------- /server/getSubscriptionUrl.js: -------------------------------------------------------------------------------- 1 | const getSubscriptionUrl = async (ctx, accessToken, shop) => { 2 | const query = JSON.stringify({ 3 | query: `mutation { 4 | appSubscriptionCreate( 5 | name: "Super Duper Plan" 6 | returnUrl: "${process.env.HOST}" 7 | test: true 8 | lineItems: [ 9 | { 10 | plan: { 11 | appUsagePricingDetails: { 12 | cappedAmount: { amount: 10, currencyCode: USD } 13 | terms: "$1 for 1000 emails" 14 | } 15 | } 16 | } 17 | { 18 | plan: { 19 | appRecurringPricingDetails: { 20 | price: { amount: 10, currencyCode: USD } 21 | } 22 | } 23 | } 24 | ] 25 | ) { 26 | userErrors { 27 | field 28 | message 29 | } 30 | confirmationUrl 31 | appSubscription { 32 | id 33 | } 34 | } 35 | }` 36 | }); 37 | 38 | const response = await fetch(`https://${shop}/admin/api/2019-07/graphql.json`, { 39 | method: 'POST', 40 | headers: { 41 | 'Content-Type': 'application/json', 42 | "X-Shopify-Access-Token": accessToken, 43 | }, 44 | body: query 45 | }) 46 | 47 | const responseJson = await response.json(); 48 | const confirmationUrl = responseJson.data.appSubscriptionCreate.confirmationUrl 49 | return ctx.redirect(confirmationUrl) 50 | }; 51 | 52 | module.exports = getSubscriptionUrl; --------------------------------------------------------------------------------