├── .babelrc ├── .eslintrc.yml ├── .github ├── ISSUE_TEMPLATE │ ├── bug_report.yaml │ ├── config.yml │ └── feature_request.yaml └── workflows │ ├── build.yml │ ├── check-semver.yml │ ├── linting.yml │ ├── publish.yml │ ├── release-on-push.yml │ └── test.yml ├── .gitignore ├── .npmignore ├── .prettierrc ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── SECURITY.md ├── jest.config.ts ├── package.json ├── rollup.config.mjs ├── src ├── __tests__ │ ├── index.test.ts │ └── shared.test.ts ├── constants │ ├── cdn-information.ts │ └── checkout-events.ts ├── index.ts └── utils │ ├── initialize.ts │ └── shared.ts ├── tsconfig.json ├── types ├── checkout │ ├── checkout.d.ts │ ├── customer.d.ts │ ├── events.d.ts │ └── retain.d.ts ├── index.d.ts ├── price-preview │ └── price-preview.d.ts ├── shared │ ├── country-code.d.ts │ ├── currency-code.d.ts │ └── shared.d.ts └── transaction-preview │ └── transaction-preview.d.ts └── yarn.lock /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": ["@babel/preset-env"] 3 | } 4 | -------------------------------------------------------------------------------- /.eslintrc.yml: -------------------------------------------------------------------------------- 1 | env: 2 | browser: true 3 | es2021: true 4 | extends: 5 | - eslint:recommended 6 | - plugin:@typescript-eslint/eslint-recommended 7 | - plugin:@typescript-eslint/recommended 8 | parserOptions: 9 | ecmaVersion: latest 10 | sourceType: module 11 | rules: 12 | { 13 | no-unused-vars: 'off', 14 | '@typescript-eslint/no-unused-vars': ['warn', { argsIgnorePattern: '^_', varsIgnorePattern: '^_' }], 15 | } 16 | ignorePatterns: 17 | - rollup.config.mjs 18 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.yaml: -------------------------------------------------------------------------------- 1 | name: Bug report 2 | description: Report a problem. 3 | title: "[Bug]: " 4 | labels: ["bug"] 5 | body: 6 | - type: markdown 7 | attributes: 8 | value: | 9 | Use this form to report a bug or problem with Paddle.js or the Paddle.js wrapper. 10 | 11 | Remember to remove sensitive information from screenshots, videos, or code samples before submitting. 12 | 13 | **Do not create issues for potential security vulnerabilities.** Please see the [Paddle Vulnerability Disclosure Policy](https://www.paddle.com/vulnerability-disclosure-policy) and report any vulnerabilities [using our form](https://vdp.paddle.com/p/Report-a-Vulnerability). 14 | 15 | Thanks for helping to make the Paddle platform better for everyone! 16 | - type: textarea 17 | id: description 18 | attributes: 19 | label: What happened? 20 | description: Describe the bug in a sentence or two. Feel free to add screenshots or a video to better explain! 21 | validations: 22 | required: true 23 | - type: textarea 24 | id: reproduce 25 | attributes: 26 | label: Steps to reproduce 27 | description: Explain how to reproduce this issue. We prefer a step-by-step walkthrough, where possible. 28 | value: | 29 | 1. 30 | 2. 31 | 3. 32 | ... 33 | validations: 34 | required: true 35 | - type: textarea 36 | id: expected-behavior 37 | attributes: 38 | label: What did you expect to happen? 39 | description: Tell us what should happen when you encounter this bug. 40 | - type: input 41 | id: environment 42 | attributes: 43 | label: How are you integrating? 44 | description: Are you using React or another JavaScript framework? Is there anything else we should know about your environment? 45 | - type: textarea 46 | id: logs 47 | attributes: 48 | label: Logs 49 | description: Copy and paste any relevant logs. This is automatically formatted into code, so no need for backticks. 50 | render: shell -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/config.yml: -------------------------------------------------------------------------------- 1 | blank_issues_enabled: false 2 | contact_links: 3 | - name: Get help 4 | url: https://developer.paddle.com/ 5 | about: For help with Paddle.js or building your integration, contact our support team at [sellers@paddle.com](mailto:sellers@paddle.com). 6 | - name: Report a vulnerability 7 | url: https://vdp.paddle.com/p/Report-a-Vulnerability 8 | about: Please see the [Paddle Vulnerability Disclosure Policy](https://www.paddle.com/vulnerability-disclosure-policy) and report any vulnerabilities using https://vdp.paddle.com/p/Report-a-Vulnerability. 9 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.yaml: -------------------------------------------------------------------------------- 1 | name: Feature request 2 | description: Suggest an idea. 3 | title: "[Feature]: " 4 | labels: ["feature"] 5 | body: 6 | - type: markdown 7 | attributes: 8 | value: | 9 | Use this form to send us suggestions for improvements to Paddle.js or the Paddle.js wrapper. 10 | 11 | For general feedback about the Paddle API or developer platform, contact our DX team directly 12 | at [team-dx@paddle.com](mailto:team-dx@paddle.com). 13 | 14 | Thanks for helping to make the Paddle platform better for everyone! 15 | - type: textarea 16 | id: request 17 | attributes: 18 | label: Tell us about your feature request 19 | description: Describe what you'd like to see added or improved. 20 | validations: 21 | required: true 22 | - type: textarea 23 | id: problem 24 | attributes: 25 | label: What problem are you looking to solve? 26 | description: Tell us how and why would implementing your suggestion would help. 27 | validations: 28 | required: true 29 | - type: textarea 30 | id: additional-information 31 | attributes: 32 | label: Additional context 33 | description: Add any other context, screenshots, or illustrations about your suggestion here. 34 | - type: dropdown 35 | id: priority 36 | attributes: 37 | label: How important is this suggestion to you? 38 | options: 39 | - Nice to have 40 | - Important 41 | - Critical 42 | default: 0 43 | validations: 44 | required: true 45 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | - v1.X 8 | pull_request: 9 | branches: 10 | - main 11 | - v1.X 12 | 13 | concurrency: 14 | group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.head_ref || github.ref }} 15 | cancel-in-progress: true 16 | 17 | jobs: 18 | run-build: 19 | name: Run build 20 | runs-on: ubuntu-latest 21 | 22 | permissions: 23 | actions: write 24 | 25 | steps: 26 | - name: Check out git repository 27 | uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3 28 | 29 | - name: Set up Node.js 30 | uses: actions/setup-node@1a4442cacd436585916779262731d5b162bc6ec7 # v3 31 | with: 32 | node-version: lts/* 33 | cache: "yarn" 34 | 35 | - name: Install yarn dependencies 36 | run: yarn install 37 | 38 | - name: Build 39 | run: yarn build -------------------------------------------------------------------------------- /.github/workflows/check-semver.yml: -------------------------------------------------------------------------------- 1 | name: Label Checker 2 | 3 | on: 4 | pull_request: 5 | types: 6 | - opened 7 | - synchronize 8 | - reopened 9 | - labeled 10 | - unlabeled 11 | 12 | jobs: 13 | check_labels: 14 | name: Check labels 15 | runs-on: ubuntu-latest 16 | steps: 17 | - uses: docker://agilepathway/pull-request-label-checker:v1.6.13 18 | with: 19 | one_of: norelease,release:major,release:minor,release:patch 20 | repo_token: ${{ secrets.GITHUB_TOKEN }} -------------------------------------------------------------------------------- /.github/workflows/linting.yml: -------------------------------------------------------------------------------- 1 | name: Lint 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | - v1.X 8 | pull_request: 9 | branches: 10 | - main 11 | - v1.X 12 | 13 | concurrency: 14 | group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.head_ref || github.ref }} 15 | cancel-in-progress: true 16 | 17 | jobs: 18 | run-linters: 19 | name: Run linters 20 | runs-on: ubuntu-latest 21 | 22 | permissions: 23 | actions: write 24 | 25 | steps: 26 | - name: Check out git repository 27 | uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3 28 | 29 | - name: Set up Node.js 30 | uses: actions/setup-node@1a4442cacd436585916779262731d5b162bc6ec7 # v3 31 | with: 32 | node-version: lts/* 33 | cache: "yarn" 34 | 35 | - name: Install yarn dependencies 36 | run: yarn install 37 | 38 | - name: Lint 39 | run: | 40 | yarn lint 41 | yarn prettier -------------------------------------------------------------------------------- /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | name: Publish 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | - v1.X 8 | 9 | jobs: 10 | run-publish: 11 | name: Run publish 12 | runs-on: ubuntu-latest 13 | 14 | permissions: 15 | contents: read 16 | actions: write 17 | 18 | steps: 19 | - name: Check out git repository 20 | uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4 21 | 22 | - name: Set up Node.js 23 | uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # v4 24 | with: 25 | node-version: lts/* 26 | cache: 'yarn' 27 | registry-url: 'https://registry.npmjs.org' 28 | 29 | - name: Install yarn dependencies 30 | run: yarn install 31 | 32 | - name: Build 33 | run: yarn build 34 | 35 | - name: Test 36 | run: yarn test 37 | 38 | - name: Check version and publish 39 | run: | 40 | PACKAGE_NAME=$(node -p "require('./package.json').name") 41 | CURRENT_VERSION=$(node -p "require('./package.json').version") 42 | 43 | # Check if version exists in npm registry 44 | if npm view "${PACKAGE_NAME}@${CURRENT_VERSION}" version &>/dev/null; then 45 | echo "Version $CURRENT_VERSION already published, skipping" 46 | exit 0 47 | fi 48 | 49 | if [[ "$CURRENT_VERSION" =~ (next) ]]; then 50 | yarn publish:next 51 | else 52 | yarn publish:latest 53 | fi 54 | env: 55 | NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} 56 | -------------------------------------------------------------------------------- /.github/workflows/release-on-push.yml: -------------------------------------------------------------------------------- 1 | name: Release on Push 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | - v1.X 8 | 9 | jobs: 10 | release_on_push: 11 | runs-on: ubuntu-latest 12 | env: 13 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 14 | steps: 15 | - uses: rymndhng/release-on-push-action@aebba2bbce07a9474bf95e8710e5ee8a9e922fe2 # v0.28.0 16 | with: 17 | bump_version_scheme: norelease 18 | use_github_release_notes: true 19 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Test 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | - v1.X 8 | pull_request: 9 | branches: 10 | - main 11 | - v1.X 12 | 13 | concurrency: 14 | group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.head_ref || github.ref }} 15 | cancel-in-progress: true 16 | 17 | jobs: 18 | run-test: 19 | name: Run test 20 | runs-on: ubuntu-latest 21 | 22 | permissions: 23 | actions: write 24 | 25 | steps: 26 | - name: Check out git repository 27 | uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3 28 | 29 | - name: Set up Node.js 30 | uses: actions/setup-node@1a4442cacd436585916779262731d5b162bc6ec7 # v3 31 | with: 32 | node-version: lts/* 33 | cache: "yarn" 34 | 35 | - name: Install yarn dependencies 36 | run: yarn install 37 | 38 | - name: Test 39 | run: yarn test -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Cache 2 | .DS_Store 3 | .cache 4 | .idea 5 | 6 | # generated files 7 | dist 8 | node_modules 9 | coverage 10 | 11 | #logs 12 | *.log 13 | .vim 14 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | * 2 | !dist/**/* 3 | !types/**/* -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "semi": true, 4 | "tabWidth": 2, 5 | "printWidth": 120, 6 | "trailingComma": "all", 7 | "bracketSpacing": true 8 | } 9 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 6 | 7 | Check our main [developer changelog](https://developer.paddle.com/?utm_source=dx&utm_medium=paddle-js-wrapper) for information about changes to the Paddle Billing platform, the Paddle API, and other developer tools. 8 | 9 | ## 1.4.0-next.0 - 2025-03-04 10 | 11 | ### Added 12 | 13 | - Added support for `customData` in `Paddle.Checkout.updateCheckout()` function. 14 | 15 | --- 16 | 17 | ## 1.3.2-next.0 - 2024-11-06 18 | 19 | ### Fixed 20 | 21 | - Add return type to `getPaddleInstance` type definition 22 | 23 | --- 24 | 25 | ## 1.3.1-next.0 - 2024-10-30 26 | 27 | ### Fixed 28 | 29 | - Fallback to window.Paddle if Billing or Classic cannot be found 30 | 31 | --- 32 | 33 | ## 1.3.0-next.0 - 2024-10-22 34 | 35 | ### Added 36 | 37 | - Support to include paddle classic concurrently with paddle billing 38 | - Build as UMD to allow script imports 39 | - Added `getPaddleInstance` to fetch classic or billing instance - version can be `classic` or `v1` 40 | 41 | --- 42 | 43 | ## 1.2.3-next.0 - 2024-10-01 44 | 45 | ### Fixed 46 | 47 | - `Checkout.updateCheckout` `discountId` and `discountCode` can both be `null`. 48 | 49 | ### Added 50 | 51 | - Added `variant` to checkout settings. 52 | 53 | --- 54 | 55 | ## 1.2.2-next.0 - 2024-09-27 56 | 57 | ### Fixed 58 | 59 | - Updated `customData` checkout type to allow nested objects. 60 | 61 | --- 62 | 63 | ## 1.1.1-next.1 - 2024-07-29 64 | 65 | ### Fixed 66 | 67 | - Added missing `price_name` property to checkout events callback. 68 | 69 | --- 70 | 71 | ## 1.1.1-next.0 - 2024-06-06 72 | 73 | ### Added 74 | 75 | - Added a new property(`allowDiscountRemoval`) to restrict users from removing discounts. 76 | 77 | --- 78 | 79 | ## 1.1.0-next.0 - 2024-05-28 80 | 81 | ### Fixed 82 | 83 | - Added missing type definition for `Paddle.Checkout.updateCheckout` [function](https://developer.paddle.com/paddlejs/methods/paddle-checkout-updatecheckout?utm_source=dx&utm_medium=paddle-js-wrapper). 84 | 85 | --- 86 | 87 | ## 1.1.0 - 2024-05-16 88 | 89 | ### Added 90 | 91 | - Added changelog. 92 | 93 | --- 94 | 95 | ## 1.0.3 - 2024-03-14 96 | 97 | ### Changed 98 | 99 | - Update type of `currency_code` from `string` to string literal types. 100 | 101 | ### Added 102 | 103 | - Added types support to pass non-catalog prices to `Paddle.TransactionPreview()` function 104 | 105 | --- 106 | 107 | ## 1.0.2 - 2024-02-27 108 | 109 | ### Added 110 | 111 | - Added `Paddle.Initialize` function, Functionally it is the same as `Paddle.Setup`. 112 | - Added `Paddle.Update` function to update `pwCustomer` or `eventCallback` after initializing Paddle JS. See [related changelog](https://developer.paddle.com/changelog/2024/paddle-update-paddle-initialize-paddlejs?utm_source=dx&utm_medium=paddle-js-wrapper). 113 | - Added `Paddle.Initialized` flag to help identify if PaddleJS is already initialized. 114 | 115 | ### Deprecated 116 | 117 | - Deprecated `Paddle.Setup` in favour of `Paddle.Initialize` field. 118 | 119 | --- 120 | 121 | ## 1.0.1 - 2024-02-20 122 | 123 | ### Changed 124 | 125 | - Removed `early access` warning message from `README.md` 126 | 127 | --- 128 | 129 | ## 1.0.0 - 2024-02-20 130 | 131 | ### Changed 132 | 133 | - Updated version to `1.0.0` 134 | 135 | --- 136 | 137 | ## 0.5.5 - 2024-01-10 138 | 139 | ### Changed 140 | 141 | - Removed `crossOrigin` header from the injected `script` tag. 142 | 143 | --- 144 | 145 | ## 0.5.4 - 2023-12-29 146 | 147 | ### Changed 148 | 149 | - Updated Example in `README.md` to include `quantity`. 150 | 151 | --- 152 | 153 | ## 0.5.3 - 2023-12-21 154 | 155 | ### Added 156 | 157 | - Added types support for `Paddle.TransactionPreview()`, see [related changelog](https://developer.paddle.com/changelog/2024/paddle-js-transaction-preview?utm_source=dx&utm_medium=paddle-js-wrapper). 158 | - Added types support for `Paddle.Retain.*` functions, see [related changelog](https://developer.paddle.com/changelog/2023/cancellation-flows-retain?utm_source=dx&utm_medium=paddle-js-wrapper). 159 | - Added types support to accept `allowedPaymentMethods` in `Paddle.Checkout.open()`, see [related changelog](https://developer.paddle.com/changelog/2023/preselect-payment-methods-checkout?utm_source=dx&utm_medium=paddle-js-wrapper). 160 | 161 | --- 162 | 163 | ## 0.5.2 - 2023-11-22 164 | 165 | ### Changed 166 | 167 | - Updated Example in `README.md` to use token instead of seller ID. 168 | 169 | --- 170 | 171 | ## 0.5.1 - 2023-10-30 172 | 173 | > **Breaking changes:** This version includes breaking changes. It is called out below. 174 | 175 | ### Changed 176 | 177 | - **Breaking change:** Changed properties of `Paddle.PricePreview()` from `snake_case` to `camelCase`. This matches JavaScript conventions for field names. 178 | 179 | --- 180 | 181 | ## 0.5.0 - 2023-10-23 182 | 183 | ### Added 184 | 185 | - Added support for `Paddle.PricePreview()`, see [related changelog](https://developer.paddle.com/changelog/2023/paddle-js-pricing-pages?utm_source=dx&utm_medium=paddle-js-wrapper). 186 | 187 | --- 188 | 189 | ## 0.4.0 - 2023-10-12 190 | 191 | ### Added 192 | 193 | - Initial early access release. 194 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | ## Contributing 2 | 3 | We're not accepting contributions to this repo right now. 4 | 5 | If you've spotted a problem with this package, open an issue. 6 | 7 | For help with Paddle.js or building your integration, contact our support team at [sellers@paddle.com](mailto:sellers@paddle.com). 8 | -------------------------------------------------------------------------------- /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 | # Paddle.js module 2 | 3 | [Paddle Billing](https://www.paddle.com/billing?utm_source=dx&utm_medium=paddle-js-wrapper) is a complete digital product sales and subscription management platform, designed for modern software businesses. It helps you increase your revenue, retain customers, and scale your operations. 4 | 5 | You can use [Paddle.js](https://developer.paddle.com/paddlejs/overview?utm_source=dx&utm_medium=paddle-js-wrapper) to integrate [Paddle Checkout](https://developer.paddle.com/concepts/sell/self-serve-checkout) and [Paddle Retain](https://www.paddle.com/retain?utm_source=dx&utm_medium=paddle-js-wrapper) with your app or website. 6 | 7 | This package is a wrapper for Paddle.js that lets you: 8 | 9 | - Download and work with Paddle.js 10 | - Use TypeScript definitions when working with Paddle.js functions 11 | 12 | > **Important:** This package works for Paddle.js v2, which is part of Paddle Billing. It does not support Paddle Classic. To work with Paddle.js v1, see: [Paddle.js v1 reference](https://developer.paddle.com/classic/reference/ZG9jOjI1MzUzOTg3-paddle-reference?utm_source=dx&utm_medium=paddle-js-wrapper) 13 | 14 | ## Installation 15 | 16 | Install using `npm`: 17 | 18 | ```sh 19 | npm install @paddle/paddle-js 20 | ``` 21 | 22 | Install using `yarn`: 23 | 24 | ```sh 25 | yarn add @paddle/paddle-js 26 | ``` 27 | 28 | Install using `pnpm`: 29 | 30 | ```sh 31 | pnpm add @paddle/paddle-js 32 | ``` 33 | 34 | ## Initialize Paddle.js 35 | 36 | Import, then use the `initializePaddle` function to initialize Paddle.js. It downloads Paddle.js from the CDN, then initializes it using the seller ID, environment, and any other settings that you passed. 37 | 38 | For security and compliance, you must only load Paddle.js directly from `https://cdn.paddle.com/`. This makes sure that you're running with the latest security and feature updates from Paddle. 39 | 40 | > **Note:** `initializePaddle` always downloads the latest version of Paddle.js. Updates to this package are for the loader or TypeScript definitions, and may not be tied to updates for Paddle.js. 41 | 42 | ## TypeScript definitions 43 | 44 | This package includes TypeScript definitions for Paddle.js. The minimum supported version of TypeScript is `4.1`. 45 | 46 | For example, `CheckoutOpenOptions` has definitions for all the values you can pass to the [`Paddle.Checkout.open()`](https://developer.paddle.com/paddlejs/methods/paddle-checkout-open?utm_source=dx&utm_medium=paddle-js-wrapper) method in Paddle.js. 47 | 48 | ## Example 49 | 50 | This is a simple React example that shows how to import, initialize, and open a checkout with one item. 51 | 52 | ```typescript jsx 53 | import { initializePaddle, Paddle } from '@paddle/paddle-js'; 54 | 55 | export function Checkout() { 56 | // Create a local state to store Paddle instance 57 | const [paddle, setPaddle] = useState(); 58 | 59 | // Download and initialize Paddle instance from CDN 60 | useEffect(() => { 61 | initializePaddle({ environment: 'ENVIRONMENT_GOES_HERE', token: 'AUTH_TOKEN_GOES_HERE' }).then( 62 | (paddleInstance: Paddle | undefined) => { 63 | if (paddleInstance) { 64 | setPaddle(paddleInstance); 65 | } 66 | }, 67 | ); 68 | }, []); 69 | 70 | // Callback to open a checkout 71 | const openCheckout = () => { 72 | paddle?.Checkout.open({ 73 | items: [{ priceId: 'PRICE_ID_GOES_HERE', quantity: 1 }], 74 | }); 75 | }; 76 | } 77 | ``` 78 | 79 | ## Learn more 80 | 81 | - [Paddle.js reference](https://developer.paddle.com/paddlejs/overview?utm_source=dx&utm_medium=paddle-js-wrapper) 82 | - [Sign up for Paddle Billing](https://login.paddle.com/signup?utm_source=dx&utm_medium=paddle-js-wrapper) 83 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | - [Security Policy](#security-policy) 2 | - [Reporting a Vulnerability](#reporting-a-vulnerability) 3 | 4 | # Security policy 5 | 6 | ## Reporting a vulnerability 7 | 8 | Please see the [Paddle Vulnerability Disclosure Policy](https://www.paddle.com/vulnerability-disclosure-policy) and 9 | report any vulnerabilities using https://vdp.paddle.com/p/Report-a-Vulnerability. 10 | 11 | > [!WARNING] 12 | > Do not create issues for potential security vulnerabilities. Issues are public and can be seen by potentially malicious actors. 13 | 14 | Thanks for helping to make the Paddle platform safe for everyone. 15 | -------------------------------------------------------------------------------- /jest.config.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * For a detailed explanation regarding each configuration property, visit: 3 | * https://jestjs.io/docs/configuration 4 | */ 5 | 6 | import type { Config } from 'jest'; 7 | 8 | const config: Config = { 9 | clearMocks: true, 10 | collectCoverage: true, 11 | coverageDirectory: 'coverage', 12 | coveragePathIgnorePatterns: ['/node_modules/'], 13 | coverageProvider: 'v8', 14 | coverageReporters: ['text', 'lcov'], 15 | moduleFileExtensions: ['js', 'ts', 'tsx'], 16 | testEnvironment: 'jsdom', 17 | testMatch: ['**/__tests__/**/*.(ts|tsx)'], 18 | transform: { 19 | '^.+\\.tsx?$': 'ts-jest', 20 | }, 21 | }; 22 | 23 | export default config; 24 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@paddle/paddle-js", 3 | "version": "1.4.0-next.0", 4 | "description": "Wrapper to load Paddle.js as a module and use TypeScript definitions when working with methods.", 5 | "main": "dist/index.js", 6 | "module": "dist/index.esm.js", 7 | "jsnext:main": "dist/index.esm.js", 8 | "types": "types/index.d.ts", 9 | "typings": "types/index.d.ts", 10 | "scripts": { 11 | "build": "yarn clean && yarn rollup -c", 12 | "clean": "rm -rf dist", 13 | "lint": "eslint '{src,types}/**/*.ts'", 14 | "prettier": "prettier --check {src,types}/**/*.ts", 15 | "prettier:fix": "prettier --check {src,types}/**/*.ts --write", 16 | "release:next": "yarn version --prerelease --preid next --no-git-tag-version --no-commit-hooks", 17 | "publish:next": "yarn publish --tag next --access public", 18 | "publish:latest": "yarn publish --access public", 19 | "test": "jest --silent", 20 | "tsc": "tsc" 21 | }, 22 | "keywords": [ 23 | "Paddle" 24 | ], 25 | "author": "Paddle.com Market Ltd.", 26 | "license": "Apache-2.0", 27 | "homepage": "https://developer.paddle.com/paddlejs/overview", 28 | "devDependencies": { 29 | "@babel/core": "^7.23.3", 30 | "@babel/preset-env": "^7.22.10", 31 | "@rollup/plugin-replace": "^5.0.2", 32 | "@types/jest": "^29.5.5", 33 | "@types/node": "^22.7.7", 34 | "@typescript-eslint/eslint-plugin": "^6.3.0", 35 | "@typescript-eslint/parser": "^6.3.0", 36 | "eslint": "^8.0.1", 37 | "jest": "^29.7.0", 38 | "jest-environment-jsdom": "^29.7.0", 39 | "prettier": "^3.0.1", 40 | "rollup": "^3.28.0", 41 | "rollup-plugin-babel": "^4.4.0", 42 | "rollup-plugin-typescript2": "^0.35.0", 43 | "ts-jest": "^29.1.1", 44 | "ts-node": "^10.9.1", 45 | "typescript": "5.1.6" 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /rollup.config.mjs: -------------------------------------------------------------------------------- 1 | import babel from 'rollup-plugin-babel'; 2 | import ts from 'rollup-plugin-typescript2'; 3 | import replace from '@rollup/plugin-replace'; 4 | 5 | import pkg from './package.json' with { type: 'json' }; 6 | 7 | const PLUGINS = [ 8 | ts({ 9 | tsconfigOverride: { exclude: ['**/*.test.ts', 'jest.config.ts'] }, 10 | }), 11 | babel({ 12 | extensions: ['.ts', '.js', '.tsx', '.jsx'], 13 | }), 14 | replace({ 15 | preventAssignment: true, 16 | _VERSION: JSON.stringify(pkg.version), 17 | }), 18 | ]; 19 | 20 | export default [ 21 | { 22 | input: 'src/index.ts', 23 | output: [ 24 | { file: pkg.main, format: 'umd', name: 'paddle', esModule: false, exports: 'named'}, 25 | { file: pkg.module, format: 'es' }, 26 | ], 27 | plugins: PLUGINS, 28 | }, 29 | ]; 30 | -------------------------------------------------------------------------------- /src/__tests__/index.test.ts: -------------------------------------------------------------------------------- 1 | import { initializePaddle } from '../index'; 2 | import * as shared from '../utils/shared'; 3 | import { Paddle } from '../../types'; 4 | import { DefaultVersion } from '../constants/cdn-information'; 5 | 6 | const mockedPaddleInstance: Paddle = { 7 | Version: DefaultVersion, 8 | Status: { 9 | libraryVersion: '2.0', 10 | }, 11 | Checkout: { 12 | close: jest.fn(), 13 | open: jest.fn(), 14 | updateItems: jest.fn(), 15 | updateCheckout: jest.fn(), 16 | }, 17 | Environment: { 18 | set: jest.fn(), 19 | }, 20 | PricePreview: jest.fn(), 21 | TransactionPreview: jest.fn(), 22 | Retain: { 23 | demo: jest.fn(), 24 | initCancellationFlow: jest.fn(), 25 | }, 26 | Setup: jest.fn(), 27 | Spinner: { 28 | hide: jest.fn(), 29 | show: jest.fn(), 30 | }, 31 | Initialized: false, 32 | Initialize: jest.fn(), 33 | Update: jest.fn(), 34 | }; 35 | 36 | describe('initializePaddle', () => { 37 | afterEach(() => { 38 | jest.clearAllMocks(); 39 | }); 40 | test('Should initialize Paddle with Seller ID', async () => { 41 | jest.spyOn(shared, 'loadFromCDN').mockResolvedValue(Promise.resolve(mockedPaddleInstance)); 42 | const paddle = await initializePaddle({ seller: 1 }); 43 | expect(paddle?.Status.libraryVersion).toBe('2.0'); 44 | expect(paddle?.Initialize).toBeCalledWith({ seller: 1 }); 45 | }); 46 | 47 | test('Should initialize Paddle with Token', async () => { 48 | jest.spyOn(shared, 'loadFromCDN').mockResolvedValue(Promise.resolve(mockedPaddleInstance)); 49 | const paddle = await initializePaddle({ token: 'TOKEN' }); 50 | expect(paddle?.Status.libraryVersion).toBe('2.0'); 51 | expect(paddle?.Initialize).toBeCalledWith({ token: 'TOKEN' }); 52 | }); 53 | 54 | test('Should initialize Paddle with Sandbox Environment', async () => { 55 | jest.spyOn(shared, 'loadFromCDN').mockResolvedValue(Promise.resolve(mockedPaddleInstance)); 56 | const paddle = await initializePaddle({ seller: 1, environment: 'sandbox' }); 57 | expect(paddle?.Environment.set).toBeCalledWith('sandbox'); 58 | expect(paddle?.Initialize).toBeCalledWith({ seller: 1 }); 59 | }); 60 | 61 | test('Should call update if Paddle is already initialized', async () => { 62 | const updatedMockedPaddleInstance = { ...mockedPaddleInstance, Initialized: true }; 63 | jest.spyOn(shared, 'loadFromCDN').mockResolvedValue(Promise.resolve(updatedMockedPaddleInstance)); 64 | const paddle = await initializePaddle({ seller: 1, environment: 'sandbox' }); 65 | expect(paddle?.Environment.set).toBeCalledWith('sandbox'); 66 | expect(paddle?.Initialize).not.toBeCalled(); 67 | expect(paddle?.Update).toBeCalledWith({ seller: 1 }); 68 | }); 69 | 70 | test('Should return error when initialization fails', async () => { 71 | const consoleWarn = jest.spyOn(console, 'warn'); 72 | jest 73 | .spyOn(shared, 'loadFromCDN') 74 | // @ts-expect-error - undefined is not a valid value for Initialize 75 | .mockResolvedValue(Promise.resolve({ ...mockedPaddleInstance, Initialize: undefined })); 76 | await initializePaddle({ seller: 1, environment: 'sandbox' }); 77 | expect(consoleWarn).toBeCalledTimes(1); 78 | }); 79 | 80 | test("Should return error when PaddleJS can't be downloaded", async () => { 81 | const consoleError = jest.spyOn(console, 'error'); 82 | jest.spyOn(shared, 'loadFromCDN').mockResolvedValue(Promise.resolve(undefined)); 83 | await initializePaddle({ seller: 1, environment: 'sandbox' }); 84 | expect(consoleError).toBeCalledWith('[Paddle] Error Loading Paddle'); 85 | }); 86 | }); 87 | -------------------------------------------------------------------------------- /src/__tests__/shared.test.ts: -------------------------------------------------------------------------------- 1 | import { findScript, getCDNInfoBasedOnVersion, injectScript } from '../utils/shared'; 2 | import { Paddle } from '../../types'; 3 | import { DefaultVersion } from '../constants/cdn-information'; 4 | 5 | const PADDLE_JS_SCRIPT = 'script[src="https://cdn.paddle.com/paddle/v2/paddle.js"]'; 6 | 7 | const mockedPaddleInstance: Paddle = { 8 | Version: DefaultVersion, 9 | Status: { 10 | libraryVersion: '2.0', 11 | }, 12 | Checkout: { 13 | close: jest.fn(), 14 | open: jest.fn(), 15 | updateItems: jest.fn(), 16 | updateCheckout: jest.fn(), 17 | }, 18 | Environment: { 19 | set: jest.fn(), 20 | }, 21 | PricePreview: jest.fn(), 22 | TransactionPreview: jest.fn(), 23 | Retain: { 24 | demo: jest.fn(), 25 | initCancellationFlow: jest.fn(), 26 | }, 27 | Setup: jest.fn(), 28 | Spinner: { 29 | hide: jest.fn(), 30 | show: jest.fn(), 31 | }, 32 | Initialized: false, 33 | Initialize: jest.fn(), 34 | Update: jest.fn(), 35 | }; 36 | 37 | interface SharedModule { 38 | loadFromCDN: (version: string) => Promise; 39 | } 40 | let sharedModule: SharedModule; 41 | jest.isolateModules(() => { 42 | sharedModule = require('../utils/shared'); 43 | }); 44 | 45 | describe('Shared module', () => { 46 | afterEach(() => { 47 | const script = document.querySelector(PADDLE_JS_SCRIPT); 48 | if (script && script.parentElement) { 49 | script.parentElement.removeChild(script); 50 | } 51 | delete window.Paddle; 52 | 53 | jest.resetModules(); 54 | jest.restoreAllMocks(); 55 | }); 56 | 57 | test('Should detect downloaded script', () => { 58 | injectScript('https://pw.paddle.com/pw.js'); 59 | injectScript('https://cdn.paddle.com/paddle/v2/paddle.js'); 60 | const cdnUrl = getCDNInfoBasedOnVersion(DefaultVersion)?.url as string; 61 | expect(!!findScript(cdnUrl)).toBe(true); 62 | }); 63 | 64 | test('Should skip Non Paddle Billing scripts', () => { 65 | const cdnUrl = getCDNInfoBasedOnVersion(DefaultVersion)?.url as string; 66 | injectScript('https://cdn.paddle.com/paddle/v1/paddle.js'); 67 | 68 | expect(!!findScript(cdnUrl)).toBe(false); 69 | }); 70 | 71 | test('Should return paddle instance on load event', async () => { 72 | window.Paddle = mockedPaddleInstance; 73 | injectScript('https://cdn.paddle.com/paddle/v2/paddle.js'); 74 | const script = document.querySelector(PADDLE_JS_SCRIPT); 75 | const promise = sharedModule.loadFromCDN('v1'); 76 | script?.dispatchEvent(new Event('load')); 77 | return promise.then((paddleInstance) => expect(paddleInstance).toBe(mockedPaddleInstance)).catch(console.warn); 78 | }); 79 | 80 | test('Should reject promise on Error', async () => { 81 | injectScript('https://cdn.paddle.com/paddle/v2/paddle.js'); 82 | const script = document.querySelector(PADDLE_JS_SCRIPT); 83 | const promise = sharedModule.loadFromCDN('v1'); 84 | script?.dispatchEvent(new Event('error')); 85 | return promise.catch((e) => expect(e.message).toBe('Paddle.js not available')); 86 | }); 87 | }); 88 | -------------------------------------------------------------------------------- /src/constants/cdn-information.ts: -------------------------------------------------------------------------------- 1 | export const Versions = { 2 | CLASSIC: 'classic', 3 | V1: 'v1', 4 | } as const; 5 | 6 | export const DefaultVersion = Versions.V1; 7 | 8 | export const PaddleClassicCDNUrl = 'https://cdn.paddle.com/paddle/paddle.js'; 9 | export const PaddleBillingCDNUrl = 'https://cdn.paddle.com/paddle/v2/paddle.js'; 10 | 11 | export const PaddleClassicInfo = { 12 | url: PaddleClassicCDNUrl, 13 | } as const; 14 | 15 | export const PaddleBillingV1Info = { 16 | url: PaddleBillingCDNUrl, 17 | } as const; 18 | -------------------------------------------------------------------------------- /src/constants/checkout-events.ts: -------------------------------------------------------------------------------- 1 | // Note: The enums in this file is only for `src`. Typescript will also need it added to the `types` directory for usage. 2 | export enum CheckoutEventNames { 3 | CHECKOUT_LOADED = 'checkout.loaded', 4 | CHECKOUT_CLOSED = 'checkout.closed', 5 | CHECKOUT_UPDATED = 'checkout.updated', 6 | CHECKOUT_COMPLETED = 'checkout.completed', 7 | CHECKOUT_ERROR = 'checkout.error', 8 | CHECKOUT_FAILED = 'checkout.failed', 9 | CHECKOUT_ITEMS_UPDATED = 'checkout.items.updated', 10 | CHECKOUT_ITEMS_REMOVED = 'checkout.items.removed', 11 | CHECKOUT_CUSTOMER_CREATED = 'checkout.customer.created', 12 | CHECKOUT_CUSTOMER_UPDATED = 'checkout.customer.updated', 13 | CHECKOUT_CUSTOMER_REMOVED = 'checkout.customer.removed', 14 | CHECKOUT_PAYMENT_SELECTED = 'checkout.payment.selected', 15 | CHECKOUT_PAYMENT_INITIATED = 'checkout.payment.initiated', 16 | CHECKOUT_PAYMENT_FAILED = 'checkout.payment.failed', 17 | CHECKOUT_DISCOUNT_APPLIED = 'checkout.discount.applied', 18 | CHECKOUT_DISCOUNT_REMOVED = 'checkout.discount.removed', 19 | } 20 | 21 | export enum CheckoutEventsTimePeriodInterval { 22 | DAY = 'day', 23 | WEEK = 'week', 24 | MONTH = 'month', 25 | YEAR = 'year', 26 | } 27 | 28 | export enum CheckoutEventsPaymentMethodTypes { 29 | ALIPAY = 'alipay', 30 | APPLE_PAY = 'apple-pay', 31 | CARD = 'card', 32 | GOOGLE_PAY = 'google-pay', 33 | IDEAL = 'ideal', 34 | PAYPAL = 'paypal', 35 | WIRE_TRANSFER = 'wire-transfer', 36 | NONE = 'none', 37 | } 38 | 39 | export enum CheckoutEventsPaymentMethodCardTypes { 40 | AMERICAN_EXPRESS = 'american_express', 41 | DINERS_CLUB = 'diners_club', 42 | DISCOVER = 'discover', 43 | JCB = 'jcb', 44 | MADA = 'mada', 45 | MAESTRO = 'maestro', 46 | MASTER_CARD = 'mastercard', 47 | UNION_PAY = 'union_pay', 48 | VISA = 'visa', 49 | UNKNOWN = 'unknown', 50 | } 51 | 52 | export enum CheckoutEventsStatus { 53 | DRAFT = 'draft', 54 | READY = 'ready', 55 | COMPLETED = 'completed', 56 | BILLED = 'billed', 57 | canceled = 'canceled', 58 | PAST_DUE = 'past_due', 59 | } 60 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import { loadFromCDN } from './utils/shared'; 2 | import { InitializePaddleOptions, Paddle, Version } from '../types'; 3 | import { DefaultVersion, Versions } from './constants/cdn-information'; 4 | import { initializePaddleBillingV1, initializePaddleClassic } from './utils/initialize'; 5 | 6 | export { 7 | CheckoutEventNames, 8 | CheckoutEventsPaymentMethodCardTypes, 9 | CheckoutEventsStatus, 10 | CheckoutEventsTimePeriodInterval, 11 | CheckoutEventsPaymentMethodTypes, 12 | } from './constants/checkout-events'; 13 | 14 | export async function initializePaddle(options?: InitializePaddleOptions): Promise { 15 | const requestedVersion = options?.version || DefaultVersion; 16 | const paddle = await loadFromCDN(requestedVersion); 17 | if (paddle) { 18 | if (options) { 19 | if (requestedVersion === Versions.V1) { 20 | initializePaddleBillingV1(options, paddle); 21 | } else if (requestedVersion === Versions.CLASSIC) { 22 | initializePaddleClassic(options, paddle); 23 | } 24 | } 25 | return paddle; 26 | } else { 27 | console.error('[Paddle] Error Loading Paddle'); 28 | return; 29 | } 30 | } 31 | 32 | export function getPaddleInstance(version: Version = DefaultVersion) { 33 | if (version === Versions.V1) { 34 | return (window.PaddleBillingV1 || window.Paddle) as Paddle; 35 | } else if (version === Versions.CLASSIC) { 36 | // eslint-disable-next-line @typescript-eslint/no-explicit-any 37 | return (window.PaddleClassic || window.Paddle) as any; 38 | } else { 39 | console.error('[Paddle] Unknown Paddle Version'); 40 | return; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/utils/initialize.ts: -------------------------------------------------------------------------------- 1 | import { InitializePaddleOptions, Paddle } from '../../types'; 2 | 3 | export function initializePaddleBillingV1(options: InitializePaddleOptions, paddle: Paddle) { 4 | const { environment, version: _version, ...rest } = options; 5 | try { 6 | if (environment) { 7 | paddle.Environment.set(environment); 8 | } 9 | if (paddle.Initialized) { 10 | paddle.Update({ ...rest }); 11 | } else { 12 | paddle.Initialize({ ...rest }); 13 | } 14 | } catch (e) { 15 | console.warn('[Paddle] Paddle Initialization failed. Please check the inputs', e); 16 | } 17 | } 18 | 19 | // eslint-disable-next-line @typescript-eslint/no-explicit-any 20 | export function initializePaddleClassic(options: InitializePaddleOptions, paddle: any) { 21 | const { environment, version: _version, ...rest } = options; 22 | try { 23 | if (environment) { 24 | paddle.Environment.set(environment); 25 | } 26 | paddle.Setup({ ...rest }); 27 | } catch (e) { 28 | console.warn('[Paddle] Paddle Initialization failed. Please check the inputs', e); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/utils/shared.ts: -------------------------------------------------------------------------------- 1 | import { Paddle, Version } from '../../types'; 2 | import { PaddleBillingV1Info, PaddleClassicInfo, Versions } from '../constants/cdn-information'; 3 | 4 | export function findScript(cdnUrl: string): HTMLScriptElement | undefined { 5 | return document.querySelector(`script[src="${cdnUrl}"]`) || undefined; 6 | } 7 | 8 | export function injectScript(src: string): HTMLScriptElement { 9 | const script = document.createElement('script'); 10 | script.src = src; 11 | 12 | const headOrBody = document.head || document.body; 13 | 14 | if (!headOrBody) { 15 | throw new Error('Cannot inject Paddle.js. It needs a or element.'); 16 | } 17 | 18 | headOrBody.appendChild(script); 19 | 20 | return script; 21 | } 22 | 23 | const promiseMap: Record | undefined> = { 24 | classic: undefined, 25 | v1: undefined, 26 | }; 27 | 28 | type PaddleInstanceName = 'PaddleClassic' | 'PaddleBillingV1'; 29 | const VersionToPaddleMap: Record = { 30 | classic: 'PaddleClassic', 31 | v1: 'PaddleBillingV1', 32 | }; 33 | 34 | export function loadFromCDN(version: Version): Promise | undefined { 35 | const cdnUrl = getCDNInfoBasedOnVersion(version)?.url; 36 | if (!cdnUrl) { 37 | return; 38 | } 39 | // Return promise on re-renders 40 | const existingPromise = promiseMap[version]; 41 | const paddleInstanceName = VersionToPaddleMap[version]; 42 | if (existingPromise !== undefined) { 43 | return existingPromise; 44 | } 45 | 46 | promiseMap[version] = new Promise((resolve, reject) => { 47 | if (typeof window === 'undefined') { 48 | // Return undefined in a server side environment 49 | resolve(undefined); 50 | return; 51 | } 52 | 53 | // Return Paddle instance if it is already initialized 54 | if (window[paddleInstanceName] || window.Paddle) { 55 | resolve(window[paddleInstanceName] || window.Paddle); 56 | return; 57 | } 58 | 59 | try { 60 | // Inject if paddle.js script tag is not found 61 | let script = findScript(cdnUrl); 62 | 63 | if (!script) { 64 | script = injectScript(cdnUrl); 65 | } 66 | 67 | // Wait for `load` event before returning 68 | script.addEventListener('load', () => { 69 | if (window[paddleInstanceName] || window.Paddle) { 70 | resolve(window[paddleInstanceName] || window.Paddle); 71 | } else { 72 | reject(new Error('Paddle.js not available')); 73 | } 74 | }); 75 | 76 | // Show an error if loading fails 77 | script.addEventListener('error', () => { 78 | reject(new Error(`Failed to load Paddle.js - ${version}`)); 79 | }); 80 | } catch (error) { 81 | reject(error); 82 | return; 83 | } 84 | }); 85 | 86 | return promiseMap[version]; 87 | } 88 | 89 | export function getCDNInfoBasedOnVersion(version: Version) { 90 | if (version === Versions.CLASSIC) { 91 | return PaddleClassicInfo; 92 | } 93 | if (version === Versions.V1) { 94 | return PaddleBillingV1Info; 95 | } else { 96 | console.error('[Paddle] Unknown Paddle Version'); 97 | return; 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "ES2022", 4 | "esModuleInterop": true, 5 | /* Modules */ 6 | "module": "ES2022", 7 | "rootDir": "./src", 8 | "moduleResolution": "node", 9 | "declaration": false, 10 | "outDir": "./dist", 11 | "forceConsistentCasingInFileNames": true, 12 | "strict": true, 13 | "noEmit": true, 14 | "noImplicitAny": true, 15 | "strictNullChecks": true, 16 | "strictFunctionTypes": true, 17 | "strictBindCallApply": true, 18 | "strictPropertyInitialization": true, 19 | "noImplicitThis": true, 20 | "useUnknownInCatchVariables": true, 21 | "alwaysStrict": true, 22 | "noUnusedLocals": true, 23 | "noUnusedParameters": true, 24 | "exactOptionalPropertyTypes": true, 25 | "noImplicitReturns": true, 26 | "noFallthroughCasesInSwitch": true, 27 | "noUncheckedIndexedAccess": true, 28 | "noImplicitOverride": true, 29 | "noPropertyAccessFromIndexSignature": true, 30 | "skipLibCheck": true 31 | }, 32 | "exclude": ["jest.config.ts"] 33 | } 34 | -------------------------------------------------------------------------------- /types/checkout/checkout.d.ts: -------------------------------------------------------------------------------- 1 | import { 2 | CheckoutEventNames, 3 | CheckoutEventsData, 4 | CheckoutEventError, 5 | DisplayMode, 6 | Theme, 7 | AvailablePaymentMethod, 8 | Variant, 9 | } from '../index'; 10 | import { CheckoutCustomer } from './customer'; 11 | 12 | export interface CheckoutSettings { 13 | displayMode?: DisplayMode; 14 | theme?: Theme; 15 | locale?: string; 16 | allowLogout?: boolean; 17 | showAddDiscounts?: boolean; 18 | showAddTaxId?: boolean; 19 | frameTarget?: string; 20 | frameStyle?: string; 21 | frameInitialHeight?: number; 22 | successUrl?: string; 23 | allowedPaymentMethods?: AvailablePaymentMethod[]; 24 | allowDiscountRemoval?: boolean; 25 | variant?: Variant; 26 | } 27 | 28 | export interface PaddleSetupPwCustomer { 29 | id?: string; 30 | email?: string; 31 | } 32 | 33 | interface PaddleSetupBaseOptions { 34 | pwAuth?: string; 35 | pwCustomer?: PaddleSetupPwCustomer; 36 | debug?: boolean; 37 | eventCallback?: (event: PaddleEventData) => void; 38 | checkout?: { 39 | settings: CheckoutSettings; 40 | }; 41 | } 42 | 43 | export interface PaddleEventData extends Partial { 44 | name?: CheckoutEventNames; 45 | data?: CheckoutEventsData; 46 | error?: CheckoutEventError; 47 | type?: string; 48 | } 49 | 50 | interface PaddleSetupOptionsWithSeller extends PaddleSetupBaseOptions { 51 | seller: number; 52 | token?: never; 53 | } 54 | 55 | interface PaddleSetupOptionsWithToken extends PaddleSetupBaseOptions { 56 | seller?: never; 57 | token: string; 58 | } 59 | 60 | export type PaddleSetupOptions = PaddleSetupOptionsWithSeller | PaddleSetupOptionsWithToken; 61 | 62 | export interface CheckoutLineItem { 63 | priceId: string; 64 | quantity: number; 65 | } 66 | 67 | export interface CheckoutOpenLineItem { 68 | priceId: string; 69 | quantity?: number; 70 | } 71 | 72 | interface CheckoutOpenOptionsWithItems { 73 | items: CheckoutOpenLineItem[]; 74 | transactionId?: never; 75 | } 76 | 77 | interface CheckoutOpenOptionsWithTransactionId { 78 | items?: never; 79 | transactionId: string; 80 | } 81 | interface CheckoutOpenOptionsWithDiscountId { 82 | discountCode?: never; 83 | discountId?: string | null; 84 | } 85 | 86 | interface CheckoutOpenOptionsWithDiscountCode { 87 | discountCode?: string | null; 88 | discountId?: never; 89 | } 90 | 91 | interface CheckoutOpenOptionsWithCustomer { 92 | customer?: CheckoutCustomer; 93 | customerAuthToken?: never; 94 | savedPaymentMethodId?: never; 95 | } 96 | 97 | interface CheckoutOpenOptionsWithCustomerAuthToken { 98 | customer?: never; 99 | customerAuthToken?: string; 100 | savedPaymentMethodId?: string; 101 | } 102 | 103 | interface CheckoutOpenBaseOptions { 104 | settings?: CheckoutSettings; 105 | customData?: Record; 106 | } 107 | 108 | type CheckoutOpenOptionsWithLineItems = CheckoutOpenOptionsWithItems | CheckoutOpenOptionsWithTransactionId; 109 | type CheckoutOpenOptionsWithDiscount = CheckoutOpenOptionsWithDiscountId | CheckoutOpenOptionsWithDiscountCode; 110 | type CheckoutOpenOptionsWithCustomerData = CheckoutOpenOptionsWithCustomer | CheckoutOpenOptionsWithCustomerAuthToken; 111 | 112 | export type CheckoutOpenOptions = CheckoutOpenBaseOptions & 113 | CheckoutOpenOptionsWithLineItems & 114 | CheckoutOpenOptionsWithDiscount & 115 | CheckoutOpenOptionsWithCustomerData; 116 | 117 | export type CheckoutUpdateOptions = CheckoutOpenOptionsWithDiscount & 118 | CheckoutOpenOptionsWithCustomerData & { 119 | items?: CheckoutOpenLineItem[]; 120 | customData?: Record; 121 | }; 122 | -------------------------------------------------------------------------------- /types/checkout/customer.d.ts: -------------------------------------------------------------------------------- 1 | interface CheckoutCustomerId { 2 | id: string; 3 | email?: never; 4 | } 5 | 6 | interface CheckoutCustomerEmail { 7 | id?: never; 8 | email: string; 9 | } 10 | 11 | interface CheckoutCustomerAddressId { 12 | id: string; 13 | countryCode?: never; 14 | postalCode?: never; 15 | region?: never; 16 | city?: never; 17 | firstLine?: never; 18 | } 19 | 20 | interface CheckoutCustomerAddressDetails { 21 | id?: never; 22 | countryCode?: string; 23 | postalCode?: string; 24 | region?: string; 25 | city?: string; 26 | firstLine?: string; 27 | } 28 | 29 | interface CheckoutCustomerBusinessId { 30 | id: string; 31 | name?: never; 32 | taxIdentifier?: never; 33 | } 34 | 35 | interface CheckoutCustomerBusinessDetails { 36 | id?: never; 37 | name: string; 38 | taxIdentifier: string; 39 | } 40 | 41 | type CheckoutCustomerUserInfo = CheckoutCustomerId | CheckoutCustomerEmail; 42 | 43 | export type CheckoutCustomerAddress = CheckoutCustomerAddressId | CheckoutCustomerAddressDetails; 44 | export type CheckoutCustomerBusiness = CheckoutCustomerBusinessId | CheckoutCustomerBusinessDetails; 45 | 46 | interface CheckoutCustomerDetails { 47 | address?: CheckoutCustomerAddress; 48 | business?: CheckoutCustomerBusiness; 49 | } 50 | 51 | export type CheckoutCustomer = CheckoutCustomerUserInfo & CheckoutCustomerDetails; 52 | -------------------------------------------------------------------------------- /types/checkout/events.d.ts: -------------------------------------------------------------------------------- 1 | // Note: The enums in this file is only for types. For it to work in the application please update the `src` directory 2 | import { CurrencyCode } from '../shared/currency-code'; 3 | 4 | export enum CheckoutEventNames { 5 | CHECKOUT_LOADED = 'checkout.loaded', 6 | CHECKOUT_CLOSED = 'checkout.closed', 7 | CHECKOUT_UPDATED = 'checkout.updated', 8 | CHECKOUT_COMPLETED = 'checkout.completed', 9 | CHECKOUT_ERROR = 'checkout.error', 10 | CHECKOUT_FAILED = 'checkout.failed', 11 | CHECKOUT_ITEMS_UPDATED = 'checkout.items.updated', 12 | CHECKOUT_ITEMS_REMOVED = 'checkout.items.removed', 13 | CHECKOUT_CUSTOMER_CREATED = 'checkout.customer.created', 14 | CHECKOUT_CUSTOMER_UPDATED = 'checkout.customer.updated', 15 | CHECKOUT_CUSTOMER_REMOVED = 'checkout.customer.removed', 16 | CHECKOUT_PAYMENT_SELECTED = 'checkout.payment.selected', 17 | CHECKOUT_PAYMENT_INITIATED = 'checkout.payment.initiated', 18 | CHECKOUT_PAYMENT_FAILED = 'checkout.payment.failed', 19 | CHECKOUT_DISCOUNT_APPLIED = 'checkout.discount.applied', 20 | CHECKOUT_DISCOUNT_REMOVED = 'checkout.discount.removed', 21 | } 22 | 23 | export enum CheckoutEventsTimePeriodInterval { 24 | DAY = 'day', 25 | WEEK = 'week', 26 | MONTH = 'month', 27 | YEAR = 'year', 28 | } 29 | 30 | export enum CheckoutEventsPaymentMethodTypes { 31 | ALIPAY = 'alipay', 32 | APPLE_PAY = 'apple-pay', 33 | CARD = 'card', 34 | GOOGLE_PAY = 'google-pay', 35 | IDEAL = 'ideal', 36 | PAYPAL = 'paypal', 37 | WIRE_TRANSFER = 'wire-transfer', 38 | NONE = 'none', 39 | } 40 | 41 | export enum CheckoutEventsPaymentMethodCardTypes { 42 | AMERICAN_EXPRESS = 'american_express', 43 | DINERS_CLUB = 'diners_club', 44 | DISCOVER = 'discover', 45 | JCB = 'jcb', 46 | MADA = 'mada', 47 | MAESTRO = 'maestro', 48 | MASTER_CARD = 'mastercard', 49 | UNION_PAY = 'union_pay', 50 | VISA = 'visa', 51 | UNKNOWN = 'unknown', 52 | } 53 | 54 | export enum CheckoutEventsStatus { 55 | DRAFT = 'draft', 56 | READY = 'ready', 57 | COMPLETED = 'completed', 58 | BILLED = 'billed', 59 | PAID = 'paid', 60 | canceled = 'canceled', 61 | PAST_DUE = 'past_due', 62 | } 63 | 64 | export interface CheckoutEventsCustomerAddress { 65 | city: string; 66 | country_code: string; 67 | first_line: string; 68 | id: string; 69 | postal_code: string; 70 | region: string; 71 | } 72 | 73 | export interface CheckoutEventsCustomerBusiness { 74 | id: string; 75 | name: string; 76 | tax_identifier: string; 77 | } 78 | 79 | export interface CheckoutEventsCustomer { 80 | address?: CheckoutEventsCustomerAddress | null; 81 | business?: CheckoutEventsCustomerBusiness | null; 82 | email?: string; 83 | id?: string; 84 | } 85 | 86 | export interface CheckoutEventsItemProduct { 87 | description?: string; 88 | id: string; 89 | image_url?: string; 90 | name: string; 91 | } 92 | 93 | export interface CheckoutEventsTimePeriod { 94 | frequency: number; 95 | interval: CheckoutEventsTimePeriodInterval; 96 | } 97 | 98 | export interface CheckoutEventsTotals { 99 | balance?: number; 100 | credit?: number; 101 | discount: number; 102 | subtotal: number; 103 | tax: number; 104 | total: number; 105 | } 106 | 107 | export interface CheckoutEventsItem { 108 | billing_cycle?: CheckoutEventsTimePeriod; 109 | price_id: string; 110 | price_name?: string | null; 111 | product: CheckoutEventsItemProduct; 112 | quantity: number; 113 | recurring_totals?: CheckoutEventsTotals; 114 | totals: CheckoutEventsTotals; 115 | trial_period?: CheckoutEventsTimePeriod; 116 | } 117 | 118 | export interface CheckoutEventsPaymentMethodCardDetails { 119 | expiry_month: number; 120 | expiry_year: number; 121 | last4: string; 122 | type: CheckoutEventsPaymentMethodCardTypes; 123 | } 124 | 125 | export interface CheckoutEventsPaymentMethodDetails { 126 | card?: CheckoutEventsPaymentMethodCardDetails; 127 | type: CheckoutEventsPaymentMethodTypes; 128 | } 129 | 130 | export interface CheckoutEventsPayment { 131 | method_details: CheckoutEventsPaymentMethodDetails; 132 | } 133 | 134 | export interface CheckoutEventsSettings { 135 | display_mode: 'overlay' | 'inline' | 'wide-overlay'; 136 | theme: 'light' | 'dark'; 137 | } 138 | 139 | export interface CheckoutEventsDiscount { 140 | code: string; 141 | id: string; 142 | } 143 | 144 | export interface CheckoutEventsData { 145 | currency_code: CurrencyCode; 146 | custom_data?: object | null; 147 | customer: CheckoutEventsCustomer; 148 | discount?: CheckoutEventsDiscount; 149 | id: string; 150 | items: CheckoutEventsItem[]; 151 | payment: CheckoutEventsPayment; 152 | recurring_totals?: CheckoutEventsTotals; 153 | settings: CheckoutEventsSettings; 154 | status: CheckoutEventsStatus; 155 | totals: CheckoutEventsTotals; 156 | transaction_id: string; 157 | } 158 | 159 | export interface CheckoutEventError { 160 | type: string; 161 | code: string; 162 | detail: string; 163 | documentation_url: string; 164 | } 165 | -------------------------------------------------------------------------------- /types/checkout/retain.d.ts: -------------------------------------------------------------------------------- 1 | export type RetainCancellationFlowStatus = 'error' | 'aborted' | 'chose_to_cancel' | 'retained'; 2 | 3 | export type RETAIN_DEMO_FEATURE = 4 | | 'paymentRecovery' 5 | | 'paymentRecoveryInApp' 6 | | 'termOptimization' 7 | | 'termOptimizationInApp' 8 | | 'cancellationFlow'; 9 | 10 | type RetainCancellationFlowNotShownStatus = 'error'; 11 | 12 | export interface RetainCancellationFlowNotShownResult { 13 | status: RetainCancellationFlowNotShownStatus; 14 | details: string; 15 | } 16 | 17 | export interface RetainCancellationFlowShownResult { 18 | status: Exclude; 19 | salvageAttemptResult: RetainCancellationFlowSalvageAttemptResult | null; 20 | salvageOfferResult: RetainCancellationFlowSalvageOfferResult | null; 21 | additionalFeedback: string | null; 22 | cancelReason: string | null; 23 | satisfactionInsight: string | null; 24 | salvageAttemptIntended: RetainCancellationFlowSalvageAttempt | null; 25 | salvageAttemptUsed: RetainCancellationFlowSalvageAttempt | null; 26 | } 27 | 28 | export type RetainCancellationFlowResult = RetainCancellationFlowShownResult | RetainCancellationFlowNotShownResult; 29 | 30 | export type RetainCancellationFlowSalvageAttemptResolution = 'accepted' | 'rejected'; 31 | 32 | export type RetainCancellationFlowSalvageOfferDecision = 'accepted' | 'rejected'; 33 | 34 | export interface RetainCancellationFlowSalvageAttemptResult { 35 | decision: RetainCancellationFlowSalvageAttemptResolution; 36 | resolution: RetainCancellationFlowSalvageAttemptResolution; 37 | hasErrors: boolean; 38 | } 39 | 40 | export interface RetainCancellationFlowSalvageOfferResult { 41 | decision: RetainCancellationFlowSalvageOfferDecision; 42 | hasErrors: boolean; 43 | } 44 | 45 | type RetainCancellationFlowSalvageAttempt = 46 | | 'pause_subscription' 47 | | 'plan_switch' 48 | | 'contact_support_email_notification' 49 | | 'contact_support_meeting_scheduler'; 50 | 51 | export interface RetainDemoAttributeProps { 52 | feature: RETAIN_DEMO_FEATURE; 53 | } 54 | 55 | export interface RetainCancellationFlowAttributeProps { 56 | subscriptionId: string; 57 | } 58 | -------------------------------------------------------------------------------- /types/index.d.ts: -------------------------------------------------------------------------------- 1 | import { 2 | CheckoutLineItem, 3 | CheckoutOpenLineItem, 4 | CheckoutOpenOptions, 5 | PaddleSetupOptions, 6 | CheckoutSettings, 7 | PaddleEventData, 8 | PaddleSetupPwCustomer, 9 | CheckoutUpdateOptions, 10 | } from './checkout/checkout'; 11 | import { CheckoutCustomer, CheckoutCustomerAddress, CheckoutCustomerBusiness } from './checkout/customer'; 12 | import { PricePreviewItem, PricePreviewParams, PricePreviewResponse } from './price-preview/price-preview'; 13 | import { 14 | RetainCancellationFlowAttributeProps, 15 | RetainCancellationFlowResult, 16 | RetainDemoAttributeProps, 17 | } from './checkout/retain'; 18 | import { 19 | TransactionPreviewParams, 20 | TransactionPreviewResponse, 21 | TransactionPreviewItem, 22 | } from './transaction-preview/transaction-preview'; 23 | 24 | export * from './shared/shared'; 25 | 26 | export { CurrencyCode } from './shared/currency-code'; 27 | export { CountryCode } from './shared/country-code'; 28 | 29 | export { 30 | CheckoutEventNames, 31 | CheckoutEventsCustomer, 32 | CheckoutEventsItem, 33 | CheckoutEventsPayment, 34 | CheckoutEventsPaymentMethodDetails, 35 | CheckoutEventsPaymentMethodCardDetails, 36 | CheckoutEventsPaymentMethodTypes, 37 | CheckoutEventsCustomerAddress, 38 | CheckoutEventsCustomerBusiness, 39 | CheckoutEventsData, 40 | CheckoutEventsPaymentMethodCardTypes, 41 | CheckoutEventsDiscount, 42 | CheckoutEventsItemProduct, 43 | CheckoutEventsSettings, 44 | CheckoutEventsStatus, 45 | CheckoutEventsTimePeriod, 46 | CheckoutEventsTimePeriodInterval, 47 | CheckoutEventsTotals, 48 | CheckoutEventError, 49 | } from './checkout/events'; 50 | 51 | export type DisplayMode = 'inline' | 'overlay'; 52 | export type Environments = 'production' | 'sandbox'; 53 | export type Version = 'classic' | 'v1'; 54 | export type Theme = 'light' | 'dark'; 55 | 56 | export { 57 | PaddleSetupPwCustomer, 58 | CheckoutOpenOptions, 59 | CheckoutUpdateOptions, 60 | PaddleSetupOptions, 61 | CheckoutLineItem, 62 | CheckoutOpenLineItem, 63 | CheckoutSettings, 64 | PaddleEventData, 65 | CheckoutCustomer, 66 | CheckoutCustomerAddress, 67 | CheckoutCustomerBusiness, 68 | PricePreviewItem, 69 | PricePreviewParams, 70 | PricePreviewResponse, 71 | RetainCancellationFlowAttributeProps, 72 | RetainCancellationFlowResult, 73 | RetainDemoAttributeProps, 74 | TransactionPreviewItem, 75 | TransactionPreviewParams, 76 | TransactionPreviewResponse, 77 | }; 78 | 79 | export interface Paddle { 80 | Checkout: { 81 | open(input: CheckoutOpenOptions): void; 82 | updateCheckout(input: CheckoutUpdateOptions): void; 83 | updateItems(items: CheckoutLineItem[]): void; 84 | close(): void; 85 | }; 86 | Environment: { 87 | set(environment: Environments): void; 88 | }; 89 | Retain: { 90 | demo: (parameters: RetainDemoAttributeProps) => void; 91 | initCancellationFlow: (parameters: RetainCancellationFlowAttributeProps) => Promise; 92 | }; 93 | PricePreview: (params: PricePreviewParams) => Promise; 94 | TransactionPreview: (params: TransactionPreviewParams) => Promise; 95 | /** 96 | @deprecated. Use `Paddle.Initialize` instead. 97 | */ 98 | Setup(options: PaddleSetupOptions): void; 99 | Spinner: { 100 | show(): void; 101 | hide(): void; 102 | }; 103 | Status: { 104 | libraryVersion: string; 105 | }; 106 | Initialized: boolean; 107 | Initialize(options: PaddleSetupOptions): void; 108 | Update(options: Partial): void; 109 | Version: Version; 110 | } 111 | 112 | declare global { 113 | interface Window { 114 | // Paddle.JS will be downloaded directly from our CDN and added to global variable 115 | // We don't recommend using `Paddle` or `PaddleBillingV1` or `PaddleClassic` directly. 116 | // Please use `getPaddleInstance` function to get Paddle instance. 117 | Paddle?: Paddle | undefined; 118 | PaddleBillingV1?: Paddle | undefined; 119 | // eslint-disable-next-line @typescript-eslint/no-explicit-any 120 | PaddleClassic?: any; 121 | } 122 | } 123 | 124 | export type InitializePaddleOptions = PaddleSetupOptions & { 125 | version?: Version; 126 | environment?: Environments; 127 | }; 128 | 129 | export function initializePaddle(options?: InitializePaddleOptions): Promise; 130 | export function getPaddleInstance(version: 'v1'): Paddle | undefined; 131 | // eslint-disable-next-line @typescript-eslint/no-explicit-any 132 | export function getPaddleInstance(version: 'classic'): any; 133 | export function getPaddleInstance(): Paddle | undefined; 134 | -------------------------------------------------------------------------------- /types/price-preview/price-preview.d.ts: -------------------------------------------------------------------------------- 1 | import { AvailablePaymentMethod, Price, Product, Totals } from '../shared/shared'; 2 | import { CurrencyCode } from '../shared/currency-code'; 3 | 4 | export interface PricePreviewItem { 5 | priceId: string; 6 | quantity: number; 7 | } 8 | 9 | export interface PricePreviewParams { 10 | items: PricePreviewItem[]; 11 | customerId?: string; 12 | addressId?: string; 13 | businessId?: string; 14 | currencyCode?: CurrencyCode; 15 | discountId?: string; 16 | address?: { 17 | countryCode: string; 18 | postalCode?: string; 19 | }; 20 | customerIpAddress?: string; 21 | } 22 | 23 | interface Discount { 24 | id: string; 25 | status: 'active' | 'archived' | 'expired' | 'used'; 26 | description: string; 27 | enabledForCheckout: boolean; 28 | code: string | null; 29 | type: 'flat' | 'flat_per_seat' | 'percentage'; 30 | amount: string; 31 | currencyCode: CurrencyCode | null; 32 | recur: boolean; 33 | maximumRecurringIntervals: number | null; 34 | usageLimit: number | null; 35 | restrictTo: string[] | null; 36 | expiresAt: string | null; 37 | timesUsed: number; 38 | createdAt: string; 39 | updatedAt: string; 40 | } 41 | 42 | interface DiscountLineItem { 43 | discount: Discount; 44 | total: string; 45 | formattedTotal: string; 46 | } 47 | 48 | interface LineItem { 49 | price: Price; 50 | quantity: number; 51 | taxRate: string; 52 | unitTotals: Totals; 53 | formattedUnitTotals: Totals; 54 | totals: Totals; 55 | formattedTotals: Totals; 56 | product: Product; 57 | discounts: DiscountLineItem[]; 58 | } 59 | 60 | export interface PricePreviewResponse { 61 | data: { 62 | customerId: string | null; 63 | addressId: string | null; 64 | businessId: string | null; 65 | currencyCode: CurrencyCode; 66 | address: { 67 | countryCode: string; 68 | postalCode: string | null; 69 | } | null; 70 | customerIpAddress: string | null; 71 | discountId: string | null; 72 | details: { 73 | lineItems: LineItem[]; 74 | }; 75 | availablePaymentMethods: AvailablePaymentMethod[]; 76 | }; 77 | meta: { 78 | requestId: string; 79 | }; 80 | } 81 | -------------------------------------------------------------------------------- /types/shared/country-code.d.ts: -------------------------------------------------------------------------------- 1 | export type CountryCode = 2 | | 'AD' 3 | | 'AE' 4 | | 'AG' 5 | | 'AI' 6 | | 'AL' 7 | | 'AM' 8 | | 'AO' 9 | | 'AR' 10 | | 'AS' 11 | | 'AT' 12 | | 'AU' 13 | | 'AW' 14 | | 'AX' 15 | | 'AZ' 16 | | 'BA' 17 | | 'BB' 18 | | 'BD' 19 | | 'BE' 20 | | 'BF' 21 | | 'BG' 22 | | 'BH' 23 | | 'BI' 24 | | 'BJ' 25 | | 'BL' 26 | | 'BM' 27 | | 'BN' 28 | | 'BO' 29 | | 'BQ' 30 | | 'BR' 31 | | 'BS' 32 | | 'BT' 33 | | 'BV' 34 | | 'BW' 35 | | 'BZ' 36 | | 'CA' 37 | | 'CC' 38 | | 'CG' 39 | | 'CH' 40 | | 'CI' 41 | | 'CK' 42 | | 'CL' 43 | | 'CM' 44 | | 'CN' 45 | | 'CO' 46 | | 'CR' 47 | | 'CV' 48 | | 'CW' 49 | | 'CX' 50 | | 'CY' 51 | | 'CZ' 52 | | 'DE' 53 | | 'DJ' 54 | | 'DK' 55 | | 'DM' 56 | | 'DO' 57 | | 'DZ' 58 | | 'EC' 59 | | 'EE' 60 | | 'EG' 61 | | 'EH' 62 | | 'ER' 63 | | 'ES' 64 | | 'ET' 65 | | 'FI' 66 | | 'FJ' 67 | | 'FK' 68 | | 'FM' 69 | | 'FO' 70 | | 'FR' 71 | | 'GA' 72 | | 'GB' 73 | | 'GD' 74 | | 'GE' 75 | | 'GF' 76 | | 'GG' 77 | | 'GH' 78 | | 'GI' 79 | | 'GL' 80 | | 'GM' 81 | | 'GN' 82 | | 'GP' 83 | | 'GQ' 84 | | 'GR' 85 | | 'GS' 86 | | 'GT' 87 | | 'GU' 88 | | 'GW' 89 | | 'GY' 90 | | 'HK' 91 | | 'HM' 92 | | 'HN' 93 | | 'HR' 94 | | 'HU' 95 | | 'ID' 96 | | 'IE' 97 | | 'IL' 98 | | 'IM' 99 | | 'IN' 100 | | 'IO' 101 | | 'IQ' 102 | | 'IS' 103 | | 'IT' 104 | | 'JE' 105 | | 'JM' 106 | | 'JO' 107 | | 'JP' 108 | | 'KE' 109 | | 'KG' 110 | | 'KH' 111 | | 'KI' 112 | | 'KM' 113 | | 'KN' 114 | | 'KR' 115 | | 'KW' 116 | | 'KY' 117 | | 'KZ' 118 | | 'LA' 119 | | 'LB' 120 | | 'LC' 121 | | 'LI' 122 | | 'LK' 123 | | 'LR' 124 | | 'LS' 125 | | 'LT' 126 | | 'LU' 127 | | 'LV' 128 | | 'MA' 129 | | 'MC' 130 | | 'MD' 131 | | 'ME' 132 | | 'MF' 133 | | 'MG' 134 | | 'MH' 135 | | 'MK' 136 | | 'MN' 137 | | 'MO' 138 | | 'MP' 139 | | 'MQ' 140 | | 'MR' 141 | | 'MS' 142 | | 'MT' 143 | | 'MU' 144 | | 'MV' 145 | | 'MW' 146 | | 'MX' 147 | | 'MY' 148 | | 'MZ' 149 | | 'NA' 150 | | 'NC' 151 | | 'NE' 152 | | 'NF' 153 | | 'NG' 154 | | 'NL' 155 | | 'NO' 156 | | 'NP' 157 | | 'NR' 158 | | 'NU' 159 | | 'NZ' 160 | | 'OM' 161 | | 'PA' 162 | | 'PE' 163 | | 'PF' 164 | | 'PG' 165 | | 'PH' 166 | | 'PK' 167 | | 'PL' 168 | | 'PM' 169 | | 'PN' 170 | | 'PR' 171 | | 'PS' 172 | | 'PT' 173 | | 'PW' 174 | | 'PY' 175 | | 'QA' 176 | | 'RE' 177 | | 'RO' 178 | | 'RS' 179 | | 'RW' 180 | | 'SA' 181 | | 'SB' 182 | | 'SC' 183 | | 'SE' 184 | | 'SG' 185 | | 'SH' 186 | | 'SI' 187 | | 'SJ' 188 | | 'SK' 189 | | 'SL' 190 | | 'SM' 191 | | 'SN' 192 | | 'SR' 193 | | 'ST' 194 | | 'SV' 195 | | 'SX' 196 | | 'SZ' 197 | | 'TC' 198 | | 'TD' 199 | | 'TF' 200 | | 'TG' 201 | | 'TH' 202 | | 'TJ' 203 | | 'TK' 204 | | 'TL' 205 | | 'TM' 206 | | 'TN' 207 | | 'TO' 208 | | 'TR' 209 | | 'TT' 210 | | 'TV' 211 | | 'TW' 212 | | 'TZ' 213 | | 'UA' 214 | | 'UG' 215 | | 'UM' 216 | | 'US' 217 | | 'UY' 218 | | 'UZ' 219 | | 'VA' 220 | | 'VC' 221 | | 'VG' 222 | | 'VI' 223 | | 'VN' 224 | | 'VU' 225 | | 'WF' 226 | | 'WS' 227 | | 'XK' 228 | | 'YT' 229 | | 'ZA' 230 | | 'ZM'; 231 | -------------------------------------------------------------------------------- /types/shared/currency-code.d.ts: -------------------------------------------------------------------------------- 1 | export type CurrencyCode = 2 | | 'USD' 3 | | 'EUR' 4 | | 'GBP' 5 | | 'JPY' 6 | | 'AUD' 7 | | 'CAD' 8 | | 'CHF' 9 | | 'HKD' 10 | | 'SGD' 11 | | 'SEK' 12 | | 'ARS' 13 | | 'BRL' 14 | | 'CNY' 15 | | 'COP' 16 | | 'CZK' 17 | | 'DKK' 18 | | 'HUF' 19 | | 'ILS' 20 | | 'INR' 21 | | 'KRW' 22 | | 'MXN' 23 | | 'NOK' 24 | | 'NZD' 25 | | 'PLN' 26 | | 'RUB' 27 | | 'THB' 28 | | 'TRY' 29 | | 'TWD' 30 | | 'UAH' 31 | | 'ZAR'; 32 | -------------------------------------------------------------------------------- /types/shared/shared.d.ts: -------------------------------------------------------------------------------- 1 | import { CountryCode } from './country-code'; 2 | import { CurrencyCode } from './currency-code'; 3 | 4 | export type AvailablePaymentMethod = 5 | | 'alipay' 6 | | 'apple_pay' 7 | | 'bancontact' 8 | | 'card' 9 | | 'google_pay' 10 | | 'ideal' 11 | | 'paypal' 12 | | 'saved_payment_methods'; 13 | 14 | export type Variant = 'multi-page' | 'one-page'; 15 | 16 | export type TaxMode = 'account_setting' | 'external' | 'internal'; 17 | 18 | export type Status = 'active' | 'archived'; 19 | 20 | export type TaxCategory = 21 | | 'digital-goods' 22 | | 'ebooks' 23 | | 'implementation-services' 24 | | 'professional-services' 25 | | 'saas' 26 | | 'software-programming-services' 27 | | 'standard' 28 | | 'training-services' 29 | | 'website-hosting'; 30 | 31 | export interface Totals { 32 | subtotal: string; 33 | discount: string; 34 | tax: string; 35 | total: string; 36 | } 37 | 38 | export interface Product { 39 | id: string; 40 | name: string; 41 | description: string | null; 42 | taxCategory: TaxCategory; 43 | imageUrl: string | null; 44 | customData: Record | null; 45 | status: Status; 46 | createdAt: string; 47 | importMeta: ImportMeta | null; 48 | } 49 | 50 | export interface UnitPrice { 51 | amount: string; 52 | currencyCode: CurrencyCode; 53 | } 54 | 55 | export interface TimePeriod { 56 | interval: 'day' | 'week' | 'month' | 'year'; 57 | frequency: number; 58 | } 59 | 60 | export interface Quantity { 61 | minimum: number; 62 | maximum: number; 63 | } 64 | 65 | export interface UnitPriceOverride { 66 | countryCodes: CountryCode[]; 67 | unitPrice: UnitPrice; 68 | } 69 | 70 | export interface ImportMeta { 71 | externalId: string | null; 72 | importedFrom: string; 73 | } 74 | 75 | export interface Price { 76 | id: string; 77 | productId: string; 78 | name: string | null; 79 | description: string; 80 | billingCycle: TimePeriod | null; 81 | trialPeriod: TimePeriod | null; 82 | taxMode: TaxMode; 83 | unitPrice: UnitPrice; 84 | unitPriceOverrides: UnitPriceOverride[]; 85 | quantity: Quantity; 86 | status: Status; 87 | customData: Record | null; 88 | importMeta: ImportMeta | null; 89 | } 90 | 91 | export interface NonCatalogProductRequest { 92 | name: string; 93 | taxCategory: TaxCategory; 94 | description?: string | null; 95 | imageUrl?: string | null; 96 | customData?: Record; 97 | } 98 | 99 | interface NonCatalogBasePriceRequest { 100 | name?: string; 101 | description: string; 102 | unitPrice: UnitPrice; 103 | billingCycle?: TimePeriod; 104 | trialPeriod?: TimePeriod; 105 | taxMode?: TaxMode; 106 | unitPriceOverrides?: UnitPriceOverride[]; 107 | quantity?: Quantity; 108 | customData?: Record; 109 | } 110 | 111 | interface NonCatalogBasePriceRequestWithProductId extends NonCatalogBasePriceRequest { 112 | productId: string; 113 | product?: never; 114 | } 115 | 116 | interface NonCatalogBasePriceRequestWithProduct extends NonCatalogBasePriceRequest { 117 | productId?: never; 118 | product: NonCatalogProductRequest; 119 | } 120 | 121 | export type NonCatalogPriceRequest = NonCatalogBasePriceRequestWithProductId | NonCatalogBasePriceRequestWithProduct; 122 | -------------------------------------------------------------------------------- /types/transaction-preview/transaction-preview.d.ts: -------------------------------------------------------------------------------- 1 | import { AvailablePaymentMethod, NonCatalogPriceRequest, Price, Product, Totals } from '../shared/shared'; 2 | import { CurrencyCode } from '../shared/currency-code'; 3 | 4 | interface BaseTransactionItemPreview { 5 | quantity: number; 6 | includeInTotals?: boolean; 7 | } 8 | 9 | interface TransactionItemWithPriceId extends BaseTransactionItemPreview { 10 | priceId: string; 11 | price?: never; 12 | } 13 | 14 | interface TransactionItemWithPrice extends BaseTransactionItemPreview { 15 | priceId?: never; 16 | price: NonCatalogPriceRequest; 17 | } 18 | 19 | export type TransactionPreviewItem = TransactionItemWithPriceId | TransactionItemWithPrice; 20 | 21 | export interface TransactionPreviewParams { 22 | items: TransactionPreviewItem[]; 23 | customerId?: string; 24 | addressId?: string; 25 | businessId?: string; 26 | currencyCode?: CurrencyCode; 27 | discountId?: string; 28 | address?: { 29 | countryCode: string; 30 | postalCode?: string; 31 | }; 32 | customerIpAddress?: string; 33 | ignoreTrials?: boolean; 34 | } 35 | 36 | interface BillingPeriod { 37 | startsAt: string; 38 | endsAt: string; 39 | } 40 | 41 | interface Proration { 42 | rate: string; 43 | billingPeriod: BillingPeriod; 44 | } 45 | 46 | interface TransactionItem { 47 | price: Price; 48 | quantity: number; 49 | includeInTotals: boolean; 50 | proration: Proration | null; 51 | } 52 | 53 | interface TransactionDetailsTaxRate { 54 | taxRate: string; 55 | totals: Totals; 56 | } 57 | 58 | interface TransactionTotal { 59 | subtotal: string; 60 | discount: string; 61 | tax: string; 62 | total: string; 63 | credit: string; 64 | balance: string; 65 | grandTotal: string; 66 | fee: string | null; 67 | earnings: string | null; 68 | currencyCode: CurrencyCode; 69 | } 70 | 71 | interface TransactionLineItems { 72 | priceId: string; 73 | quantity: number; 74 | taxRate: string; 75 | unitTotals: Totals; 76 | totals: Totals; 77 | product: Product; 78 | } 79 | 80 | interface TransactionDetails { 81 | taxRatesUsed: TransactionDetailsTaxRate[]; 82 | totals: TransactionTotal; 83 | lineItems: TransactionLineItems[]; 84 | } 85 | 86 | export interface TransactionPreviewResponse { 87 | data: { 88 | customerId: string | null; 89 | addressId: string | null; 90 | businessId: string | null; 91 | currencyCode: CurrencyCode; 92 | address: { 93 | countryCode: string; 94 | postalCode: string | null; 95 | } | null; 96 | customerIpAddress: string | null; 97 | discountId: string | null; 98 | ignoreTrials: boolean; 99 | items: TransactionItem[]; 100 | details: TransactionDetails; 101 | availablePaymentMethods: AvailablePaymentMethod[]; 102 | }; 103 | meta: { 104 | requestId: string; 105 | }; 106 | } 107 | --------------------------------------------------------------------------------