Next.js Discord

Discord Forum

Uncaught Error: Expected an order id to be passed while integrating PAYPAL

Answered
Masai Lion posted this in #help-forum
Open in Discord
Masai LionOP
Hello. Me again, this is urgent. so I am integrating PayPal to my NextJS website w/ Typescript.
My project is throwing the error on the title of the post, but before doing the modifications the order ID was sent successfully without errors. Anyways. I hope someone can help me 🙂
This is being difficult for me as I have never integrated PayPal.

I am trying to make it so that the items that are in the cart, when you click on the paypal button you can pay the 1 or 2 or the products you want and the price will be also established by the same list of properties. I also want to know if someone can share with me the documentation on how to change the currency_code without errors and also how to add the option to pay with only a credit/debit card.

But first I want to focus on the error mentioned in the title.

Scripts are inside this single file separated by comments.
https://paste.ec/paste/cN6zWVfL#sC3EAa2F6UxPViluXg9h4yUOphMIbfh0YsRQAurceeq
Link expires in 1 day
Answered by Ray
try this
request.requestBody({
    "intent": "CAPTURE",
    "purchase_units": [
        {
            "amount": {
                "currency_code": "USD",
                "value": "100.00"
            }
        }
     ]
});
View full answer

153 Replies

Masai LionOP
Im trying to fix it while I wait so there might be modifications when someone answers me 🤭
Masai LionOP
So now it only says that Type r is not a function lol
Masai LionOP
Hello! I’m still looking for someone to help me!!
try to console.log(order.id)
@Anay-208 try to `console.log(order.id)`
Masai LionOP
I did already hehe
It throws nothing
@Masai Lion I did already hehe
line 94
export async function POST(req: any) {
    const { products } = await req.json()
@Ray line 94 ts export async function POST(req: any) { const { products } = await req.json()
Masai LionOP
Uhhh can you explain me please?
@Masai Lion Uhhh can you explain me please?
does it fix it?
@Ray does it fix it?
Masai LionOP
I haven’t tried it I just want to see what it is just so I can learn :))
you can't use req.body to access the body in app router. Instead, use [web api](https://developer.mozilla.org/en-US/docs/Web/API/Request/json) method req.json(), req.formData() or req.text() for it
Masai LionOP
Wait sorry
But I modified my script already
I am using parts of my other scripts to get the item id
give me a second to share the new ones in codeblocks
Well
First a ss
@Masai Lion Click to see attachment
does the redux store work in route handler?
@Ray does the redux store work in route handler?
Masai LionOP
Yeah
I mean, when I add the products to the cart it shows the products
1 or 2 or many products and the quantity and the price adjusts automatically
I will send the CartProducts.tsx code together with the modifications of the route.tsx
Masai LionOP
@Ray would u mind if I put three codes inside a 0bin link?
like 3 in 1?
UPDATED SCRIPTS
@Ray does the redux store work in route handler?
Masai LionOP
it used to work before adding modifications like to make it to be automatically updated by the products on the cart
i made a thread because I had a problem with this same files
someone helped me and it started working
@Ray what error you get now?
Masai LionOP
same
no order id
let me try again just to confirm but last time I checked the error was still the same
@Masai Lion same
do you see the products logged in console?
console.log(products)
i havent logged that yet
i will add it to route.tsx
and hope
@Ray do you see the products logged in console? ` console.log(products)`
Masai LionOP
inside the scripts on components indeed i get the products
but not on the paypal one
@Masai Lion inside the scripts on components indeed i get the products
but I don't think it will get the products in the route handler
@Ray but I don't think it will get the products in the route handler
Masai LionOP
let me init server
wait
inside route.tsx i think i dont get products
@Masai Lion inside route.tsx i think i dont get products
any error? do you see the log for the response?
@Ray any error? do you see the log for the response?
Masai LionOP
yes
the server was also giving 505 internal server error
so i should run npm run build
it works but when i press the button the whole screen goes black and then it goes back to normal
prolly my 4gb of ram aint enough
@Masai Lion yes
try wrap the endpoint with try/catch
export async function POST() {
  try {
    const products = useAppSelector((state) => state.cartReducer);
    const request = new paypal.orders.OrdersCreateRequest()
     
    const getTotal= () => {
        let total = 0;
        products.forEach((item) => (total = total + item.price * item.quantity));
        return total;
    };
     
    console.log(products)
     
    request.requestBody({
        intent: "CAPTURE",
        ....

     const response = await client.execute(request);
    console.log(response);
 
    return NextResponse.json({
        id: response.result.id
    });

  } catch (e) {
     const error = e instanceof Error ? e.message : typeof e === 'string' ? e : 'unexpected error'
    return NextResponse.json({error})
  }
is this being logged?
console.log("ORDER:", order)
@Ray is this being logged? ` console.log("ORDER:", order)`
Masai LionOP
It is inside but not logged
@Masai Lion It is inside but not logged
  const res = await fetch('/api/checkout', {
                            method: "POST",
                             headers: {
                              "Content-Type": "application/json",
                          },
                        })
inside cart.tsx
right
the button
@Ray the button
Masai LionOP
same errors
@Masai Lion same errors
do you see the console.log(products) and console.log(response); logged /api/checkout?
Masai LionOP
inside the console no
in the script indeed
@Masai Lion inside the console no
try curl -X POST http://localhost:3000/api/checkout in cmd
and what do you see
in terminal and console
Masai LionOP
it shows the x isnt a recognized parameter
@Masai Lion it shows the x isnt a recognized parameter
do you see console.log(products) logged?
@Ray do you see ` console.log(products)` logged?
Masai LionOP
no
@Masai Lion it shows the x isnt a recognized parameter
comment out const products = useAppSelector((state) => state.cartReducer);
wait
and the items
getTotal just return 10
Masai LionOP
i runned curl -X POST http://localhost:3000/api/checkout inside the console of inspector it says uhmm
Uncaught SyntaxError: Unexpected identifier 'POST'
this inside the inspector´s console
run it in terminal
browser doesn't have curl
Masai LionOP
them yeah it says X is not a parameter
@Ray and the items
and this
@Ray and the items
Masai LionOP
what are the items?
oh wait
i see
i comment the items?
but then paypal will ask me for items
@Masai Lion but then paypal will ask me for items
just for test
their example doesn't have items either
Masai LionOP
oh
so i comment it?
how do i comment it, ik how to comment but it gives me a syntax error
saying that amount blah blah blah
imma just delete it and send it here
items: products.map((item: any) => ({
                    name: item.name,
                    category: "PHYSICAL_GOODS",
                    description: item.description,
                    quantity: item.quantity.toString(),
                    unit_amount: {
                      currency_code: "USD",
                      value: item.price.toString(),
                    },
                  })),
done @Ray
@Masai Lion done <@743561772069421169>
any error you get now?
@Ray any error you get now?
Masai LionOP
let me check rq
@Ray any error you get now?
Masai LionOP
same errors
same unexpected end of json
export async function POST() {
  try {
    //const products = useAppSelector((state) => state.cartReducer);
    const request = new paypal.orders.OrdersCreateRequest()
 
    request.requestBody({
        intent: "CAPTURE",
        ....

     const response = await client.execute(request);
    console.log("response", response);
 
    return NextResponse.json({
        id: response.result.id
    });

  } catch (e) {
     console.log("endpoing error", e)
     const error = e instanceof Error ? e.message : typeof e === 'string' ? e : 'unexpected error'
    return NextResponse.json({error})
  }
Masai LionOP
i mean
there is no other errors rather than the ones i sent while ago
does your code on github which can be share? I have no idea how to debug without error log
@Masai Lion i added this and nothing
/** @type {import('next').NextConfig} */
const nextConfig = {
  experimental: {
    serverComponentsExternalPackages: ['@paypal/checkout-server-sdk'],
  },
}
 
module.exports = nextConfig

try adding this to next.config.js
wait, you have 'use client' in app/api/checkout/route.tsx?
Masai LionOP
i dont have next.config.js, i only have next.config.mjs
same add it
@Masai Lion yes...?
remove it
@Ray remove it
Masai LionOP
done
try again
Masai LionOP
and now I try again?
sure
Masai LionOP
paypal window just loads and loads
no errors
no nothing
just loading paypal screen
finally
error
new messages and errors
thats something
what error
Masai LionOP
fist console log
Uncaught Error: Expected an order id to be passed
at https://www.sandbox.paypal.com/smart/buttons?
try this
request.requestBody({
    "intent": "CAPTURE",
    "purchase_units": [
        {
            "amount": {
                "currency_code": "USD",
                "value": "100.00"
            }
        }
     ]
});
Answer
Masai LionOP
and a third one
well the same one we`ve always had
Masai LionOP
basically it now lets me sign in, which means it works
so something wrong with your requestBody object
check their doc and modify it
and sending the product in fetch request of the button instead of using redux store
which doesn't work in route handler
Masai LionOP
basically i just went to the beginning
so im alone from now on?
cuz this is where i started from
i went from 1st steps to something to 1st steps again
Masai LionOP
bro now what :C
i need to do everything again?
Masai LionOP
Imma go sleep and rest. Hopefully to find a way tommorow to idk make something up
@Masai Lion i went from 1st steps to something to 1st steps again
I think you just need to correct the schema in the requestBody object and sending the items in the body of the fetch request