├── .env.example ├── .github ├── CODEOWNERS ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md ├── PULL_REQUEST_TEMPLATE.md ├── SECURITY.md ├── SUPPORT.md ├── dependabot.yml └── workflows │ └── ci.yml ├── .gitignore ├── .npmignore ├── .nvmrc ├── LICENSE ├── README.md ├── eslint.config.mjs ├── package-lock.json ├── package.json ├── public ├── app.css ├── dark-mode.css ├── examples │ ├── ach.html │ ├── afterpay.html │ ├── apple-pay.html │ ├── card-charge-and-store.html │ ├── card-charge-card-on-file.html │ ├── card-charge.html │ ├── card-store.html │ ├── card-styling-simple.html │ ├── cash-app-pay.html │ ├── gift-card.html │ ├── google-pay.html │ └── payment-request.html ├── favicon.ico └── index.html ├── server.js ├── server.test.js └── server ├── config.js ├── config.test.js ├── logger.js ├── logger.test.js ├── schema.js ├── schema.test.js ├── square.js └── square.test.js /.env.example: -------------------------------------------------------------------------------- 1 | # Secrets such as your Square Access Token should be defined in these .env files 2 | # Read more about storing configuration in the environment: https://www.npmjs.com/package/dotenv 3 | # 4 | # Remember to copy .env.example to .env.sandbox 5 | SQUARE_ACCESS_TOKEN= 6 | -------------------------------------------------------------------------------- /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | # CODEOWNERS syntax https://docs.github.com/en/github/creating-cloning-and-archiving-repositories/about-code-owners#codeowners-syntax 2 | # 3 | # Code owners are automatically requested for review when someone opens a pull request that modifies code that they own. 4 | # Code owners are not automatically requested to review draft pull requests 5 | # When you mark a draft pull request as ready for review, code owners are automatically notified. 6 | 7 | * @square/websdk 8 | -------------------------------------------------------------------------------- /.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, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and 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@squareup.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.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | 75 | For answers to common questions about this code of conduct, see 76 | https://www.contributor-covenant.org/faq 77 | -------------------------------------------------------------------------------- /.github/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | :+1::tada: First off, thanks for taking the time to contribute! :tada::+1: 4 | 5 | The following is a set of guidelines for contributing. These are mostly guidelines, not rules. Use your best judgment, and feel free to propose changes to this document in a pull request. 6 | 7 | #### Table Of Contents 8 | 9 | [Code of Conduct](#code-of-conduct) 10 | 11 | [Individual Contributor License Agreement (CLA)](#individual-contributor-license-agreement) 12 | 13 | ## Code of Conduct 14 | 15 | This project and everyone participating in it is governed by the [Code of Conduct](CODE_OF_CONDUCT.md). By participating, you are expected to uphold this code. 16 | 17 | ## Individual Contributor License Agreement 18 | 19 | Before your code can be accepted into the project you must also sign the 20 | [Individual Contributor License Agreement (CLA)](https://spreadsheets.google.com/spreadsheet/viewform?formkey=dDViT2xzUHAwRkI3X3k5Z0lQM091OGc6MQ&ndplr=1). 21 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: 'bug' 6 | assignees: '' 7 | --- 8 | 9 | **Describe the bug** 10 | A clear and concise description of what the bug is. 11 | 12 | **To Reproduce** 13 | Steps to reproduce the behavior: 14 | 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | 28 | - OS: [e.g. iOS] 29 | - Browser [e.g. chrome, safari] 30 | - Version [e.g. 22] 31 | 32 | **Smartphone (please complete the following information):** 33 | 34 | - Device: [e.g. iPhone6] 35 | - OS: [e.g. iOS8.1] 36 | - Browser [e.g. stock browser, safari] 37 | - Version [e.g. 22] 38 | 39 | **Additional context** 40 | Add any other context about the problem here. 41 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: 'enhancement' 6 | assignees: '' 7 | --- 8 | 9 | **Is your feature request related to a problem? Please describe.** 10 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 11 | 12 | **Describe the solution you'd like** 13 | A clear and concise description of what you want to happen. 14 | 15 | **Describe alternatives you've considered** 16 | A clear and concise description of any alternative solutions or features you've considered. 17 | 18 | **Additional context** 19 | Add any other context or screenshots about the feature request here. 20 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | Please explain the changes you made here. 2 | 3 | _Does this close any currently open issues?_ 4 | 5 | - [ ] [Individual Contributor License Agreement (CLA)](https://spreadsheets.google.com/spreadsheet/viewform?formkey=dDViT2xzUHAwRkI3X3k5Z0lQM091OGc6MQ&ndplr=1) signed 6 | -------------------------------------------------------------------------------- /.github/SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security 2 | 3 | Square recognizes the important contributions the security research community can make. We therefore encourage reporting security issues with the code contained in this repository. 4 | 5 | If you believe you have discovered a security vulnerability, please follow the guidelines at https://bugcrowd.com/squareopensource 6 | -------------------------------------------------------------------------------- /.github/SUPPORT.md: -------------------------------------------------------------------------------- 1 | # Support 2 | 3 | Working with Square APIs? 4 | 5 | - [Forums](https://developer.squareup.com/forums/) 6 | - [Slack](https://buildwithsquare.slack.com) 7 | - [Email](https://squareup.com/help/us/en/contact?panel=BF53A9C8EF68) 8 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates 5 | 6 | version: 2 7 | updates: 8 | - package-ecosystem: 'npm' 9 | directory: '/' 10 | schedule: 11 | interval: 'weekly' 12 | commit-message: 13 | prefix: 'chore: ' 14 | ignore: 15 | # remain on node-fetch 2.x as this repository is CJS, and 3.x is ESM-only 16 | # https://github.com/node-fetch/node-fetch/blob/HEAD/docs/v3-UPGRADE-GUIDE.md#converted-to-es-module 17 | - dependency-name: 'node-fetch' 18 | update-types: ['version-update:semver-major'] 19 | 20 | - package-ecosystem: 'github-actions' 21 | directory: '/' 22 | schedule: 23 | interval: 'weekly' 24 | commit-message: 25 | prefix: 'chore: ' 26 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: [main] 6 | pull_request: 7 | branches: [main] 8 | 9 | jobs: 10 | test: 11 | runs-on: ubuntu-latest 12 | 13 | steps: 14 | - name: Check out repository 15 | uses: actions/checkout@v4 16 | 17 | - name: Set up Node 18 | uses: actions/setup-node@v4 19 | with: 20 | node-version: '20' # keep in sync with .nvmrc 21 | 22 | - name: Get npm cache directory 23 | id: npm-cache 24 | run: | 25 | echo "::set-output name=dir::$(npm config get cache)" 26 | 27 | - name: Cache dependencies 28 | uses: actions/cache@v4.2.3 29 | with: 30 | path: ${{ steps.npm-cache.outputs.dir}} 31 | key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }} 32 | restore-keys: | 33 | ${{ runner.os }}-node- 34 | 35 | - name: Install dependencies 36 | run: npm ci 37 | 38 | - name: Run tests 39 | run: npm test 40 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # do not commit sensitive information to git 2 | .env* 3 | !.env.example 4 | 5 | # dependencies 6 | node_modules/ 7 | 8 | # dev tools 9 | .eslintcache 10 | .nyc_output 11 | coverage 12 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | .github 2 | .husky 3 | -------------------------------------------------------------------------------- /.nvmrc: -------------------------------------------------------------------------------- 1 | v20 2 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Web Payments Quickstart 2 | 3 | [![LICENSE](https://img.shields.io/badge/license-Apache%202-blue.svg)](https://github.com/square/tpl-oss-js/blob/main/LICENSE) 4 | [![CI](https://github.com/square/web-payments-quickstart/actions/workflows/ci.yml/badge.svg)](https://github.com/square/web-payments-quickstart/actions/workflows/ci.yml) 5 | 6 | Quickstart for using Square's Web Payments SDK 7 | 8 | - [Web Payments SDK Overview](https://developer.squareup.com/docs/web-payments/overview). 9 | - [API Documentation](https://developer.squareup.com/reference/sdks/web/payments). 10 | 11 | ## Getting Started 12 | 13 | Start by [cloning](https://docs.github.com/en/github/creating-cloning-and-archiving-repositories/cloning-a-repository) this repository. 14 | 15 | ```sh 16 | git clone https://github.com/square/web-payments-quickstart 17 | cd web-payments-quickstart 18 | ``` 19 | 20 | Install [Node.js](https://nodejs.org/en/about/releases/) which will include `npm`. This repository contains an `.nvmrc` file if you use [`nvm`](https://github.com/nvm-sh/nvm) to manage your node versions. 21 | 22 | Then, to install dependencies run: 23 | 24 | ```sh 25 | npm install 26 | ``` 27 | 28 | Run the development server. 29 | 30 | ```sh 31 | npm run dev 32 | ``` 33 | 34 | Finally, open [http://localhost:3000](http://localhost:3000). 35 | 36 | ### Credentials 37 | 38 | Before you can take a payment, you'll need to configure your developer credentials which can be found in the [Developer Dashboard](https://developer.squareup.com/apps). 39 | 40 | Copy `.env.example`to `.env.sandbox` 41 | 42 | ```sh 43 | cp .env.example .env.sandbox 44 | ``` 45 | 46 | Define `SQUARE_ACCESS_TOKEN` with your **Sandbox** Access Token from the Developer Dashboard. 47 | 48 | ```ini 49 | SQUARE_ACCESS_TOKEN=eX@mpl3_t0k3n 50 | ``` 51 | 52 | Restart your server to use this new value. 53 | 54 | _Remember: Do not add your access tokens to git!_ 55 | 56 | ## Development 57 | 58 | ### Setup 59 | 60 | When contributing to this project, you'll want to use the version of Node as defined by `.nvmrc`. You can use [nvm](https://github.com/nvm-sh/nvm) to install the correct version: 61 | 62 | ```sh 63 | nvm install $(cat .nvmrc) 64 | ``` 65 | 66 | Follow the "Getting Started" instructions above to install dependencies and verify your local server starts properly. 67 | 68 | ### Testing 69 | 70 | You can run all linters, tests, and builds like CI with `npm test`. 71 | 72 | ### Linting 73 | 74 | You can run all linters with `npm run lint`. 75 | 76 | #### ESLint 77 | 78 | [ESLint](https://eslint.org/) analyzes the code to find and fix problems. We use [eslint-plugin-square](https://github.com/square/eslint-plugin-square) for out-of-the-box configuration. 79 | 80 | ```sh 81 | npm run lint:eslint 82 | ``` 83 | 84 | ##### Fixing warnings and errors automatically 85 | 86 | ESLint can sometimes fix warnings and errors automatically for you with its [--fix option](https://eslint.org/docs/user-guide/command-line-interface#fixing-problems). 87 | 88 | ```sh 89 | npm run lint:eslint --fix 90 | ``` 91 | 92 | #### Prettier 93 | 94 | [Prettier](https://prettier.io/) is an opinionated code formatter. We use [@square/prettier-config](https://github.com/square/prettier-config) for those opinions. 95 | 96 | ```sh 97 | npm run lint:prettier 98 | ``` 99 | 100 | ##### Fixing code style issues 101 | 102 | If after running `npm run lint:prettier` you get a warning like, "Code style issues found in the above file(s). Forgot to run Prettier?", you can have Prettier fix them. 103 | 104 | ```sh 105 | npm run lint:prettier:fix 106 | ``` 107 | 108 | ## Continuous Integration 109 | 110 | [GitHub Actions](https://docs.github.com/en/actions) is used for our CI/CD workflows. See `.github/workflows` for details. 111 | 112 | ## License 113 | 114 | Copyright 2021 Square, Inc. 115 | 116 | Licensed under the Apache License, Version 2.0 (the "License"); 117 | you may not use this file except in compliance with the License. 118 | You may obtain a copy of the License at 119 | 120 | http://www.apache.org/licenses/LICENSE-2.0 121 | 122 | Unless required by applicable law or agreed to in writing, software 123 | distributed under the License is distributed on an "AS IS" BASIS, 124 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 125 | See the License for the specific language governing permissions and 126 | limitations under the License. 127 | -------------------------------------------------------------------------------- /eslint.config.mjs: -------------------------------------------------------------------------------- 1 | // eslint.config.js 2 | import js from '@eslint/js'; 3 | import globals from 'globals'; 4 | 5 | export default [ 6 | js.configs.recommended, 7 | { 8 | languageOptions: { 9 | sourceType: 'commonjs', 10 | globals: { 11 | ...globals.node, 12 | }, 13 | }, 14 | }, 15 | { 16 | files: ['eslint.config.mjs'], 17 | languageOptions: { 18 | sourceType: 'module', 19 | }, 20 | }, 21 | ]; 22 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@square/web-payments-quickstart", 3 | "version": "1.0.0", 4 | "description": "Quickstart for using Square's Web Payments SDK", 5 | "main": "server.js", 6 | "private": true, 7 | "type": "commonjs", 8 | "scripts": { 9 | "start": "NODE_ENV=production micro --listen tcp://0.0.0.0:${PORT-3000}", 10 | "start:sandbox": "NODE_ENV=sandbox micro --listen tcp://0.0.0.0:${PORT-3000}", 11 | "inspect": "node --inspect node_modules/.bin/micro-dev", 12 | "dev": "micro-dev", 13 | "lint": "npm-run-all --serial lint:*", 14 | "lint:eslint": "eslint --ignore-pattern .gitignore --cache .", 15 | "lint:prettier": "prettier --ignore-pattern .gitignore --check .", 16 | "lint:prettier:fix": "prettier --ignore-pattern .gitignore --write .", 17 | "test": "npm-run-all --serial lint test:*", 18 | "test:unit": "nyc ava" 19 | }, 20 | "repository": { 21 | "type": "git", 22 | "url": "git+https://github.com/square/square/web-payments-quickstart.git" 23 | }, 24 | "keywords": [ 25 | "template" 26 | ], 27 | "author": "", 28 | "license": "Apache-2.0", 29 | "bugs": { 30 | "url": "https://github.com/square/web-payments-quickstart/issues" 31 | }, 32 | "homepage": "https://github.com/square/web-payments-quickstart#readme", 33 | "dependencies": { 34 | "ajv": "^8.17.1", 35 | "async-retry": "^1.3.3", 36 | "debug": "^4.4.1", 37 | "dotenv": "^16.5.0", 38 | "micro": "9.3.4", 39 | "microrouter": "^3.1.3", 40 | "serve-handler": "^6.1.6", 41 | "square": "^39.1.1" 42 | }, 43 | "devDependencies": { 44 | "@square/prettier-config": "^1.0.0", 45 | "ava": "^6.4.0", 46 | "eslint": "^9.28.0", 47 | "eslint-plugin-ava": "^15.0.1", 48 | "eslint-plugin-prettier": "^5.4.1", 49 | "eslint-plugin-square": "^26.0.1", 50 | "husky": "^9.1.7", 51 | "lint-staged": "^16.1.0", 52 | "micro-dev": "^3.1.0", 53 | "node-fetch": "^2.7.0", 54 | "npm-run-all": "^4.1.5", 55 | "nyc": "^17.1.0", 56 | "prettier": "^3.5.3", 57 | "test-listen": "^1.1.0" 58 | }, 59 | "prettier": "@square/prettier-config", 60 | "eslintConfig": { 61 | "env": { 62 | "browser": true, 63 | "node": true 64 | }, 65 | "plugins": [ 66 | "square", 67 | "ava" 68 | ], 69 | "extends": [ 70 | "plugin:square/base", 71 | "plugin:ava/recommended" 72 | ] 73 | }, 74 | "husky": { 75 | "hooks": { 76 | "pre-commit": "lint-staged" 77 | } 78 | }, 79 | "lint-staged": { 80 | "*.js": "eslint --cache --fix", 81 | "*.{html,json,md,yml}": "prettier --write" 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /public/app.css: -------------------------------------------------------------------------------- 1 | * { 2 | box-sizing: border-box; 3 | } 4 | 5 | body { 6 | font-family: Arial, sans-serif; 7 | } 8 | 9 | #payment-form { 10 | max-width: 550px; 11 | min-width: 300px; 12 | margin: 150px auto; 13 | } 14 | 15 | .buyer-inputs { 16 | display: flex; 17 | gap: 20px; 18 | justify-content: space-between; 19 | border: none; 20 | margin: 0; 21 | padding: 0; 22 | } 23 | 24 | #card-container { 25 | margin-top: 45px; 26 | /* this height depends on the size of the container element */ 27 | /* We transition from a single row to double row at 485px */ 28 | /* Settting this min-height minimizes the impact of the card form loading */ 29 | min-height: 90px; 30 | } 31 | 32 | #gift-card-container { 33 | margin-top: 45px; 34 | min-height: 90px; 35 | } 36 | 37 | @media screen and (max-width: 500px) { 38 | #card-container { 39 | min-height: 140px; 40 | } 41 | } 42 | 43 | #ach-button { 44 | margin-top: 20px; 45 | } 46 | 47 | #landing-page-layout { 48 | width: 80%; 49 | margin: 150px auto; 50 | max-width: 1000px; 51 | } 52 | 53 | #its-working { 54 | color: #737373; 55 | } 56 | 57 | #example-container { 58 | width: 100%; 59 | border: 1px solid #b3b3b3; 60 | padding: 48px; 61 | margin: 32px 0; 62 | border-radius: 12px; 63 | } 64 | 65 | #example-list { 66 | display: flex; 67 | flex-direction: column; 68 | gap: 15px; 69 | } 70 | 71 | #customer-input { 72 | margin-bottom: 40px; 73 | } 74 | 75 | #card-input { 76 | margin-top: 0; 77 | margin-bottom: 40px; 78 | } 79 | 80 | h3 { 81 | margin: 0; 82 | } 83 | 84 | p { 85 | line-height: 24px; 86 | } 87 | 88 | label { 89 | font-size: 12px; 90 | width: 100%; 91 | } 92 | 93 | input { 94 | padding: 12px; 95 | width: 100%; 96 | border-radius: 5px; 97 | border-width: 1px; 98 | margin-top: 20px; 99 | font-size: 16px; 100 | border: 1px solid rgba(0, 0, 0, 0.15); 101 | } 102 | 103 | input:focus { 104 | border: 1px solid #006aff; 105 | } 106 | 107 | button { 108 | color: #ffffff; 109 | background-color: #006aff; 110 | border-radius: 5px; 111 | cursor: pointer; 112 | border-style: none; 113 | user-select: none; 114 | outline: none; 115 | font-size: 16px; 116 | font-weight: 500; 117 | line-height: 24px; 118 | padding: 12px; 119 | width: 100%; 120 | box-shadow: 1px; 121 | } 122 | 123 | button:active { 124 | background-color: rgb(0, 85, 204); 125 | } 126 | 127 | button:disabled { 128 | background-color: rgba(0, 0, 0, 0.05); 129 | color: rgba(0, 0, 0, 0.3); 130 | } 131 | 132 | #payment-status-container { 133 | display: flex; 134 | align-items: center; 135 | justify-content: center; 136 | border: 1px solid rgba(0, 0, 0, 0.05); 137 | box-sizing: border-box; 138 | border-radius: 50px; 139 | margin: 0 auto; 140 | width: 225px; 141 | height: 48px; 142 | visibility: hidden; 143 | } 144 | 145 | #payment-status-container.missing-credentials { 146 | width: 350px; 147 | } 148 | 149 | #payment-status-container.is-success:before { 150 | content: ''; 151 | background-color: #00b23b; 152 | width: 16px; 153 | height: 16px; 154 | margin-right: 16px; 155 | -webkit-mask: url("data:image/svg+xml,%3Csvg width='16' height='16' viewBox='0 0 16 16' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M8 16C12.4183 16 16 12.4183 16 8C16 3.58172 12.4183 0 8 0C3.58172 0 0 3.58172 0 8C0 12.4183 3.58172 16 8 16ZM11.7071 6.70711C12.0968 6.31744 12.0978 5.68597 11.7093 5.29509C11.3208 4.90422 10.6894 4.90128 10.2973 5.28852L11 6C10.2973 5.28852 10.2973 5.28853 10.2973 5.28856L10.2971 5.28866L10.2967 5.28908L10.2951 5.29071L10.2886 5.29714L10.2632 5.32224L10.166 5.41826L9.81199 5.76861C9.51475 6.06294 9.10795 6.46627 8.66977 6.90213C8.11075 7.4582 7.49643 8.07141 6.99329 8.57908L5.70711 7.29289C5.31658 6.90237 4.68342 6.90237 4.29289 7.29289C3.90237 7.68342 3.90237 8.31658 4.29289 8.70711L6.29289 10.7071C6.68342 11.0976 7.31658 11.0976 7.70711 10.7071L11.7071 6.70711Z' fill='black' fill-opacity='0.9'/%3E%3C/svg%3E"); 156 | mask: url("data:image/svg+xml,%3Csvg width='16' height='16' viewBox='0 0 16 16' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M8 16C12.4183 16 16 12.4183 16 8C16 3.58172 12.4183 0 8 0C3.58172 0 0 3.58172 0 8C0 12.4183 3.58172 16 8 16ZM11.7071 6.70711C12.0968 6.31744 12.0978 5.68597 11.7093 5.29509C11.3208 4.90422 10.6894 4.90128 10.2973 5.28852L11 6C10.2973 5.28852 10.2973 5.28853 10.2973 5.28856L10.2971 5.28866L10.2967 5.28908L10.2951 5.29071L10.2886 5.29714L10.2632 5.32224L10.166 5.41826L9.81199 5.76861C9.51475 6.06294 9.10795 6.46627 8.66977 6.90213C8.11075 7.4582 7.49643 8.07141 6.99329 8.57908L5.70711 7.29289C5.31658 6.90237 4.68342 6.90237 4.29289 7.29289C3.90237 7.68342 3.90237 8.31658 4.29289 8.70711L6.29289 10.7071C6.68342 11.0976 7.31658 11.0976 7.70711 10.7071L11.7071 6.70711Z' fill='black' fill-opacity='0.9'/%3E%3C/svg%3E"); 157 | } 158 | 159 | #payment-status-container.is-success:after { 160 | content: 'Payment successful'; 161 | font-size: 14px; 162 | line-height: 16px; 163 | } 164 | 165 | #payment-status-container.is-failure:before { 166 | content: ''; 167 | background-color: #cc0023; 168 | width: 16px; 169 | height: 16px; 170 | margin-right: 16px; 171 | -webkit-mask: url("data:image/svg+xml,%3Csvg width='16' height='16' viewBox='0 0 16 16' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M8 16C12.4183 16 16 12.4183 16 8C16 3.58172 12.4183 0 8 0C3.58172 0 0 3.58172 0 8C0 12.4183 3.58172 16 8 16ZM5.70711 4.29289C5.31658 3.90237 4.68342 3.90237 4.29289 4.29289C3.90237 4.68342 3.90237 5.31658 4.29289 5.70711L6.58579 8L4.29289 10.2929C3.90237 10.6834 3.90237 11.3166 4.29289 11.7071C4.68342 12.0976 5.31658 12.0976 5.70711 11.7071L8 9.41421L10.2929 11.7071C10.6834 12.0976 11.3166 12.0976 11.7071 11.7071C12.0976 11.3166 12.0976 10.6834 11.7071 10.2929L9.41421 8L11.7071 5.70711C12.0976 5.31658 12.0976 4.68342 11.7071 4.29289C11.3166 3.90237 10.6834 3.90237 10.2929 4.29289L8 6.58579L5.70711 4.29289Z' fill='black' fill-opacity='0.9'/%3E%3C/svg%3E%0A"); 172 | mask: url("data:image/svg+xml,%3Csvg width='16' height='16' viewBox='0 0 16 16' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M8 16C12.4183 16 16 12.4183 16 8C16 3.58172 12.4183 0 8 0C3.58172 0 0 3.58172 0 8C0 12.4183 3.58172 16 8 16ZM5.70711 4.29289C5.31658 3.90237 4.68342 3.90237 4.29289 4.29289C3.90237 4.68342 3.90237 5.31658 4.29289 5.70711L6.58579 8L4.29289 10.2929C3.90237 10.6834 3.90237 11.3166 4.29289 11.7071C4.68342 12.0976 5.31658 12.0976 5.70711 11.7071L8 9.41421L10.2929 11.7071C10.6834 12.0976 11.3166 12.0976 11.7071 11.7071C12.0976 11.3166 12.0976 10.6834 11.7071 10.2929L9.41421 8L11.7071 5.70711C12.0976 5.31658 12.0976 4.68342 11.7071 4.29289C11.3166 3.90237 10.6834 3.90237 10.2929 4.29289L8 6.58579L5.70711 4.29289Z' fill='black' fill-opacity='0.9'/%3E%3C/svg%3E%0A"); 173 | } 174 | 175 | #payment-status-container.is-failure:after { 176 | content: 'Payment failed'; 177 | font-size: 14px; 178 | line-height: 16px; 179 | } 180 | 181 | #payment-status-container.missing-credentials:before { 182 | content: ''; 183 | background-color: #cc0023; 184 | width: 16px; 185 | height: 16px; 186 | margin-right: 16px; 187 | -webkit-mask: url("data:image/svg+xml,%3Csvg width='16' height='16' viewBox='0 0 16 16' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M8 16C12.4183 16 16 12.4183 16 8C16 3.58172 12.4183 0 8 0C3.58172 0 0 3.58172 0 8C0 12.4183 3.58172 16 8 16ZM5.70711 4.29289C5.31658 3.90237 4.68342 3.90237 4.29289 4.29289C3.90237 4.68342 3.90237 5.31658 4.29289 5.70711L6.58579 8L4.29289 10.2929C3.90237 10.6834 3.90237 11.3166 4.29289 11.7071C4.68342 12.0976 5.31658 12.0976 5.70711 11.7071L8 9.41421L10.2929 11.7071C10.6834 12.0976 11.3166 12.0976 11.7071 11.7071C12.0976 11.3166 12.0976 10.6834 11.7071 10.2929L9.41421 8L11.7071 5.70711C12.0976 5.31658 12.0976 4.68342 11.7071 4.29289C11.3166 3.90237 10.6834 3.90237 10.2929 4.29289L8 6.58579L5.70711 4.29289Z' fill='black' fill-opacity='0.9'/%3E%3C/svg%3E%0A"); 188 | mask: url("data:image/svg+xml,%3Csvg width='16' height='16' viewBox='0 0 16 16' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M8 16C12.4183 16 16 12.4183 16 8C16 3.58172 12.4183 0 8 0C3.58172 0 0 3.58172 0 8C0 12.4183 3.58172 16 8 16ZM5.70711 4.29289C5.31658 3.90237 4.68342 3.90237 4.29289 4.29289C3.90237 4.68342 3.90237 5.31658 4.29289 5.70711L6.58579 8L4.29289 10.2929C3.90237 10.6834 3.90237 11.3166 4.29289 11.7071C4.68342 12.0976 5.31658 12.0976 5.70711 11.7071L8 9.41421L10.2929 11.7071C10.6834 12.0976 11.3166 12.0976 11.7071 11.7071C12.0976 11.3166 12.0976 10.6834 11.7071 10.2929L9.41421 8L11.7071 5.70711C12.0976 5.31658 12.0976 4.68342 11.7071 4.29289C11.3166 3.90237 10.6834 3.90237 10.2929 4.29289L8 6.58579L5.70711 4.29289Z' fill='black' fill-opacity='0.9'/%3E%3C/svg%3E%0A"); 189 | } 190 | 191 | #payment-status-container.missing-credentials:after { 192 | content: 'applicationId and/or locationId is incorrect'; 193 | font-size: 14px; 194 | line-height: 16px; 195 | } 196 | 197 | #payment-status-container.is-success.store-card-message:after { 198 | content: 'Store card successful'; 199 | } 200 | 201 | #payment-status-container.is-failure.store-card-message:after { 202 | content: 'Store card failed'; 203 | } 204 | 205 | #afterpay-button { 206 | height: 40px; 207 | } 208 | -------------------------------------------------------------------------------- /public/dark-mode.css: -------------------------------------------------------------------------------- 1 | .dark-mode { 2 | background-color: #080808; 3 | } 4 | 5 | .dark-mode button { 6 | background-color: #006aff; 7 | } 8 | 9 | .dark-mode #payment-status-container.is-success:after { 10 | color: #ffffff; 11 | } 12 | 13 | .dark-mode #payment-status-container.is-failure:after { 14 | color: #ffffff; 15 | } 16 | 17 | .dark-mode #payment-status-container.missing-credentials:after { 18 | color: #ffffff; 19 | } 20 | 21 | .dark-mode #payment-status-container { 22 | background-color: #2d2d2d; 23 | border-color: #2d2d2d; 24 | } 25 | -------------------------------------------------------------------------------- /public/examples/ach.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 9 | 161 | 162 | 163 |
164 |
165 | 175 | 176 | 186 |
187 | 188 |
189 |
190 | 191 | 192 | -------------------------------------------------------------------------------- /public/examples/afterpay.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 9 | 194 | 195 | 196 |
197 |
198 |
199 | 200 |
201 |
202 | 203 | 204 | -------------------------------------------------------------------------------- /public/examples/apple-pay.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 15 | 19 | 171 | 172 | 173 |
174 |
175 |
176 | 177 |
178 |
179 | 180 | 181 | -------------------------------------------------------------------------------- /public/examples/card-charge-and-store.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 9 | 183 | 184 | 185 |
186 | 195 |
196 | 197 |
198 |
199 | 200 | 201 | -------------------------------------------------------------------------------- /public/examples/card-charge-card-on-file.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 9 | 164 | 165 | 166 |
167 | 176 | 185 | 186 |
187 |
188 | 189 | 190 | -------------------------------------------------------------------------------- /public/examples/card-charge.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 9 | 142 | 143 | 144 |
145 |
146 | 147 |
148 |
149 | 150 | 151 | -------------------------------------------------------------------------------- /public/examples/card-store.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 9 | 147 | 148 | 149 |
150 | 159 |
160 | 161 |
162 |
163 | 164 | 165 | -------------------------------------------------------------------------------- /public/examples/card-styling-simple.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 10 | 163 | 164 | 165 |
166 |
167 | 168 |
169 |
170 | 171 | 172 | -------------------------------------------------------------------------------- /public/examples/cash-app-pay.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 10 | 128 | 129 | 130 |
131 |

