-
Notifications
You must be signed in to change notification settings - Fork 10.5k
Invoices example #17755
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Invoices example #17755
Changes from 1 commit
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
72e323e
Invoices example
celso 8c12435
Update src/content/docs/workflows/examples/send-invoices.mdx
sidharthachatterjee f7b8931
typo
celso da86944
Merge branch 'celso/workflows-examples' of github.com:cloudflare/clou…
celso 71502b9
Apply suggestions from code review
elithrar 573add2
remove examples for now (#17753)
elithrar 0ce7f8a
Invoices example
celso 79a7126
Invoices example
celso d66be8f
Merge branch 'production' into celso/workflows-examples
sidharthachatterjee File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
15 changes: 0 additions & 15 deletions
15
src/content/docs/workflows/examples/automate-lifecycle-emails.mdx
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,219 @@ | ||
| --- | ||
| type: example | ||
| summary: Send invoice when shopping cart is checked out and paid for | ||
| tags: | ||
| - Workflows | ||
| - D1 | ||
| - Email Routing | ||
| pcx_content_type: configuration | ||
| title: Pay cart and send invoice | ||
| sidebar: | ||
| order: 3 | ||
| description: Send invoice when shopping cart is checked out and paid for | ||
|
|
||
| --- | ||
|
|
||
| import { TabItem, Tabs } from "~/components" | ||
|
|
||
| In this example we implement a Workflow for that is triggered | ||
|
|
||
| Once a workflow instance is triggered, it starts polling a [D1](/d1) database for the cart ID until it's been checked out. Once the shopping cart is checked out, we proceed to process the payment with an external provider doing a fetch POST. Finally, assuming everything goes well, we try to send an email using [Email Workers](/email-routing/email-workers/) with the invoice to the customer. | ||
|
|
||
| As you can see, Workflows handles all the different service responses and failures; it will retry D1 until the cart is checked out, retry the payment processor if it fails for some reason, and retry sending the email with the invoice if it can't. The developer doesn't have to care about any of that logic, and the workflow can run for hours, handling all the possible conditions until it is completed. | ||
elithrar marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| This is obviously a simplified example of processing a shopping cart. We'd assume more steps and additional logic in a real-life scenario, but hopefully, it gives you a good idea of what you can do with Workflows. | ||
elithrar marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| ```ts | ||
| import { | ||
| WorkflowEntrypoint, | ||
| WorkflowStep, | ||
| WorkflowEvent, | ||
| } from "cloudflare:workers"; | ||
| import { EmailMessage } from "cloudflare:email"; | ||
| import { createMimeMessage } from "mimetext"; | ||
|
|
||
| // We are using Email Routing to send emails out and D1 for our cart database | ||
| type Env = { | ||
| CART_WORKFLOW: Workflow; | ||
| SEND_EMAIL: any; | ||
| DB: any; | ||
| }; | ||
|
|
||
| // Workflow parameters: we expect a cartId | ||
| type Params = { | ||
| cartId: string; | ||
| }; | ||
|
|
||
| // Adjust this to your Cloudflare zone using Email Routing | ||
| const merchantEmail = "[email protected]"; | ||
|
|
||
| // Uses mimetext npm to generate Email | ||
| const genEmail = (email: string, amount: number) => { | ||
| const msg = createMimeMessage(); | ||
| msg.setSender({ name: "Pet shop", addr: merchantEmail }); | ||
| msg.setRecipient(email); | ||
| msg.setSubject("You invoice"); | ||
| msg.addMessage({ | ||
| contentType: "text/plain", | ||
| data: `Your invoice for ${amount} has been paid. Your products will be shipped shortly.`, | ||
| }); | ||
|
|
||
| return new EmailMessage(merchantEmail, email, msg.asRaw()); | ||
| }; | ||
|
|
||
| // Workflow logic | ||
| export class cartInvoicesWorkflow extends WorkflowEntrypoint<Env, Params> { | ||
| async run(event: WorkflowEvent<Params>, step: WorkflowStep) { | ||
| await step.sleep("sleep for a while", "10 seconds"); | ||
|
|
||
| // Retrieve the cart from the D1 database | ||
| // if the cart hasn't been checked out yet retry every 2 minutes, 10 times, otherwise give up | ||
| const cart = await step.do( | ||
| "retrieve cart", | ||
| { | ||
| retries: { | ||
| limit: 10, | ||
| delay: 2000 * 60, | ||
| backoff: "constant", | ||
| }, | ||
| timeout: "30 seconds", | ||
| }, | ||
| async () => { | ||
| const { results } = await this.env.DB.prepare( | ||
| `SELECT * FROM cart WHERE id = ?`, | ||
| ) | ||
| .bind(event.payload.cartId) | ||
| .all(); | ||
| // should return { checkedOut: true, amount: 250 , account: { email: "[email protected]" }}; | ||
| if(results[0].checkedOut === false) { | ||
| throw new Error("cart hasn't been checked out yet"); | ||
| } | ||
| return results[0]; | ||
| }, | ||
| ); | ||
|
|
||
| // Proceed to payment, retry 10 times every minute or give up | ||
| const payment = await step.do( | ||
| "payment", | ||
| { | ||
| retries: { | ||
| limit: 10, | ||
| delay: 1000 * 60, | ||
| backoff: "constant", | ||
| }, | ||
| timeout: "30 seconds", | ||
| }, | ||
| async () => { | ||
| let resp = await fetch("https://payment-processor.example.com/", { | ||
| method: "POST", | ||
| headers: { | ||
| "Content-Type": "application/json; charset=utf-8", | ||
| }, | ||
| body: JSON.stringify({ amount: cart.amount }), | ||
| }); | ||
|
|
||
| if (!resp.ok) { | ||
| throw new Error("payment has failed"); | ||
| } | ||
|
|
||
| return { success: true, amount: cart.amount }; | ||
| }, | ||
| ); | ||
|
|
||
| // Send invoice to the customer, retry 10 times every 5 minutes or give up | ||
| // Requires that cart.account.email has previously been validated in Email Routing, | ||
| // See https://developers.cloudflare.com/email-routing/email-workers/ | ||
| await step.do( | ||
| "send invoice", | ||
| { | ||
| retries: { | ||
| limit: 10, | ||
| delay: 5000 * 60, | ||
| backoff: "constant", | ||
| }, | ||
| timeout: "30 seconds", | ||
| }, | ||
| async () => { | ||
| const message = genEmail(cart.account.email, payment.amount); | ||
| try { | ||
| await this.env.SEND_EMAIL.send(message); | ||
| } catch (e) { | ||
| throw new Error("failed to send invoice"); | ||
| } | ||
| }, | ||
| ); | ||
|
|
||
| } | ||
| } | ||
|
|
||
| // Default page for admin | ||
| // Remove in production | ||
|
|
||
| export default { | ||
| async fetch(req: Request, env: Env): Promise<Response> { | ||
| let url = new URL(req.url); | ||
|
|
||
| let id = new URL(req.url).searchParams.get("instanceId"); | ||
|
|
||
| // Get the status of an existing instance, if provided | ||
| if (id) { | ||
| let instance = await env.CART_WORKFLOW.get(id); | ||
| return Response.json({ | ||
| status: await instance.status(), | ||
| }); | ||
| } | ||
|
|
||
| if (url.pathname.startsWith("/new")) { | ||
| let instance = await env.CART_WORKFLOW.create({ | ||
| params: { | ||
| cartId: "123" | ||
| }, | ||
| }); | ||
| return Response.json({ | ||
| id: instance.id, | ||
| details: await instance.status(), | ||
| }); | ||
| } | ||
|
|
||
| return new Response( | ||
| `<html><body><a href="/new">new instance</a> or add ?instanceId=...</body></html>`, | ||
| { | ||
| headers: { | ||
| "content-type": "text/html;charset=UTF-8", | ||
| }, | ||
| }, | ||
| ); | ||
| }, | ||
| }; | ||
| ``` | ||
|
|
||
| Here's a minimal package.json: | ||
elithrar marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| ```json | ||
| { | ||
| "devDependencies": { | ||
| "@cloudflare/workers-types": "^4.20241022.0", | ||
| "wrangler": "^3.83.0" | ||
| }, | ||
| "dependencies": { | ||
| "mimetext": "^3.0.24" | ||
| } | ||
| } | ||
| ``` | ||
|
|
||
| And finally wrangler.toml: | ||
|
|
||
| ```toml | ||
| name = "cart-invoices" | ||
| main = "src/index.ts" | ||
| compatibility_date = "2024-10-22" | ||
| compatibility_flags = ["experimental", "nodejs_compat" ] | ||
sidharthachatterjee marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| [[workflows]] | ||
| name = "cart-invoices-workflow" | ||
| binding = "CART_WORKFLOW" | ||
| class_name = "cartInvoicesWorkflow" | ||
|
|
||
| [[send_email]] | ||
| name = "SEND_EMAIL" | ||
| ``` | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.