Coinbase commerce api sample code and common errors in Node

The followings are some code relevant to the title.

Create Charge

A charge is something that the frontend needs to send users to the payment page. Just add the following code to your nodejs route:


import CoinbaseCommerce from 'coinbase-commerce-node';
const Charge = CoinbaseCommerce.resources.Charge;
CoinbaseCommerce.Client.init(process.env.COINBASE_API_KEY);

 if (req.method === 'POST') {
        try {
            const { amount, currency, user_id,user_email} = req.body;

            // create a charge
            const chargeData = {
                name: 'Your Awesome Comany',
                description: 'Deposit to Your Awesome Comany',
                local_price: {
                    amount,
                    currency,
                },
                pricing_type: "fixed_price",
                metadata: {
                    user_id,
                    user_email
                },
            };           
            const charge = await Charge.create(chargeData);
            res.status(200).json({ hosted_url: charge.hosted_url });
        } catch (error) {
            console.log("Error :", error)
        }
    } else {
        res.status(405).end();
    }

Webhook Callback

The coinbase webhook is something we need  when users make paymentst to our coinbase commerce account. Then, Coinbase commerce will send request to our backend. So, we need to create a nodejs post route in order for coinbase to send the payment status request which we can use to update our database:

    //const rawbody = req.rawBody;
    const signature = req.headers['x-cc-webhook-signature'] as string;
    const webhookSecret = process.env.your_coinbase_webhook_secret as string;

    try {
        event = Webhook.verifyEventBody(JSON.stringify(req.body), signature, webhookSecret);
       
        const user = await User.findById(event.metadata.user_id);
       
        if (!user) {
            return res.status(400).json({
                message: "invalid user"
            })
        }
      
       
        if (event.type === "charge:confirmed") {         

            user.balance += deposit.amount;
            await user.save();
        }

        if (event.type === "charge:failed") {
           //other things
        }
        return res.status(200).send(event);

    } catch (error: any) {  

        return res.status(400).send('Webhook Error:' + error.message);
    }
  
    res.status(200).send(event);

Common Errors

  • Forget to set: res.setHeader("Access-Control-Allow-Origin", "*");
  • Forget to add: res.setHeader("Access-Contxprol-Allow-Headers", "X-CC-Webhook-Signature");
  • Forget to set: res.setHeader("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT,DELETE");
  • Forget to use: Webhook.verifyEventBody(JSON.stringify(req.body), signature, webhookSecret); Here rawbody does not work. Use JSON.stringify(req.body) instead.

Comments

Popular posts from this blog

How to Make A Reusable Image Slideshow HTML Component With Vanilla JavaScript

HTML Tags and Inline CSS that Work In Plotly.js Title

How to Type Spaces In HTML Input And Display In the Browser