Pay $1.00

132 |
133 |
134 |
135 | 136 | 137 | -------------------------------------------------------------------------------- /public/examples/gift-card.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 9 | 145 | 146 | 147 |
148 |
149 | 150 | 151 |
152 | 153 |
154 |
155 | 156 | 157 | -------------------------------------------------------------------------------- /public/examples/google-pay.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 9 | 156 | 157 | 158 |
159 |
160 |
161 |
162 | 163 | 164 | -------------------------------------------------------------------------------- /public/examples/payment-request.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 9 | 306 | 307 | 308 |
309 |
310 |
311 | 312 |
313 |
314 | 315 | 316 | -------------------------------------------------------------------------------- /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/square/web-payments-quickstart/9e8891dabe6db477481da2bb4a08563db3cc8004/public/favicon.ico -------------------------------------------------------------------------------- /public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 8 | 9 | Square Web Payments Quickstart 10 | 11 | 12 | 13 | 14 |
15 |

It's working!

16 |

Welcome to the Web Payments SDK Quickstart

17 |

18 | To get started, we recommend following our 19 | Quickstart guide. 20 |

21 |

22 | If you need more detail on a method or object, we also have a 23 | technical reference. 28 |

29 | 30 |
31 |

Examples

32 |

33 | These example implementations can be used as a reference or as the 34 | base for your own implementation. For these to work, you'll need to 35 | set your 36 | applicationId and locationId. 39 |

