I'm making payment function for my static e-commerce Next.js app.
For payment I've several stages:
- Making cart page with shipping information form and button "Pay" which redirect to
/paymentpage; - On
/paymentpage I connect with my payment service and need to get cart info from Context API, but I can't use Context API ingetStaticPropsit's my problem. Payment page needs just get cart data and redirects on external service payment form.
Code for page /payment is below:
import { useEffect, useContext } from "react"
import QiwiBillPaymentsAPI from "@qiwi/bill-payments-node-js-sdk"
import { CartContext } from "@/context/GlobalState"
export default function Payment ({ payUrl }) {
useEffect(() => window.location.assign(payUrl))
return (
<span>Redirect</span>
)
}
export async function getStaticProps() {
const qiwiApi = new QiwiBillPaymentsAPI(process.env.QIWI_SECRET_KEY)
const { state, dispatch } = useContext(CartContext)
const { cart } = state
const billId = qiwiApi.generateId()
const lifetime = qiwiApi.getLifetimeByDay(1);
const fields = {
amount: 1.00,
currency: "RUB",
expirationDateTime: lifetime,
}
const payment_data = await qiwiApi.createBill( billId, fields )
const payUrl = payment_data.payUrl
return { props: { payUrl }}
}
Please, help me with any ideas.
getStaticPropsruns at build-time on the server. You won't have access to any runtime or client-side logic in there. Also, why do you need access to the context if you don't seem to be using the cart data ingetStaticProps? Couldn't you handle the context in yourPaymentcomponent instead?window.location.assign, which is probably a good idea in this case. But I'm afraid of you are using the same thing for everything. Make sure you usenext router. Otherwise you are completely opt yourself out from SPA and advantage of usingNext.jswindow.location.assignonly in this case. And I was looking for approach to make it withnext router, but I can't. If you know, tell me please!getStaticPropsfor changeamount(total price for future payment) in fields object and something more. For some reason I cannot use qiwiApi inside of the Payment component, I tried it in useEffect or just in function but in don't work and returns error with 'fs'.getStaticPropscode to an API route, then make a request from yourPaymentcomponent to that API route with whatever you need from the context.