|  | 
|  | 1 | +import { buffer } from "micro"; | 
|  | 2 | +const Stripe = require('stripe'); | 
|  | 3 | +const WooCommerceRestApi = require("@woocommerce/woocommerce-rest-api").default; | 
|  | 4 | + | 
|  | 5 | +const stripe = new Stripe(process.env.STRIPE_SECRET_KEY, { | 
|  | 6 | +    apiVersion: '2020-08-27' | 
|  | 7 | +}); | 
|  | 8 | +const webhookSecret = process.env.STRIPE_WEBHOOK_ENDPOINT_SECRET; | 
|  | 9 | + | 
|  | 10 | +export const config = { | 
|  | 11 | +    api: { | 
|  | 12 | +        bodyParser: false, | 
|  | 13 | +    }, | 
|  | 14 | +}; | 
|  | 15 | + | 
|  | 16 | +const api = new WooCommerceRestApi({ | 
|  | 17 | +	url: process.env.NEXT_PUBLIC_WORDPRESS_SITE_URL, | 
|  | 18 | +	consumerKey: process.env.WC_CONSUMER_KEY, | 
|  | 19 | +	consumerSecret: process.env.WC_CONSUMER_SECRET, | 
|  | 20 | +	version: "wc/v3" | 
|  | 21 | +}); | 
|  | 22 | + | 
|  | 23 | +/** | 
|  | 24 | + * Update Order. | 
|  | 25 | + * | 
|  | 26 | + * Once payment is successful or failed, | 
|  | 27 | + * Update Order Status to 'Processing' or 'Failed' and set the transaction id. | 
|  | 28 | + * | 
|  | 29 | + * @param {String} newStatus Order Status to be updated. | 
|  | 30 | + * @param {String} orderId Order id | 
|  | 31 | + * @param {String} transactionId Transaction id. | 
|  | 32 | + * | 
|  | 33 | + * @returns {Promise<void>} | 
|  | 34 | + */ | 
|  | 35 | +const updateOrder = async ( newStatus, orderId, transactionId = '' ) => { | 
|  | 36 | + | 
|  | 37 | +    let newOrderData = { | 
|  | 38 | +        status: newStatus | 
|  | 39 | +    } | 
|  | 40 | + | 
|  | 41 | +    if ( transactionId ) { | 
|  | 42 | +        newOrderData.transaction_id = transactionId | 
|  | 43 | +    } | 
|  | 44 | + | 
|  | 45 | +    try { | 
|  | 46 | +        const {data} = await api.put( `orders/${ orderId }`, newOrderData ); | 
|  | 47 | +        console.log( '✅ Order updated data', data ); | 
|  | 48 | +    } catch (ex) { | 
|  | 49 | +        console.error('Order creation error', ex); | 
|  | 50 | +        throw ex; | 
|  | 51 | +    } | 
|  | 52 | +} | 
|  | 53 | + | 
|  | 54 | +const handler = async (req, res) => { | 
|  | 55 | +    if (req.method === "POST") { | 
|  | 56 | +        const buf = await buffer(req); | 
|  | 57 | +        const sig = req.headers["stripe-signature"]; | 
|  | 58 | + | 
|  | 59 | +        let stripeEvent; | 
|  | 60 | + | 
|  | 61 | +        try { | 
|  | 62 | +            stripeEvent = stripe.webhooks.constructEvent(buf, sig, webhookSecret); | 
|  | 63 | +            console.log( 'stripeEvent', stripeEvent ); | 
|  | 64 | +        } catch (err) { | 
|  | 65 | +            res.status(400).send(`Webhook Error: ${err.message}`); | 
|  | 66 | +            return; | 
|  | 67 | +        } | 
|  | 68 | + | 
|  | 69 | +        if ( 'checkout.session.completed' === stripeEvent.type ) { | 
|  | 70 | +            const session = stripeEvent.data.object; | 
|  | 71 | +            console.log( 'sessionsession', session ); | 
|  | 72 | +            console.log( '✅ session.metadata.orderId', session.metadata.orderId, session.id ); | 
|  | 73 | +            // Payment Success. | 
|  | 74 | +            try { | 
|  | 75 | +                await updateOrder( 'processing', session.metadata.orderId, session.id ); | 
|  | 76 | +            } catch (error) { | 
|  | 77 | +                await updateOrder( 'failed', session.metadata.orderId ); | 
|  | 78 | +                console.error('Update order error', error); | 
|  | 79 | +            } | 
|  | 80 | +        } | 
|  | 81 | + | 
|  | 82 | +        res.json({ received: true }); | 
|  | 83 | +    } else { | 
|  | 84 | +        res.setHeader("Allow", "POST"); | 
|  | 85 | +        res.status(405).end("Method Not Allowed"); | 
|  | 86 | +    } | 
|  | 87 | +}; | 
|  | 88 | + | 
|  | 89 | +export default handler; | 
0 commit comments