40 | 82 |
83 |
84 | 85 | 86 | -------------------------------------------------------------------------------- /server.js: -------------------------------------------------------------------------------- 1 | // micro provides http helpers 2 | const { createError, json, send } = require('micro'); 3 | // microrouter provides http server routing 4 | const { router, get, post } = require('microrouter'); 5 | // serve-handler serves static assets 6 | const staticHandler = require('serve-handler'); 7 | // async-retry will retry failed API requests 8 | const retry = require('async-retry'); 9 | 10 | // logger gives us insight into what's happening 11 | const logger = require('./server/logger'); 12 | // schema validates incoming requests 13 | const { 14 | validatePaymentPayload, 15 | validateCreateCardPayload, 16 | } = require('./server/schema'); 17 | // square provides the API client and error types 18 | const { ApiError, client: square } = require('./server/square'); 19 | 20 | async function createPayment(req, res) { 21 | const payload = await json(req); 22 | logger.debug(JSON.stringify(payload)); 23 | // We validate the payload for specific fields. You may disable this feature 24 | // if you would prefer to handle payload validation on your own. 25 | if (!validatePaymentPayload(payload)) { 26 | throw createError(400, 'Bad Request'); 27 | } 28 | 29 | await retry(async (bail, attempt) => { 30 | try { 31 | logger.debug('Creating payment', { attempt }); 32 | 33 | const payment = { 34 | idempotencyKey: payload.idempotencyKey, 35 | locationId: payload.locationId, 36 | sourceId: payload.sourceId, 37 | amountMoney: { 38 | // the expected amount is in cents, meaning this is $1.00. 39 | amount: '100', 40 | // If you are a non-US account, you must change the currency to match the country in which 41 | // you are accepting the payment. 42 | currency: 'USD', 43 | }, 44 | }; 45 | 46 | if (payload.customerId) { 47 | payment.customerId = payload.customerId; 48 | } 49 | 50 | // VerificationDetails is part of Secure Card Authentication. 51 | // This part of the payload is highly recommended (and required for some countries) 52 | // for 'unauthenticated' payment methods like Cards. 53 | if (payload.verificationToken) { 54 | payment.verificationToken = payload.verificationToken; 55 | } 56 | 57 | const { result, statusCode } = 58 | await square.paymentsApi.createPayment(payment); 59 | 60 | logger.info('Payment succeeded!', { result, statusCode }); 61 | 62 | send(res, statusCode, { 63 | success: true, 64 | payment: { 65 | id: result.payment.id, 66 | status: result.payment.status, 67 | receiptUrl: result.payment.receiptUrl, 68 | orderId: result.payment.orderId, 69 | }, 70 | }); 71 | } catch (ex) { 72 | if (ex instanceof ApiError) { 73 | // likely an error in the request. don't retry 74 | logger.error(ex.errors); 75 | bail(ex); 76 | } else { 77 | // IDEA: send to error reporting service 78 | logger.error(`Error creating payment on attempt ${attempt}: ${ex}`); 79 | throw ex; // to attempt retry 80 | } 81 | } 82 | }); 83 | } 84 | 85 | async function storeCard(req, res) { 86 | const payload = await json(req); 87 | 88 | if (!validateCreateCardPayload(payload)) { 89 | throw createError(400, 'Bad Request'); 90 | } 91 | 92 | await retry(async (bail, attempt) => { 93 | try { 94 | logger.debug('Storing card', { attempt }); 95 | 96 | const cardReq = { 97 | idempotencyKey: payload.idempotencyKey, 98 | sourceId: payload.sourceId, 99 | card: { 100 | customerId: payload.customerId, 101 | }, 102 | }; 103 | 104 | if (payload.verificationToken) { 105 | cardReq.verificationToken = payload.verificationToken; 106 | } 107 | 108 | const { result, statusCode } = await square.cardsApi.createCard(cardReq); 109 | 110 | logger.info('Store Card succeeded!', { result, statusCode }); 111 | 112 | // cast 64-bit values to string 113 | // to prevent JSON serialization error during send method 114 | result.card.expMonth = result.card.expMonth.toString(); 115 | result.card.expYear = result.card.expYear.toString(); 116 | result.card.version = result.card.version.toString(); 117 | 118 | send(res, statusCode, { 119 | success: true, 120 | card: result.card, 121 | }); 122 | } catch (ex) { 123 | if (ex instanceof ApiError) { 124 | // likely an error in the request. don't retry 125 | logger.error(ex.errors); 126 | bail(ex); 127 | } else { 128 | // IDEA: send to error reporting service 129 | logger.error( 130 | `Error creating card-on-file on attempt ${attempt}: ${ex}`, 131 | ); 132 | throw ex; // to attempt retry 133 | } 134 | } 135 | }); 136 | } 137 | 138 | // serve static files like index.html and favicon.ico from public/ directory 139 | async function serveStatic(req, res) { 140 | logger.debug('Handling request', req.path); 141 | await staticHandler(req, res, { 142 | public: 'public', 143 | }); 144 | } 145 | 146 | // export routes to be served by micro 147 | module.exports = router( 148 | post('/payment', createPayment), 149 | post('/card', storeCard), 150 | get('/*', serveStatic), 151 | ); 152 | -------------------------------------------------------------------------------- /server.test.js: -------------------------------------------------------------------------------- 1 | // ava is a test runner for Node.js that isolates tests 2 | const test = require('ava'); 3 | // micro is a minimal http framework (what's run by `npm start`) 4 | const micro = require('micro'); 5 | // test-listen creates URLs with ephimeral ports ideal for isolated tests 6 | const listen = require('test-listen'); 7 | // node-fetch brings window.fetch to Node.js 8 | const fetch = require('node-fetch'); 9 | 10 | const main = require('.'); 11 | 12 | // serveStatic 13 | [ 14 | ['/', /Quickstart/], 15 | ['/index.html', /sandbox\.web\.squarecdn/], 16 | ['/favicon.ico', /.+/], 17 | ].forEach(([path, re]) => { 18 | test(`serves ${path}`, async (t) => { 19 | const service = micro(main); 20 | const url = await listen(service); 21 | const res = await fetch(url + path); 22 | t.true(res.ok); 23 | 24 | const body = await res.text(); 25 | t.regex(body, re); 26 | 27 | service.close(t.falsy); 28 | }); 29 | }); 30 | 31 | // createPayment 32 | test('createPayment errors with invalid payload', async (t) => { 33 | const service = micro(main); 34 | const url = await listen(service); 35 | const res = await fetch(`${url}/payment`, { 36 | method: 'post', 37 | headers: { 'Content-Type': 'application/json' }, 38 | body: JSON.stringify({ 39 | wrong: true, 40 | }), 41 | }); 42 | 43 | // expect 'bad request' response because body is wrong (literally) 44 | t.false(res.ok); 45 | t.is(res.status, 400); 46 | 47 | service.close(t.falsy); 48 | }); 49 | 50 | // storeCard 51 | test('storeCard errors with invalid payload', async (t) => { 52 | const service = micro(main); 53 | const url = await listen(service); 54 | const res = await fetch(`${url}/card`, { 55 | method: 'post', 56 | headers: { 'Content-Type': 'application/json' }, 57 | body: JSON.stringify({ 58 | wrong: true, 59 | }), 60 | }); 61 | 62 | // expect 'bad request' response because body is wrong (literally) 63 | t.false(res.ok); 64 | t.is(res.status, 400); 65 | 66 | service.close(t.falsy); 67 | }); 68 | -------------------------------------------------------------------------------- /server/config.js: -------------------------------------------------------------------------------- 1 | const { config } = require('dotenv'); 2 | 3 | const logger = require('./logger'); 4 | 5 | // package.json sets NODE_ENV in its scripts 6 | const isProduction = process.env.NODE_ENV === 'production'; 7 | 8 | // load configuration based on environment 9 | const { error, parsed } = config({ 10 | path: isProduction ? '.env.production' : '.env.sandbox', 11 | }); 12 | 13 | if (error) { 14 | // likely file missing 15 | logger.error(`Error loading configuration: ${error}`); 16 | } 17 | 18 | // PROTIP: get more insight by running in debug mode: `DEBUG=* npm run dev` 19 | logger.debug('Parsed configuration:', parsed); 20 | 21 | // export secrets stored in .env.production or .env.sandbox (based on .env.example) 22 | module.exports = { 23 | ...parsed, 24 | isProduction, 25 | }; 26 | -------------------------------------------------------------------------------- /server/config.test.js: -------------------------------------------------------------------------------- 1 | const test = require('ava'); 2 | 3 | const config = require('./config'); 4 | 5 | test('exports isProduction', (t) => { 6 | t.true(typeof config.isProduction === 'boolean'); 7 | }); 8 | -------------------------------------------------------------------------------- /server/logger.js: -------------------------------------------------------------------------------- 1 | const debug = require('debug'); 2 | 3 | module.exports = { 4 | // IDEA: replace console with more robust logger 5 | info: console.info, 6 | error: console.error, 7 | debug: debug('sq-web-pay'), 8 | }; 9 | -------------------------------------------------------------------------------- /server/logger.test.js: -------------------------------------------------------------------------------- 1 | const test = require('ava'); 2 | 3 | const logger = require('./logger'); 4 | 5 | ['info', 'error', 'debug'].forEach((fn) => { 6 | test(`exports ${fn}`, (t) => { 7 | t.true(typeof logger[fn] === 'function'); 8 | }); 9 | }); 10 | -------------------------------------------------------------------------------- /server/schema.js: -------------------------------------------------------------------------------- 1 | const Ajv = require('ajv/dist/jtd').default; 2 | 3 | const ajv = new Ajv(); // options can be passed, e.g. {allErrors: true} 4 | 5 | // JSON Type Definition https://ajv.js.org/guide/getting-started.html#basic-data-validation 6 | const paymentSchema = { 7 | properties: { 8 | sourceId: { type: 'string' }, 9 | locationId: { type: 'string' }, 10 | idempotencyKey: { type: 'string' }, 11 | }, 12 | optionalProperties: { 13 | amount: { type: 'uint32' }, 14 | customerId: { type: 'string' }, 15 | verificationToken: { type: 'string' }, 16 | }, 17 | }; 18 | 19 | const cardSchema = { 20 | properties: { 21 | sourceId: { type: 'string' }, 22 | locationId: { type: 'string' }, 23 | customerId: { type: 'string' }, 24 | idempotencyKey: { type: 'string' }, 25 | }, 26 | optionalProperties: { 27 | verificationToken: { type: 'string' }, 28 | }, 29 | }; 30 | 31 | module.exports = { 32 | validatePaymentPayload: ajv.compile(paymentSchema), 33 | validateCreateCardPayload: ajv.compile(cardSchema), 34 | }; 35 | -------------------------------------------------------------------------------- /server/schema.test.js: -------------------------------------------------------------------------------- 1 | const test = require('ava'); 2 | 3 | const schema = require('./schema'); 4 | 5 | test('validatePaymentPayload returns true if valid payload', (t) => { 6 | t.true( 7 | schema.validatePaymentPayload({ 8 | amount: 100, 9 | locationId: 'LKYXSPGPXK05M', 10 | sourceId: 't0k3n', 11 | idempotencyKey: 'idempot5cyK3y', 12 | }), 13 | ); 14 | }); 15 | 16 | test('validatePaymentPayload returns false if invalid amount', (t) => { 17 | t.false( 18 | schema.validatePaymentPayload({ 19 | amount: '$2.34', 20 | locationId: 'LKYXSPGPXK05M', 21 | sourceId: 't0k3n', 22 | }), 23 | ); 24 | }); 25 | 26 | test('validatePaymentPayload returns false if incomplete payload', (t) => { 27 | t.false( 28 | schema.validatePaymentPayload({ 29 | locationId: 'LKYXSPGPXK05M', 30 | }), 31 | ); 32 | }); 33 | 34 | test('validatePaymentPayload returns false if empty payload', (t) => { 35 | t.false(schema.validatePaymentPayload({})); 36 | }); 37 | 38 | test('validateCreateCardPayload returns true if valid payload', (t) => { 39 | t.true( 40 | schema.validateCreateCardPayload({ 41 | sourceId: 't0k3n', 42 | locationId: 'LKYXSPGPXK05M', 43 | customerId: 'customer123', 44 | idempotencyKey: 'idempot5cyK3y', 45 | }), 46 | ); 47 | }); 48 | 49 | test('validateCreateCardPayload returns false if missing sourceId', (t) => { 50 | t.false( 51 | schema.validateCreateCardPayload({ 52 | locationId: 'LKYXSPGPXK05M', 53 | customerId: 'customer123', 54 | }), 55 | ); 56 | }); 57 | 58 | test('validateCreateCardPayload returns false if missing customerId', (t) => { 59 | t.false( 60 | schema.validateCreateCardPayload({ 61 | sourceId: 't0k3n', 62 | locationId: 'LKYXSPGPXK05M', 63 | }), 64 | ); 65 | }); 66 | 67 | test('validateCreateCardPayload returns false if empty payload', (t) => { 68 | t.false(schema.validateCreateCardPayload({})); 69 | }); 70 | -------------------------------------------------------------------------------- /server/square.js: -------------------------------------------------------------------------------- 1 | const { ApiError, Client, Environment } = require('square'); 2 | 3 | const { isProduction, SQUARE_ACCESS_TOKEN } = require('./config'); 4 | 5 | const client = new Client({ 6 | environment: isProduction ? Environment.Production : Environment.Sandbox, 7 | accessToken: SQUARE_ACCESS_TOKEN, 8 | }); 9 | 10 | module.exports = { ApiError, client }; 11 | -------------------------------------------------------------------------------- /server/square.test.js: -------------------------------------------------------------------------------- 1 | const test = require('ava'); 2 | 3 | const square = require('./square'); 4 | 5 | test('exports client', (t) => { 6 | t.true(typeof square.client.paymentsApi.createPayment === 'function'); 7 | }); 8 | --------------------------------------------------------------------------------