1
votes

I have a React front-end, Firebase back-end trying complete the Stripe OAuth process. The redirect URI has come back (returning to https://mywebsitename.com/oauth_return) and the react component I have opening up on that page parses over that URL and accesses the Authentication Code and state. (please see below)

inside "oauth_return.js" file

import React from 'react';
import queryString from 'query-string';

const oauth_redirect  = () => {

    //Parsing over URL
    const value=queryString.parse(window.location.search);
    const code=value.code;
    console.log('code:', code)
    const state=value.state;
    console.log('state:', state)
}
export default (oauth_redirect)

What I am having difficulty doing is trying to figure out how to make the firebase HTTP function return the authentication code via a POST method. All of my firebase functions exist inside the "index.js" file of the functions directory. All of the tutorials that I have seen show various ways of building this function in Typescript, but my code needs to be written in Javascript.

inside "functions/index.js" file

(...)

  exports.stripeCreateOathResponseToken = functions.https.onRequest((req, res) => {

  (...) Not sure what to write in this function to return the authorization code. All tutorials I've found are written in Typescript.

});

Unfortunately I don't understand how this HTTP function can be triggered to be called in the first place (i.e. do I need to explicitly call it inside the "oauth_return.js" file? How do I pass the authorization code into it? And most importantly, how does it send back the authorization code to Stripe?

Any clarity on this issue would be greatly appreciated.

1
You already have a great answer below that I think is worth exploring. But I wanted to point out that Stripe has a new onboarding flow for Standard/Express accounts that doesn't require OAuth. It might be worth looking into. You can read more on that here: stripe.com/docs/connect/standard-accounts, stripe.com/docs/connect/express-accountsttmarek
Thanks ttmarek! I'll definitely look into this solution as well.Andrew B.

1 Answers

3
votes

Here is the working code written for exact purpose as yours. Hope this would help you in providing solution.

exports.stripeCreateOathResponseToken = functions.https.onRequest((req, res) => {

    res.set('Access-Control-Allow-Origin', '*');

    if (req.method === 'OPTIONS') {
        console.log('Executing OPTIONS request code block');
        res.set('Access-Control-Allow-Methods', 'POST');
        res.set('Access-Control-Allow-Headers', 'Origin, Content-Type, Accept');
        res.set('Access-Control-Max-Age', '3600');
        res.status(204).send('');
    } else if (req.method === 'POST') {
        console.log('Executing POST request code block');
        return oauthResponseCheck(req, res);
    }
    else {
        // Log, but ignore requests which are not OPTIONS or POST.
        console.log(`We received an invalid request method of type: ${req.method}`);
        return;
    }
});


function oauthResponseCheck(req, res) {
     // code: An authorization code you can use in the next call to get an access token for your user.
    // This can only be used once and expires in 5 minutes.

    // state: The value of the state parameter you provided on the initial POST request.
    const { code, state } = req.body;

    // Assert the state matches the state you provided in the OAuth link (optional).
    if (!stateMatches(state)) {
        console.log('Incorrect state parameter for state::', state)
        return res.status(403).json({ error: 'Incorrect state parameter: ' + state });
    }
   
    // Send the authorization code to Stripe's API.
    stripe.oauth.token({
        grant_type: 'authorization_code',
        code
    }).then(
        (response) => {
            var stripe_connected_account_id = response.stripe_user_id;
         
            console.log('Stripe Connected Account Saved successfully: ' + JSON.stringify(response));
            return res.status(200).json({
                status: true,
                message: 'Stripe Connected Account Saved successfully',
                data: response
            });

        },
        (err) => {
            if (err.type === 'StripeInvalidGrantError') {
                console.log('Invalid authorization code: ' + code);
                return res.status(400).json({
                    status: false,
                    message: 'Invalid authorization code.::' + code,
                }
                );
            } else {
                console.log('An unknown error occurred: ' + err);
                return res.status(500).json({
                    status: false,
                    message: 'An unknown error occurred.::' + err,
                });
            }
        }
    );
})