├── .gitignore ├── LICENSE ├── README.md ├── convex ├── README.md ├── _generated │ ├── api.d.ts │ ├── api.js │ ├── dataModel.d.ts │ ├── server.d.ts │ └── server.js ├── http.ts ├── messages.ts ├── payments.ts ├── schema.ts ├── stripe.ts └── tsconfig.json ├── index.html ├── package-lock.json ├── package.json ├── screenshot.png ├── src ├── App.tsx ├── index.css ├── main.tsx └── vite-env.d.js ├── tsconfig.json └── vite.config.js /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .DS_Store 3 | dist 4 | .env.local 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 2024 Convex, Inc. 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Convex Stripe Demo 2 | 3 | This example app demonstrates how to integrate Stripe, the payments platform, with Convex, the backend application platform. We keep track of payments in Convex and fulfill orders when they're confirmed by Stripe. 4 | 5 | ![Screenshot of the app and Stripe's UI](./screenshot.png) 6 | 7 | Features: 8 | 9 | - You can test the payment flow end to end using Stripe's test card numbers 10 | 11 | This integration works! You can see a production deployment at this live site: https://xixixao.github.io/paymorebeseen/. 12 | 13 | Read a deep dive into this repo in [Wake up, you need to make money! (ft. Stripe)](https://stack.convex.dev/stripe-with-convex) on Stack. 14 | 15 | ## Setting up 16 | 17 | Run: 18 | 19 | ``` 20 | npm install 21 | npm run dev 22 | ``` 23 | 24 | This will guide you through making a Convex project. 25 | 26 | To test the payments flow, follow these steps: 27 | 28 | 1. Sign up for Stripe for free at https://stripe.com/ 29 | 2. [Install the stripe CLI](https://stripe.com/docs/stripe-cli) 30 | 3. Get your HTTP Actions URL from the Convex dashboard (Settings -> URL & Deploy Key -> Show development credentials). 31 | This should looks something like https://happy-dog-123.convex.site 32 | 4. Run 33 | 34 | ``` 35 | stripe listen --forward-to /stripe 36 | ``` 37 | 38 | 5. Copy the "Your webhook signing secret" from the output of the `listen` command, and set it as `STRIPE_WEBHOOKS_SECRET` environment variable on your Convex dashboard or via the CLI: 39 | 40 | ```sh 41 | npx convex env set STRIPE_WEBHOOKS_SECRET 42 | ``` 43 | 6. Copy your test secret API key from the code example on https://stripe.com/docs/checkout/quickstart and set it as `STRIPE_KEY` environment variable on your Convex dashboard or via the CLI: 44 | 45 | ```sh 46 | npx convex env set STRIPE_KEY 47 | ``` 48 | 49 | 50 | You can then use the test credit card details to go through the payment flow, see https://stripe.com/docs/checkout/quickstart#testing 51 | 52 | # What is Convex? 53 | 54 | [Convex](https://convex.dev) is a hosted backend platform with a 55 | built-in database that lets you write your 56 | [database schema](https://docs.convex.dev/database/schemas) and 57 | [server functions](https://docs.convex.dev/functions) in 58 | [TypeScript](https://docs.convex.dev/typescript). Server-side database 59 | [queries](https://docs.convex.dev/functions/query-functions) automatically 60 | [cache](https://docs.convex.dev/functions/query-functions#caching--reactivity) and 61 | [subscribe](https://docs.convex.dev/client/react#reactivity) to data, powering a 62 | [realtime `useQuery` hook](https://docs.convex.dev/client/react#fetching-data) in our 63 | [React client](https://docs.convex.dev/client/react). There are also 64 | [Python](https://docs.convex.dev/client/python), 65 | [Rust](https://docs.convex.dev/client/rust), 66 | [ReactNative](https://docs.convex.dev/client/react-native), and 67 | [Node](https://docs.convex.dev/client/javascript) clients, as well as a straightforward 68 | [HTTP API](https://github.com/get-convex/convex-js/blob/main/src/browser/http_client.ts#L40). 69 | 70 | The database support 71 | [NoSQL-style documents](https://docs.convex.dev/database/document-storage) with 72 | [relationships](https://docs.convex.dev/database/document-ids) and 73 | [custom indexes](https://docs.convex.dev/database/indexes/) 74 | (including on fields in nested objects). 75 | 76 | The 77 | [`query`](https://docs.convex.dev/functions/query-functions) and 78 | [`mutation`](https://docs.convex.dev/functions/mutation-functions) server functions have transactional, 79 | low latency access to the database and leverage our 80 | [`v8` runtime](https://docs.convex.dev/functions/runtimes) with 81 | [determinism guardrails](https://docs.convex.dev/functions/runtimes#using-randomness-and-time-in-queries-and-mutations) 82 | to provide the strongest ACID guarantees on the market: 83 | immediate consistency, 84 | serializable isolation, and 85 | automatic conflict resolution via 86 | [optimistic multi-version concurrency control](https://docs.convex.dev/database/advanced/occ) (OCC / MVCC). 87 | 88 | The [`action` server functions](https://docs.convex.dev/functions/actions) have 89 | access to external APIs and enable other side-effects and non-determinism in 90 | either our 91 | [optimized `v8` runtime](https://docs.convex.dev/functions/runtimes) or a more 92 | [flexible `node` runtime](https://docs.convex.dev/functions/runtimes#nodejs-runtime). 93 | 94 | Functions can run in the background via 95 | [scheduling](https://docs.convex.dev/scheduling/scheduled-functions) and 96 | [cron jobs](https://docs.convex.dev/scheduling/cron-jobs). 97 | 98 | Development is cloud-first, with 99 | [hot reloads for server function](https://docs.convex.dev/cli#run-the-convex-dev-server) editing via the 100 | [CLI](https://docs.convex.dev/cli). There is a 101 | [dashbord UI](https://docs.convex.dev/dashboard) to 102 | [browse and edit data](https://docs.convex.dev/dashboard/deployments/data), 103 | [edit environment variables](https://docs.convex.dev/production/environment-variables), 104 | [view logs](https://docs.convex.dev/dashboard/deployments/logs), 105 | [run server functions](https://docs.convex.dev/dashboard/deployments/functions), and more. 106 | 107 | There are built-in features for 108 | [reactive pagination](https://docs.convex.dev/database/pagination), 109 | [file storage](https://docs.convex.dev/file-storage), 110 | [reactive search](https://docs.convex.dev/text-search), 111 | [https endpoints](https://docs.convex.dev/functions/http-actions) (for webhooks), 112 | [streaming import/export](https://docs.convex.dev/database/import-export/), and 113 | [runtime data validation](https://docs.convex.dev/database/schemas#validators) for 114 | [function arguments](https://docs.convex.dev/functions/args-validation) and 115 | [database data](https://docs.convex.dev/database/schemas#schema-validation). 116 | 117 | Everything scales automatically, and it’s [free to start](https://www.convex.dev/plans). 118 | -------------------------------------------------------------------------------- /convex/README.md: -------------------------------------------------------------------------------- 1 | # Welcome to your Convex functions directory! 2 | 3 | Write your Convex functions here. See 4 | https://docs.convex.dev/using/writing-convex-functions for more. 5 | 6 | A query function that takes two arguments looks like: 7 | 8 | ```ts 9 | // functions.js 10 | import { query } from "./_generated/server"; 11 | import { v } from "convex/values"; 12 | 13 | export const myQueryFunction = query({ 14 | // Validators for arguments. 15 | args: { 16 | first: v.number(), 17 | second: v.string(), 18 | }, 19 | 20 | // Function implementation. 21 | hander: async (ctx, args) => { 22 | // Read the database as many times as you need here. 23 | // See https://docs.convex.dev/database/reading-data. 24 | const documents = await ctx.db.query("tablename").collect(); 25 | 26 | // Arguments passed from the client are properties of the args object. 27 | console.log(args.first, args.second); 28 | 29 | // Write arbitrary JavaScript here: filter, aggregate, build derived data, 30 | // remove non-public properties, or create new objects. 31 | return documents; 32 | }, 33 | }); 34 | ``` 35 | 36 | Using this query function in a React component looks like: 37 | 38 | ```ts 39 | const data = useQuery(api.functions.myQueryFunction, { 40 | first: 10, 41 | second: "hello", 42 | }); 43 | ``` 44 | 45 | A mutation function looks like: 46 | 47 | ```ts 48 | // functions.js 49 | import { mutation } from "./_generated/server"; 50 | import { v } from "convex/values"; 51 | 52 | export const myMutationFunction = mutation({ 53 | // Validators for arguments. 54 | args: { 55 | first: v.string(), 56 | second: v.string(), 57 | }, 58 | 59 | // Function implementation. 60 | hander: async (ctx, args) => { 61 | // Insert or modify documents in the database here. 62 | // Mutations can also read from the database like queries. 63 | // See https://docs.convex.dev/database/writing-data. 64 | const message = { body: args.first, author: args.second }; 65 | const id = await ctx.db.insert("messages", message); 66 | 67 | // Optionally, return a value from your mutation. 68 | return await ctx.db.get(id); 69 | }, 70 | }); 71 | ``` 72 | 73 | Using this mutation function in a React component looks like: 74 | 75 | ```ts 76 | const mutation = useMutation(api.functions.myMutationFunction); 77 | function handleButtonPress() { 78 | // fire and forget, the most common way to use mutations 79 | mutation({ first: "Hello!", second: "me" }); 80 | // OR 81 | // use the result once the mutation has completed 82 | mutation({ first: "Hello!", second: "me" }).then((result) => 83 | console.log(result) 84 | ); 85 | } 86 | ``` 87 | 88 | Use the Convex CLI to push your functions to a deployment. See everything 89 | the Convex CLI can do by running `npx convex -h` in your project root 90 | directory. To learn more, launch the docs with `npx convex docs`. 91 | -------------------------------------------------------------------------------- /convex/_generated/api.d.ts: -------------------------------------------------------------------------------- 1 | /* eslint-disable */ 2 | /** 3 | * Generated `api` utility. 4 | * 5 | * THIS CODE IS AUTOMATICALLY GENERATED. 6 | * 7 | * Generated by convex@1.14.0. 8 | * To regenerate, run `npx convex dev`. 9 | * @module 10 | */ 11 | 12 | import type { 13 | ApiFromModules, 14 | FilterApi, 15 | FunctionReference, 16 | } from "convex/server"; 17 | import type * as http from "../http.js"; 18 | import type * as messages from "../messages.js"; 19 | import type * as payments from "../payments.js"; 20 | import type * as stripe from "../stripe.js"; 21 | 22 | /** 23 | * A utility for referencing Convex functions in your app's API. 24 | * 25 | * Usage: 26 | * ```js 27 | * const myFunctionReference = api.myModule.myFunction; 28 | * ``` 29 | */ 30 | declare const fullApi: ApiFromModules<{ 31 | http: typeof http; 32 | messages: typeof messages; 33 | payments: typeof payments; 34 | stripe: typeof stripe; 35 | }>; 36 | export declare const api: FilterApi< 37 | typeof fullApi, 38 | FunctionReference 39 | >; 40 | export declare const internal: FilterApi< 41 | typeof fullApi, 42 | FunctionReference 43 | >; 44 | -------------------------------------------------------------------------------- /convex/_generated/api.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable */ 2 | /** 3 | * Generated `api` utility. 4 | * 5 | * THIS CODE IS AUTOMATICALLY GENERATED. 6 | * 7 | * Generated by convex@1.14.0. 8 | * To regenerate, run `npx convex dev`. 9 | * @module 10 | */ 11 | 12 | import { anyApi } from "convex/server"; 13 | 14 | /** 15 | * A utility for referencing Convex functions in your app's API. 16 | * 17 | * Usage: 18 | * ```js 19 | * const myFunctionReference = api.myModule.myFunction; 20 | * ``` 21 | */ 22 | export const api = anyApi; 23 | export const internal = anyApi; 24 | -------------------------------------------------------------------------------- /convex/_generated/dataModel.d.ts: -------------------------------------------------------------------------------- 1 | /* eslint-disable */ 2 | /** 3 | * Generated data model types. 4 | * 5 | * THIS CODE IS AUTOMATICALLY GENERATED. 6 | * 7 | * Generated by convex@1.14.0. 8 | * To regenerate, run `npx convex dev`. 9 | * @module 10 | */ 11 | 12 | import type { 13 | DataModelFromSchemaDefinition, 14 | DocumentByName, 15 | TableNamesInDataModel, 16 | SystemTableNames, 17 | } from "convex/server"; 18 | import type { GenericId } from "convex/values"; 19 | import schema from "../schema.js"; 20 | 21 | /** 22 | * The names of all of your Convex tables. 23 | */ 24 | export type TableNames = TableNamesInDataModel; 25 | 26 | /** 27 | * The type of a document stored in Convex. 28 | * 29 | * @typeParam TableName - A string literal type of the table name (like "users"). 30 | */ 31 | export type Doc = DocumentByName< 32 | DataModel, 33 | TableName 34 | >; 35 | 36 | /** 37 | * An identifier for a document in Convex. 38 | * 39 | * Convex documents are uniquely identified by their `Id`, which is accessible 40 | * on the `_id` field. To learn more, see [Document IDs](https://docs.convex.dev/using/document-ids). 41 | * 42 | * Documents can be loaded using `db.get(id)` in query and mutation functions. 43 | * 44 | * IDs are just strings at runtime, but this type can be used to distinguish them from other 45 | * strings when type checking. 46 | * 47 | * @typeParam TableName - A string literal type of the table name (like "users"). 48 | */ 49 | export type Id = 50 | GenericId; 51 | 52 | /** 53 | * A type describing your Convex data model. 54 | * 55 | * This type includes information about what tables you have, the type of 56 | * documents stored in those tables, and the indexes defined on them. 57 | * 58 | * This type is used to parameterize methods like `queryGeneric` and 59 | * `mutationGeneric` to make them type-safe. 60 | */ 61 | export type DataModel = DataModelFromSchemaDefinition; 62 | -------------------------------------------------------------------------------- /convex/_generated/server.d.ts: -------------------------------------------------------------------------------- 1 | /* eslint-disable */ 2 | /** 3 | * Generated utilities for implementing server-side Convex query and mutation functions. 4 | * 5 | * THIS CODE IS AUTOMATICALLY GENERATED. 6 | * 7 | * Generated by convex@1.14.0. 8 | * To regenerate, run `npx convex dev`. 9 | * @module 10 | */ 11 | 12 | import { 13 | ActionBuilder, 14 | HttpActionBuilder, 15 | MutationBuilder, 16 | QueryBuilder, 17 | GenericActionCtx, 18 | GenericMutationCtx, 19 | GenericQueryCtx, 20 | GenericDatabaseReader, 21 | GenericDatabaseWriter, 22 | } from "convex/server"; 23 | import type { DataModel } from "./dataModel.js"; 24 | 25 | /** 26 | * Define a query in this Convex app's public API. 27 | * 28 | * This function will be allowed to read your Convex database and will be accessible from the client. 29 | * 30 | * @param func - The query function. It receives a {@link QueryCtx} as its first argument. 31 | * @returns The wrapped query. Include this as an `export` to name it and make it accessible. 32 | */ 33 | export declare const query: QueryBuilder; 34 | 35 | /** 36 | * Define a query that is only accessible from other Convex functions (but not from the client). 37 | * 38 | * This function will be allowed to read from your Convex database. It will not be accessible from the client. 39 | * 40 | * @param func - The query function. It receives a {@link QueryCtx} as its first argument. 41 | * @returns The wrapped query. Include this as an `export` to name it and make it accessible. 42 | */ 43 | export declare const internalQuery: QueryBuilder; 44 | 45 | /** 46 | * Define a mutation in this Convex app's public API. 47 | * 48 | * This function will be allowed to modify your Convex database and will be accessible from the client. 49 | * 50 | * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument. 51 | * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible. 52 | */ 53 | export declare const mutation: MutationBuilder; 54 | 55 | /** 56 | * Define a mutation that is only accessible from other Convex functions (but not from the client). 57 | * 58 | * This function will be allowed to modify your Convex database. It will not be accessible from the client. 59 | * 60 | * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument. 61 | * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible. 62 | */ 63 | export declare const internalMutation: MutationBuilder; 64 | 65 | /** 66 | * Define an action in this Convex app's public API. 67 | * 68 | * An action is a function which can execute any JavaScript code, including non-deterministic 69 | * code and code with side-effects, like calling third-party services. 70 | * They can be run in Convex's JavaScript environment or in Node.js using the "use node" directive. 71 | * They can interact with the database indirectly by calling queries and mutations using the {@link ActionCtx}. 72 | * 73 | * @param func - The action. It receives an {@link ActionCtx} as its first argument. 74 | * @returns The wrapped action. Include this as an `export` to name it and make it accessible. 75 | */ 76 | export declare const action: ActionBuilder; 77 | 78 | /** 79 | * Define an action that is only accessible from other Convex functions (but not from the client). 80 | * 81 | * @param func - The function. It receives an {@link ActionCtx} as its first argument. 82 | * @returns The wrapped function. Include this as an `export` to name it and make it accessible. 83 | */ 84 | export declare const internalAction: ActionBuilder; 85 | 86 | /** 87 | * Define an HTTP action. 88 | * 89 | * This function will be used to respond to HTTP requests received by a Convex 90 | * deployment if the requests matches the path and method where this action 91 | * is routed. Be sure to route your action in `convex/http.js`. 92 | * 93 | * @param func - The function. It receives an {@link ActionCtx} as its first argument. 94 | * @returns The wrapped function. Import this function from `convex/http.js` and route it to hook it up. 95 | */ 96 | export declare const httpAction: HttpActionBuilder; 97 | 98 | /** 99 | * A set of services for use within Convex query functions. 100 | * 101 | * The query context is passed as the first argument to any Convex query 102 | * function run on the server. 103 | * 104 | * This differs from the {@link MutationCtx} because all of the services are 105 | * read-only. 106 | */ 107 | export type QueryCtx = GenericQueryCtx; 108 | 109 | /** 110 | * A set of services for use within Convex mutation functions. 111 | * 112 | * The mutation context is passed as the first argument to any Convex mutation 113 | * function run on the server. 114 | */ 115 | export type MutationCtx = GenericMutationCtx; 116 | 117 | /** 118 | * A set of services for use within Convex action functions. 119 | * 120 | * The action context is passed as the first argument to any Convex action 121 | * function run on the server. 122 | */ 123 | export type ActionCtx = GenericActionCtx; 124 | 125 | /** 126 | * An interface to read from the database within Convex query functions. 127 | * 128 | * The two entry points are {@link DatabaseReader.get}, which fetches a single 129 | * document by its {@link Id}, or {@link DatabaseReader.query}, which starts 130 | * building a query. 131 | */ 132 | export type DatabaseReader = GenericDatabaseReader; 133 | 134 | /** 135 | * An interface to read from and write to the database within Convex mutation 136 | * functions. 137 | * 138 | * Convex guarantees that all writes within a single mutation are 139 | * executed atomically, so you never have to worry about partial writes leaving 140 | * your data in an inconsistent state. See [the Convex Guide](https://docs.convex.dev/understanding/convex-fundamentals/functions#atomicity-and-optimistic-concurrency-control) 141 | * for the guarantees Convex provides your functions. 142 | */ 143 | export type DatabaseWriter = GenericDatabaseWriter; 144 | -------------------------------------------------------------------------------- /convex/_generated/server.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable */ 2 | /** 3 | * Generated utilities for implementing server-side Convex query and mutation functions. 4 | * 5 | * THIS CODE IS AUTOMATICALLY GENERATED. 6 | * 7 | * Generated by convex@1.14.0. 8 | * To regenerate, run `npx convex dev`. 9 | * @module 10 | */ 11 | 12 | import { 13 | actionGeneric, 14 | httpActionGeneric, 15 | queryGeneric, 16 | mutationGeneric, 17 | internalActionGeneric, 18 | internalMutationGeneric, 19 | internalQueryGeneric, 20 | } from "convex/server"; 21 | 22 | /** 23 | * Define a query in this Convex app's public API. 24 | * 25 | * This function will be allowed to read your Convex database and will be accessible from the client. 26 | * 27 | * @param func - The query function. It receives a {@link QueryCtx} as its first argument. 28 | * @returns The wrapped query. Include this as an `export` to name it and make it accessible. 29 | */ 30 | export const query = queryGeneric; 31 | 32 | /** 33 | * Define a query that is only accessible from other Convex functions (but not from the client). 34 | * 35 | * This function will be allowed to read from your Convex database. It will not be accessible from the client. 36 | * 37 | * @param func - The query function. It receives a {@link QueryCtx} as its first argument. 38 | * @returns The wrapped query. Include this as an `export` to name it and make it accessible. 39 | */ 40 | export const internalQuery = internalQueryGeneric; 41 | 42 | /** 43 | * Define a mutation in this Convex app's public API. 44 | * 45 | * This function will be allowed to modify your Convex database and will be accessible from the client. 46 | * 47 | * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument. 48 | * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible. 49 | */ 50 | export const mutation = mutationGeneric; 51 | 52 | /** 53 | * Define a mutation that is only accessible from other Convex functions (but not from the client). 54 | * 55 | * This function will be allowed to modify your Convex database. It will not be accessible from the client. 56 | * 57 | * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument. 58 | * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible. 59 | */ 60 | export const internalMutation = internalMutationGeneric; 61 | 62 | /** 63 | * Define an action in this Convex app's public API. 64 | * 65 | * An action is a function which can execute any JavaScript code, including non-deterministic 66 | * code and code with side-effects, like calling third-party services. 67 | * They can be run in Convex's JavaScript environment or in Node.js using the "use node" directive. 68 | * They can interact with the database indirectly by calling queries and mutations using the {@link ActionCtx}. 69 | * 70 | * @param func - The action. It receives an {@link ActionCtx} as its first argument. 71 | * @returns The wrapped action. Include this as an `export` to name it and make it accessible. 72 | */ 73 | export const action = actionGeneric; 74 | 75 | /** 76 | * Define an action that is only accessible from other Convex functions (but not from the client). 77 | * 78 | * @param func - The function. It receives an {@link ActionCtx} as its first argument. 79 | * @returns The wrapped function. Include this as an `export` to name it and make it accessible. 80 | */ 81 | export const internalAction = internalActionGeneric; 82 | 83 | /** 84 | * Define a Convex HTTP action. 85 | * 86 | * @param func - The function. It receives an {@link ActionCtx} as its first argument, and a `Request` object 87 | * as its second. 88 | * @returns The wrapped endpoint function. Route a URL path to this function in `convex/http.js`. 89 | */ 90 | export const httpAction = httpActionGeneric; 91 | -------------------------------------------------------------------------------- /convex/http.ts: -------------------------------------------------------------------------------- 1 | import { httpRouter } from "convex/server"; 2 | import { httpAction } from "./_generated/server"; 3 | import { internal } from "./_generated/api"; 4 | 5 | const http = httpRouter(); 6 | 7 | http.route({ 8 | path: "/stripe", 9 | method: "POST", 10 | handler: httpAction(async (ctx, request) => { 11 | const signature: string = request.headers.get("stripe-signature") as string; 12 | const result = await ctx.runAction(internal.stripe.fulfill, { 13 | signature, 14 | payload: await request.text(), 15 | }); 16 | if (result.success) { 17 | return new Response(null, { 18 | status: 200, 19 | }); 20 | } else { 21 | return new Response("Webhook Error", { 22 | status: 400, 23 | }); 24 | } 25 | }), 26 | }); 27 | 28 | export default http; 29 | -------------------------------------------------------------------------------- /convex/messages.ts: -------------------------------------------------------------------------------- 1 | import { query } from "./_generated/server"; 2 | 3 | export const list = query({ 4 | handler: async (ctx) => { 5 | return await ctx.db.query("messages").collect(); 6 | }, 7 | }); 8 | -------------------------------------------------------------------------------- /convex/payments.ts: -------------------------------------------------------------------------------- 1 | import { v } from "convex/values"; 2 | import { internalMutation, query } from "./_generated/server"; 3 | 4 | export const getMessageId = query({ 5 | args: { paymentId: v.optional(v.id("payments")) }, 6 | handler: async (ctx, { paymentId }) => { 7 | if (paymentId === undefined) { 8 | return null; 9 | } 10 | return (await ctx.db.get(paymentId))?.messageId; 11 | }, 12 | }); 13 | 14 | export const create = internalMutation({ 15 | handler: async (ctx, { text }: { text: string }) => { 16 | return await ctx.db.insert("payments", { text }); 17 | }, 18 | }); 19 | 20 | export const markPending = internalMutation({ 21 | args: { paymentId: v.id("payments"), stripeId: v.string() }, 22 | handler: async (ctx, { paymentId, stripeId }) => { 23 | await ctx.db.patch(paymentId, { stripeId }); 24 | }, 25 | }); 26 | 27 | export const fulfill = internalMutation({ 28 | args: { stripeId: v.string() }, 29 | handler: async (ctx, { stripeId }) => { 30 | const { _id: paymentId, text } = (await ctx.db 31 | .query("payments") 32 | .withIndex("stripeId", (q) => q.eq("stripeId", stripeId)) 33 | .unique())!; 34 | const messageId = await ctx.db.insert("messages", { text }); 35 | await ctx.db.patch(paymentId, { messageId }); 36 | }, 37 | }); 38 | -------------------------------------------------------------------------------- /convex/schema.ts: -------------------------------------------------------------------------------- 1 | import { defineSchema, defineTable } from "convex/server"; 2 | import { v } from "convex/values"; 3 | 4 | export default defineSchema( 5 | { 6 | payments: defineTable({ 7 | text: v.string(), 8 | // If present the payment has been initiated 9 | stripeId: v.optional(v.string()), 10 | // If present the payment has been fulfilled 11 | messageId: v.optional(v.id("messages")), 12 | }).index("stripeId", ["stripeId"]), 13 | messages: defineTable({ 14 | text: v.string(), 15 | }), 16 | }, 17 | { schemaValidation: false } 18 | ); 19 | -------------------------------------------------------------------------------- /convex/stripe.ts: -------------------------------------------------------------------------------- 1 | import { v } from "convex/values"; 2 | import { action, internalAction } from "./_generated/server"; 3 | import Stripe from "stripe"; 4 | import { internal } from "./_generated/api"; 5 | 6 | export const pay = action({ 7 | args: { text: v.string() }, 8 | handler: async ({ runMutation }, { text }) => { 9 | const domain = process.env.HOSTING_URL ?? "http://localhost:5173"; 10 | const stripe = new Stripe(process.env.STRIPE_KEY!, { 11 | apiVersion: "2022-11-15", 12 | }); 13 | const paymentId = await runMutation(internal.payments.create, { text }); 14 | const session = await stripe.checkout.sessions.create({ 15 | line_items: [ 16 | { 17 | price_data: { 18 | currency: "USD", 19 | unit_amount: 100, 20 | tax_behavior: "exclusive", 21 | product_data: { 22 | name: "One message of your choosing", 23 | }, 24 | }, 25 | quantity: 1, 26 | }, 27 | ], 28 | mode: "payment", 29 | success_url: `${domain}?paymentId=${paymentId}`, 30 | cancel_url: `${domain}`, 31 | automatic_tax: { enabled: true }, 32 | }); 33 | 34 | await runMutation(internal.payments.markPending, { 35 | paymentId, 36 | stripeId: session.id, 37 | }); 38 | return session.url; 39 | }, 40 | }); 41 | 42 | export const fulfill = internalAction({ 43 | args: { signature: v.string(), payload: v.string() }, 44 | handler: async ({ runMutation }, { signature, payload }) => { 45 | const stripe = new Stripe(process.env.STRIPE_KEY!, { 46 | apiVersion: "2022-11-15", 47 | }); 48 | 49 | const webhookSecret = process.env.STRIPE_WEBHOOKS_SECRET as string; 50 | try { 51 | const event = await stripe.webhooks.constructEventAsync( 52 | payload, 53 | signature, 54 | webhookSecret 55 | ); 56 | if (event.type === "checkout.session.completed") { 57 | const stripeId = (event.data.object as { id: string }).id; 58 | await runMutation(internal.payments.fulfill, { stripeId }); 59 | } 60 | return { success: true }; 61 | } catch (err) { 62 | console.error(err); 63 | return { success: false, error: (err as { message: string }).message }; 64 | } 65 | }, 66 | }); 67 | -------------------------------------------------------------------------------- /convex/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | /* This TypeScript project config describes the environment that 3 | * Convex functions run in and is used to typecheck them. 4 | * You can modify it, but some settings required to use Convex. 5 | */ 6 | "compilerOptions": { 7 | /* These settings are not required by Convex and can be modified. */ 8 | "allowJs": true, 9 | "strict": true, 10 | 11 | /* These compiler options are required by Convex */ 12 | "target": "ESNext", 13 | "lib": ["ES2021", "dom"], 14 | "forceConsistentCasingInFileNames": true, 15 | "allowSyntheticDefaultImports": true, 16 | "module": "ESNext", 17 | "moduleResolution": "Node", 18 | "isolatedModules": true, 19 | "noEmit": true 20 | }, 21 | "include": ["./**/*"], 22 | "exclude": ["./_generated"] 23 | } 24 | -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Convex Paid Chat 7 | 8 | 9 |
10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "convex-tutorial", 3 | "version": "0.0.0", 4 | "scripts": { 5 | "dev": "npm-run-all dev:init --parallel dev:frontend dev:backend", 6 | "build": "vite build", 7 | "dev:backend": "convex dev", 8 | "dev:frontend": "vite --open --clearScreen false", 9 | "dev:init": "convex dev --until-success" 10 | }, 11 | "dependencies": { 12 | "convex": "^1.0.2", 13 | "react": "^17.0.2", 14 | "react-dom": "^17.0.2", 15 | "stripe": "^12.12.0" 16 | }, 17 | "devDependencies": { 18 | "@types/react": "^18.2.14", 19 | "@types/react-dom": "^18.2.6", 20 | "@typescript-eslint/eslint-plugin": "^5.61.0", 21 | "@typescript-eslint/parser": "^5.61.0", 22 | "@vitejs/plugin-react": "^4.0.1", 23 | "npm-run-all": "^4.1.5", 24 | "typescript": "^5.0.2", 25 | "vite": "^4.4.0" 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/get-convex/convex-stripe-demo/1c68301b09632cc4c6e9e0ae96ef3e2eccc110d5/screenshot.png -------------------------------------------------------------------------------- /src/App.tsx: -------------------------------------------------------------------------------- 1 | import { FormEvent, useEffect, useState } from "react"; 2 | import { useAction, useQuery } from "convex/react"; 3 | import { api } from "../convex/_generated/api"; 4 | import { Id } from "../convex/_generated/dataModel"; 5 | 6 | export default function App() { 7 | const paymentId = useConsumeQueryParam("paymentId"); 8 | 9 | const sentMessageId = useQuery(api.payments.getMessageId, { 10 | paymentId: (paymentId ?? undefined) as Id<"payments"> | undefined, 11 | }); 12 | const messages = useQuery(api.messages.list) || []; 13 | 14 | const [newMessageText, setNewMessageText] = useState(""); 15 | const payAndSendMessage = useAction(api.stripe.pay); 16 | 17 | async function handleSendMessage(event: FormEvent) { 18 | event.preventDefault(); 19 | const paymentUrl = await payAndSendMessage({ text: newMessageText }); 20 | window.location.href = paymentUrl!; 21 | } 22 | return ( 23 |
24 |

Convex Paid Chat

25 |
    26 | {messages.map((message) => ( 27 |
  • 31 | {message.text} 32 | {new Date(message._creationTime).toLocaleTimeString()} 33 |
  • 34 | ))} 35 |
36 |
37 | setNewMessageText(event.target.value)} 40 | placeholder="Write a message…" 41 | /> 42 | 47 |
48 |
49 | ); 50 | } 51 | 52 | function useConsumeQueryParam(name: string) { 53 | const [value] = useState( 54 | new URLSearchParams(window.location.search).get(name) 55 | ); 56 | 57 | useEffect(() => { 58 | const currentUrl = new URL(window.location.href); 59 | const searchParams = currentUrl.searchParams; 60 | searchParams.delete(name); 61 | const consumedUrl = 62 | currentUrl.origin + currentUrl.pathname + searchParams.toString(); 63 | window.history.replaceState(null, "", consumedUrl); 64 | }, []); 65 | return value; 66 | } 67 | -------------------------------------------------------------------------------- /src/index.css: -------------------------------------------------------------------------------- 1 | /* reset */ 2 | * { 3 | margin: 0; 4 | padding: 0; 5 | border: 0; 6 | line-height: 1.5; 7 | } 8 | 9 | body { 10 | font-family: system-ui, "Segoe UI", Roboto, "Helvetica Neue", helvetica, 11 | sans-serif; 12 | } 13 | 14 | main { 15 | padding-top: 1em; 16 | padding-bottom: 1em; 17 | width: min(800px, 95vw); 18 | margin: 0 auto; 19 | } 20 | 21 | h1 { 22 | text-align: center; 23 | margin-bottom: 8px; 24 | font-size: 1.8em; 25 | font-weight: 500; 26 | } 27 | 28 | .badge { 29 | text-align: center; 30 | margin-bottom: 16px; 31 | } 32 | .badge span { 33 | background-color: #212529; 34 | color: #ffffff; 35 | border-radius: 6px; 36 | font-weight: bold; 37 | padding: 4px 8px 4px 8px; 38 | font-size: 0.75em; 39 | } 40 | 41 | ul { 42 | margin: 8px; 43 | border-radius: 8px; 44 | border: solid 1px lightgray; 45 | box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075); 46 | overflow: hidden; 47 | } 48 | 49 | ul:empty { 50 | display: none; 51 | } 52 | 53 | li { 54 | display: flex; 55 | justify-content: flex-start; 56 | padding: 8px 16px 8px 16px; 57 | border-bottom: solid 1px lightgray; 58 | font-size: 16px; 59 | } 60 | 61 | li.sent { 62 | background-color: #fff1cd; 63 | } 64 | 65 | li:last-child { 66 | border: 0; 67 | } 68 | 69 | li span:nth-child(1) { 70 | font-weight: bold; 71 | margin-right: 4px; 72 | white-space: nowrap; 73 | } 74 | li span:nth-child(2) { 75 | margin-right: 4px; 76 | word-break: break-word; 77 | } 78 | li span:nth-child(3) { 79 | color: #6c757d; 80 | margin-left: auto; 81 | white-space: nowrap; 82 | } 83 | 84 | form { 85 | display: flex; 86 | justify-content: center; 87 | } 88 | 89 | input:not([type]) { 90 | padding: 6px 12px 6px 12px; 91 | color: rgb(33, 37, 41); 92 | border: solid 1px rgb(206, 212, 218); 93 | border-radius: 8px; 94 | font-size: 16px; 95 | } 96 | 97 | input[type="submit"], 98 | button { 99 | margin-left: 4px; 100 | background: lightblue; 101 | color: white; 102 | padding: 6px 12px 6px 12px; 103 | border-radius: 8px; 104 | font-size: 16px; 105 | background-color: rgb(49, 108, 244); 106 | } 107 | 108 | input[type="submit"]:hover, 109 | button:hover { 110 | background-color: rgb(41, 93, 207); 111 | } 112 | 113 | input[type="submit"]:disabled, 114 | button:disabled { 115 | background-color: rgb(122, 160, 248); 116 | } 117 | -------------------------------------------------------------------------------- /src/main.tsx: -------------------------------------------------------------------------------- 1 | import { StrictMode } from "react"; 2 | import ReactDOM from "react-dom"; 3 | import "./index.css"; 4 | import App from "./App"; 5 | import { ConvexProvider, ConvexReactClient } from "convex/react"; 6 | 7 | const address = import.meta.env.VITE_CONVEX_URL; 8 | 9 | const convex = new ConvexReactClient(address); 10 | 11 | ReactDOM.render( 12 | 13 | 14 | 15 | 16 | , 17 | document.getElementById("root") 18 | ); 19 | -------------------------------------------------------------------------------- /src/vite-env.d.js: -------------------------------------------------------------------------------- 1 | /// 2 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "ES2020", 4 | "useDefineForClassFields": true, 5 | "lib": ["ES2020", "DOM", "DOM.Iterable"], 6 | "module": "ESNext", 7 | "skipLibCheck": true, 8 | 9 | /* Bundler mode */ 10 | "moduleResolution": "bundler", 11 | "allowImportingTsExtensions": true, 12 | "resolveJsonModule": true, 13 | "isolatedModules": true, 14 | "noEmit": true, 15 | "jsx": "react-jsx", 16 | 17 | /* Linting */ 18 | "strict": true, 19 | "noUnusedLocals": true, 20 | "noUnusedParameters": true, 21 | "noFallthroughCasesInSwitch": true, 22 | 23 | "types": ["vite/client"], 24 | }, 25 | "include": ["src"], 26 | } 27 | -------------------------------------------------------------------------------- /vite.config.js: -------------------------------------------------------------------------------- 1 | import { defineConfig } from "vite"; 2 | import react from "@vitejs/plugin-react"; 3 | 4 | // https://vitejs.dev/config/ 5 | export default defineConfig({ 6 | plugins: [react()], 7 | }); 8 | --------------------------------------------------------------------------------