Skip to content
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

Trying to add Stripe... #373

Closed
PierrickLozach opened this issue Dec 26, 2024 · 3 comments
Closed

Trying to add Stripe... #373

PierrickLozach opened this issue Dec 26, 2024 · 3 comments
Labels
bug Something isn't working

Comments

@PierrickLozach
Copy link

Hi,

I am trying to use Stripe to process payments.
I copied some code from https://github.com/leerob/next-saas-starter as suggested in one of the issues but when it redirects to my localhost site using this URL: http://localhost:3000/webhooks/stripe?session_id=cs_test_a18bZmUK2kprFiXdknvC4KbJ1OosQ5jj5DxpMUO9x8RfeGxWRvW3aQIGAX, I get a 404.

Where should I redirect the user after the Stripe session has completed? I can see that apps/api/app/webhooks/stripe/route.ts seems to have the correct code to handle the response?

next-forge version
2.21.8

@PierrickLozach PierrickLozach added the bug Something isn't working label Dec 26, 2024
@trevorpfiz
Copy link
Contributor

maybe https://github.com/vercel/nextjs-subscription-payments can help as well? this is what I am doing based on it:

const router = useRouter();
const [priceIdLoading, setPriceIdLoading] = useState<string>();
const currentPath = usePathname();

const handleStripeCheckout = async (price: Price) => {
    setPriceIdLoading(price.id);

    const { errorRedirect, checkoutUrl } = await checkoutWithStripe({
      price,
      userId,
      email: userEmail,
      redirectPath: currentPath,
    });

    if (errorRedirect) {
      setPriceIdLoading(undefined);
      return router.push(errorRedirect);
    }

    if (!checkoutUrl) {
      setPriceIdLoading(undefined);
      return router.push(
        getErrorRedirect(
          currentPath,
          'An unknown error occurred.',
          'Please try again later or contact a system administrator.'
        )
      );
    }

    router.push(checkoutUrl);
    setPriceIdLoading(undefined);
  };
type CheckoutResponse = {
  errorRedirect?: string;
  checkoutUrl?: string;
};

export async function checkoutWithStripe({
  price,
  userId,
  email,
  redirectPath = '/',
}: {
  price: Price;
  userId: ProfileId;
  email: string;
  redirectPath?: string;
}): Promise<CheckoutResponse> {
  try {
    // Retrieve or create the customer in Stripe
    const { stripeCustomerId } = await createOrRetrieveCustomer({
      userId,
      email,
    });

    if (!stripeCustomerId) {
      throw new Error('Could not get customer.');
    }

    let params: Stripe.Checkout.SessionCreateParams = {
      allow_promotion_codes: true,
      billing_address_collection: 'required',
      customer: stripeCustomerId,
      customer_update: {
        address: 'auto',
      },
      line_items: [
        {
          price: price.id,
          quantity: 1,
        },
      ],
      cancel_url: getURL(),
      success_url: getURL(redirectPath),
    };

    if (price.type === 'recurring') {
      params = {
        ...params,
        mode: 'subscription',
        subscription_data: {
          trial_end: calculateTrialEndUnixTimestamp(price.trialPeriodDays),
        },
      };
    } else if (price.type === 'one_time') {
      params = {
        ...params,
        mode: 'payment',
      };
    }

    // Create a checkout session in Stripe
    const session = await stripe.checkout.sessions.create(params);

    if (!session?.url) {
      throw new Error('Unable to create checkout session.');
    }

    return { checkoutUrl: session.url };
  } catch (error) {
    if (error instanceof Error) {
      return {
        errorRedirect: getErrorRedirect(
          redirectPath,
          error.message,
          'Please try again later or contact a system administrator.'
        ),
      };
    }
    return {
      errorRedirect: getErrorRedirect(
        redirectPath,
        'An unknown error occurred.',
        'Please try again later or contact a system administrator.'
      ),
    };
  }
}

@haydenbleasel
Copy link
Owner

@PierrickLozach Hi there! The webhook handlers run on the api app, not the app app.

So, if you wanted to hit up that webhooks/stripe route, you would use the following URL:

http://localhost:3002/webhooks/stripe

@PierrickLozach
Copy link
Author

Thanks. Turns out my redirect url (success_url) was wrong. I get the session_id from Stripe now. Only need to understand what to do next now :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

3 participants