@agentaos/nextjs package gives a Next.js app two route handlers:
The handlers use the standard
Request and Response, so they also work in other frameworks with web-standard route handlers.
Before you start
- In the dashboard, create the products you sell. Copy each product’s link ID from the product page.
- Open Developers → API keys and create a key. A key that starts with
sk_test_works in test mode. - Open Settings → Developers → Webhooks and set the URL to
https://your-domain.com/api/webhooks/agentaos. Click Reveal signing secret and copy the secret. - Add both values to your environment:
.env.local
Install
Add the checkout route
app/checkout/route.ts
- A buyer can only buy a product that is in
products, by its slug. The route adds the slug to the checkoutmetadataasproduct. - The buyer’s details, the metadata and the return URLs come from your server, never from the link.
- The route ignores prefetch requests, so a link that scrolls into view does not start a checkout. With the Next.js
<Link>component, setprefetch={false}. - After paying, the buyer returns to
successUrlwith?sessionId=...added.
4242 4242 4242 4242, any future date and any CVC.
Add the webhook route
app/api/webhooks/agentaos/route.ts
webhookSecret.
You can set one function per event: onCheckoutCompleted, onSubscriptionCreated, onSubscriptionRenewed, onSubscriptionUpdated, onSubscriptionPaymentFailed, onSubscriptionCanceled, onDisputeCreated and onDisputeClosed. onEvent receives every event, after the function for that event. If a function throws an error, the route answers 500 and AgentaOS sends the event again.
Handle events
In your functions:- Use
event.data.metadata.productto know what was bought. Oncheckout.session.completed,event.data.linkIdis the payment link’s public token, not the link ID inproducts. - Expect your metadata on the first
checkout.session.completedonly. Renewals and upgrade charges also arrive ascheckout.session.completed, with AgentaOS’ssubscriptionIdin the metadata instead. Save the link fromsubscriptionIdto your user from the first event. - Read metadata keys in camelCase. A key you send as
user_idarrives asuserId. - Ignore test events in live mode: check
event.data.livemode. - Give access only once, because an event can arrive more than once. For checkouts, save
event.data.sessionId.