Home > other >  Approve PayPal Order but serverside
Approve PayPal Order but serverside

Time:03-26

I have this code for payement:

  generatePayPalButton() {
    paypal
      .Buttons({
        createOrder: async () => {
          const res = await this.sendReq.postReq("/api/paypal/create-order", { quantity: 1 })
          return res.id
        },
        onApprove: function (data: any, actions: any) {
          const capture = actions?.order?.capture().then((details: any) => {
            console.log(details)
          })
        },
        onCancel: () => {
          console.log("Canceled")
        },
        one rror: (e: any) => {
          console.error(e)
        }
      })
      .render("#paypal")
  }

You can clearly see, that Im approving the order in the frontend. But I want to approve the order in the backend and save it to a database.

Here is my backend code:

router.post("/api/paypal/create-order", async(req, res) => {
    const request = new paypal.orders.OrdersCreateRequest()
    const quantity = req.body.quantity
    const total = quantity * dataController.payement.pricePerNight
    request.prefer("return=representation")
    request.requestBody({
        intent: "CAPTURE",
        purchase_units: [{
            amount: {
                currency_code: "USD",
                value: total,
                breakdown: {
                    item_total: {
                        currency_code: "USD",
                        value: total,
                    },
                },
            },
        }, ],
    })

    try {
        const order = await paypalClient.execute(request)
        res.send({ id: order.result.id })
    } catch (e) {
        console.error(`Paypal error: `, e.message)
        res.send(e)
    }
})

So in the backend I just have a route, where Im giving the order id back, so I can charge the user. But how can I be sure that he paid. Can I check a token or something in the backend?

Im using: NodeJs, express @paypal/checkout-server-sdk Angular sendRequestService

CodePudding user response:

The approval step always takes place on the client side. The person paying is giving their approval, and they don't live inside your server, they connect to it via a client.

However, the steps immediately prior to approval (create order) and after approval (capture order, which is what actually creates a transaction) are both done from a server. You'll need a server route for each of these; looks like you already have a create route. The second capture route should take an id as input, capture it, do any validation such as checking that any successful transaction was for the correct amount before returning a response to the client. (Error/unsuccessful transaction responses should also be propagated back to the client, so it can display an appropriate message or restart in the case of INSTRUMENT_DECLINED)

For approval on the client, use this flow: https://developer.paypal.com/demo/checkout/#/pattern/server

  • Related