I'm developing a integration with stripe in my nextjs aplication. Currently I'm trying to redirect the user to the checkout process, however, for that I need to get the session information in my 'subscribe.ts' file inside /pages/api.
I'm using getSession for that, here's my subscribe.ts file:
import { NextApiRequest, NextApiResponse } from "next";
// import { unstable_getServerSession } from "next-auth/next";
import { getSession } from "next-auth/react";
import { stripe } from "services/stripe";
// import { authOptions } from "./auth/[...nextauth]";
export default async (req: NextApiRequest, res: NextApiResponse) => {
if(req.method == 'POST') {
console.log(req, res);
const session = await getSession({ req });
console.log(req.cookies, session);
// console.log(session);
if(!session) return;
const stripeCustomer = await stripe.customers.create({
email: session.user.email,
})
const stripeCheckoutSession = await stripe.checkout.sessions.create({
customer: stripeCustomer.id,
payment_method_types: ['card'],
billing_address_collection: 'required',
line_items: [
{ price: 'price_1Kn2z8HXoO2e9eo5NaPFzRV1', quantity: 1 }
],
mode: 'subscription',
allow_promotion_codes: true,
success_url: process.env.STRIPE_SUCCESS_URL,
cancel_url: process.env.STRIPE_CANCEL_URL
});
return res.status(200).json({ sessionId: stripeCheckoutSession.id });
} else {
res.setHeader('Allow', 'POST');
res.status(405).end('Method not allowed');
}
}
The user makes login using the github integration from nextauth.
I've tried using the 'unstable_getServerSession' function but it returned null as well. After searching for a while I found that maybe there was some issue with the cookies from the request, but on the console.log the cookies are correctly tracked by the variable.
What am I doing wrong here?
// Edit: my [...nextauth].js
import { query as q } from 'faunadb';
import NextAuth from "next-auth";
import GithubProvider from "next-auth/providers/github";
import { Fauna } from "services/fauna";
export const authOptions = {
providers: [
GithubProvider({
clientId: process.env.GITHUB_ID,
clientSecret: process.env.GITHUB_SECRET,
authorization: { params: { scope: 'read:user' } }
}),
],
callbacks: {
async signIn({ user, account, profile }) {
const { email } = user;
try {
await Fauna.query(
q.If(
q.Not(
q.Exists(
q.Match(
q.Index('user_by_email'),
q.Casefold(user.email)
)
)
),
q.Create(
q.Collection('users'),
{ data: { email } }
),
q.Get(
q.Match(
q.Index('user_by_email'),
q.Casefold(user.email)
)
)
)
);
return true;
} catch (error) {
console.log(error);
return false;
}
}
}
};
export default NextAuth(authOptions);