How to use Stripe checkout with autumn-js?
How can I use the Stripe checkout instead of the Autumn checkout dialog component? I'm using Next.js with the autumn-js SDK.
To use Stripe Checkout instead of the built-in Autumn checkout dialog in a Next.js application with the autumn-js SDK, you should use the attach method from the useCustomer hook.
The attach function is designed to handle the product attachment process. For paid products, it automatically generates a Stripe Checkout URL and can handle the redirection for you.
###How to use Stripe Checkout directly
Instead of using the checkout method (which is typically used to fetch details for a preview dialog), call attach directly in your click handler:
import { useCustomer } from "autumn-js/react";
export function UpgradeButton({ productId }) {
const { attach } = useCustomer();
const handleUpgrade = async () => {
try {
const result = await attach({
productId: productId,
// The SDK will handle the redirect if you set this to true
openInNewTab: true,
// Optional: specify where to return after successful payment
successUrl: `${window.location.origin}/dashboard?session_id={CHECKOUT_SESSION_ID}`,
cancelUrl: `${window.location.origin}/pricing`,
});
// If you prefer to handle the redirect manually:
if (result.checkout_url) {
window.location.href = result.checkout_url;
}
} catch (error) {
console.error("Upgrade failed", error);
}
};
return <button onClick={handleUpgrade}>Upgrade Now</button>;
}
###Key Differences
checkout(): Returns aCheckoutResultcontaining proration information, total due today, and line items. It is intended to be used with a dialog (like the defaultCheckoutDialog) to show the user what they are about to pay before they confirm.attach(): Directly initiates the process of adding the product to the customer. If the product is paid and requires a new subscription or payment, the Autumn backend will return acheckout_url(a hosted Stripe Checkout page).
###If you are using the Autumn PricingTable component
If you have installed the Autumn Pricing Table as a component in your project (e.g., in components/autumn/pricing-table.tsx), you can modify the onClick handler of the PricingCard to call attach instead of checkout:
// Inside your PricingTable component
<PricingCard
productId={product.id}
buttonProps={{
onClick: async () => {
await attach({
productId: product.id,
openInNewTab: true,
});
},
}}
/>
###Important Configuration
Ensure that your Stripe account is connected in the Autumn dashboard and that your success_url is configured in your organization settings, as the backend uses these to construct the Stripe session. The attach call will fallback to the organization's default success URL if one isn't provided in the function call.
END OF POST