DEV Community

Cover image for Stripe Connect Integration in Marketplace App
Sarthak kumar
Sarthak kumar

Posted on • Updated on

Stripe Connect Integration in Marketplace App

Set up stripe:

  • npm install --save stripe
  • Put your stripe secrets in .env file

Create stripe object (backend - server.js)

const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY, {
  apiVersion: '2020-08-27',
  appInfo: {
    name: "stripe-samples/accept-a-payment/custom-payment-flow",
    version: "0.0.2",
    url: "https://github.com/stripe-samples"
  }
});
Enter fullscreen mode Exit fullscreen mode

Seller Onboarding: Creating seller stripe account (backend - server.js)

app.get('/stripeConnectRegisterSeller', async (req, res) => {
  try{
    //Create Express account for the seller
    const account = await stripe.accounts.create({type:'standard'});
    console.log(account);

    //Create account link
    const accountLink = await stripe.accountLinks.create({
      account: account.id,
      refresh_url: 'http://localhost:8080/failed',
      return_url: 'http://localhost:8080/success',
      type: 'account_onboarding',
    });

    console.log(accountLink);
    res.status(200).json({success: true, url: accountLink.url});
  }
  catch(err){
    console.log(err);
    res.send(err);
  }
});
app.get('/success', (req, res)=>{
  res.send("Success");
});
app.get('/failed', (req, res)=>{
  res.send("Failed");
});
Enter fullscreen mode Exit fullscreen mode

Redirect the user to accountLink (frontend - account.js)

async function addAccount(){
    document.getElementById("accountDetails").innerHTML = "Wait for request to process"
    await fetch(`${BACKEND_URL}/stripeConnectRegisterSeller`)
        .then(res=>res.json())
        .then(res => {

            accountId = res.accountId;
            const currentUser = Moralis.User.current();
            currentUser.set("account_ID", accountId);
            currentUser.save();
            return res
        }) 
        .then(res => {
            window.location = res.url;
        })
        .catch(err => console.log(err))
}
Enter fullscreen mode Exit fullscreen mode
  • Seller will fill their required details to create stripe account. User will be redirected to the return_url after compeleting onboarding.

Payment by customer to the registered seller (backend - server.js)

  • Create checkout session using stripe API and send this session object to the frontend
app.post('/create-checkout-session', async (req, res) => {
  const {currency, paymentMethodType, amount, userEthAddress, userStripeAccountId, tokenId, productType } = req.body;
  console.log({paymentMethodType, amount, currency, userEthAddress, userStripeAccountId, tokenId, productType})
  const session = await stripe.checkout.sessions.create({
    payment_method_types: ['card'],
    line_items: [{
      name: "Connect",
      amount: amount,
      quantity: 1,
      currency: currency,
    }],
    mode: 'payment',
    success_url: 'https://example.com/success',
    cancel_url: 'https://example.com/failure',
    payment_intent_data: {
      application_fee_amount: 0.03*amount,
      transfer_data: {
        destination: userStripeAccountId,
      },
    },
  });

  res.send({session})
});
Enter fullscreen mode Exit fullscreen mode

Redirect to stripe payment page (frontend - payment.js)

const makePayment = async ()=>{
    const currentBid = document.querySelector('#payment-modal-token-price').value;
    const userEthAddress = localStorage.getItem('userEthAddress');
    const tokenId = parseInt(localStorage.getItem('tokenId'));
    let productType = getProductType();

    await fetch(
        `${BACKEND_URL}/create-checkout-session`,
        {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                currency: 'inr',
                amount: currentBid*100*80,
                paymentMethodType: 'card',
                userEthAddress: userEthAddress,
                userStripeAccountId: 'acct_1K3HMxQkqeDnOAwK',
                tokenId: tokenId,
                tokenNos: 1,
                productType: productType
            }),
        }
    )
    .then((r) => r.json())
    .then((res)=>{
        const sessionId = res.session['id']; 
        var stripe = Stripe(STRIPE_PUBLISHABLE_KEY)
        stripe.redirectToCheckout({
            sessionId: sessionId
        }).then(function (result) {
            result.error.message = 'Error'
        });
        console.log(res);
    })
    .catch((err)=>console.log(err));
}
Enter fullscreen mode Exit fullscreen mode
  • After completing payment process page will be redirected to success_url or cancel_url depending on the user response.

Top comments (0)