How to authorize your web to connect to a Stripe account

I will divide this article into 2 parts:

  1. Client-side
  2. Server-side

Client-side

Let's assume that we want to authorize a Stripe account to connect to our web. If we are using React, we can create a button to redirect the user to Stripe:

jsx
import React, { useState, useEffect } from 'react';

const ConnectToStripe = () => {
    
    const connectToStripe = () => {
        
        // URL to authorize OAuth    
        let url = 'https://connect.stripe.com/oauth/authorize';
       
        // Go to `https://dashboard.stripe.com/settings/applications`
        let clientID = 'STRIPE_CLIENT_ID'; 
        
        // Redirecting the user to desired URL
        window.location.href = `${url}?response_type=code&client_id=${clientID}&scope=read_write`;
        
    }
    
    return(
        <div className = 'StripeConnection'>
            <button onClick = {connectToStripe}></button>
        </div>
    );
    
}

export default ConnectToStripe;

At this point, if the user clicks on the button, he will be redirected to Stripe and he will be able to authorize Stripe to connect his account.

If the user accepts to connect, Stripe will send the user back to our webpage, but now the URL will include a code.

Example:

https://erikmartinjordan.com?code=iJOEjfmkMOEur892904jmfm

We will read this code from the URL and send it back to Stripe to complete the connection.

jsx
import React, { useState, useEffect } from 'react';

const ConnectToStripe = () => {
    
    useEffect(() => {
        
        // Getting the current URL
        let url = window.location.href;
        
        // If URL has parameters, we read them
        if(url.includes('?')){
            
            // We transform parameters to object
            let res = transformURLparametersToObject(url);
            
            if(res.code){
                
                // We complete the Stripe connection
                completeStripeConnection(res.code);
                
            }
            
        }
        
    }, []);   
    
    const connectToStripe = () => {
        
        // URL to authorize OAuth    
        let url = 'https://connect.stripe.com/oauth/authorize';
       
        // If you go to `https://dashboard.stripe.com/settings/applications` you will see your client ID.
        let clientID = 'STRIPE_CLIENT_ID'; 
        
        // Redirecting the user to desired URL
        window.location.href = `${url}?response_type=code&client_id=${clientID}&scope=read_write`;
        
    }
    
    return(
        <div className = 'StripeConnection'>
            <button onClick = {connectToStripe}></button>
        </div>
    );
    
}

export default ConnectToStripe;

Now we need to define both functions transformURLparametersToObject(url) and completeStripeConnection(code):

jsx
import React, { useState, useEffect } from 'react';

const ConnectToStripe = () => {
    
    useEffect(() => {
        
        // Getting the current URL
        let url = window.location.href;
        
        // If URL has parameters, we read them
        if(url.includes('?')){
            
            // We transform parameters to object
            let res = transformURLparametersToObject(url);
            
            if(res.code){
                
                // We complete the Stripe connection
                completeStripeConnection(res.code);
                
            }
            
        }
        
    }, []);
    
    const transformURLparametersToObject = (url) => {
        
        // Getting the string after the quotation mark
        let str = url.split('?')[1];
        
        // Splitting if we hit a &
        let arr = str.split('&');
        
        // Resplitting again
        let entries = arr.map(str => [str.split('=')[0], str.split('=')[1]]);
        
        // Transforming into object
        let res = Object.fromEntries(entries);
        
        return res;
        
    }
    
    const connectToStripe = () => {
        
        // URL to authorize OAuth    
        let url = 'https://connect.stripe.com/oauth/authorize';
       
        // If you go to `https://dashboard.stripe.com/settings/applications` you will see your client ID.
        let clientID = 'STRIPE_CLIENT_ID'; 
        
        // Redirecting the user to desired URL
        window.location.href = `${url}?response_type=code&client_id=${clientID}&scope=read_write`;
        
    }

    const completeStripeConnection = async (authorizationCode) => {
        
        // Defining the URL to fetch
        let fetchURL = 'URL_TO_FETCH';
        
        // Getting response
        let response = await fetch(fetchURL, {
            
            method: 'POST',
            headers: {'Content-Type':'application/json'},
            body: JSON.stringify({
                authorizationCode: authorizationCode,
            })
            
        });
        
        if(response.ok){
            
            let data = await response.json();
            
            let stripeUserId = data.stripeUserId;
            
            console.log(`User is connected to Stripe with ID ${stripeUserId}`)
            
        }
        
    }
    
    return(
        <div className = 'StripeConnection'>
            <button onClick = {connectToStripe}></button>
        </div>
    );
    
}

export default ConnectToStripe;

Server-side

From the server-side, we'll create an endpoint (URL to fetch).

The fetch() function from the client side will send the authorization code to the server. After the server receives it, we'll send it to Stripe via stripe.oauth.token():

jsx
exports.stripeAccountConnection = functions.https.onRequest( (request, response) => {
    
    return cors(request, response, async () => {
        
        let stripe = require('stripe')('SECRET_API_KEY');
        
        let authorizationCode = request.body.authorizationCode;
        
        let oauth = await stripe.oauth.token({
            grant_type: 'authorization_code',
            code: authorizationCode,
        });
        
        let stripeUserId = oauth.stripe_user_id;
        
        stripeUserId
        ? response.status(200).json({stripeUserId: stripeUserId})
        : response.status(500).send('Error!'); 
        
    });
    
});

The function ends sending the Stripe user identification back.

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.