averageUsername123
averageUsername123

Reputation: 723

How to connect Stripe, AWS Cognito, and my RDS Postgres database all together?

The goal is to have a user table that includes their Stripe customer ID, their email they used to authenticate, and the plan they chose to buy from my web application.

It was easy enough to insert in user records once they've registered onto my web application through Cognito. On the front end, I check for when the auth state changes to "signUp", and I call my backend Express API that creates a new User with their email and username.

The tough part is when the customer has made a purchase through Stripe. I used the pre-built Checkout page that creates the UI and logic for me. I set up the event webhooks on my backend so that whenever a customer has purchased an item, I can do my logic there. The problem is that when this webhook is triggered, I don't have information about their email, so I don't know how to find their record in the database and update it with the customer ID information.

Here is my webhook code:


router.post("/webhooks", (req, res) => {
  const event = req.body;

  switch (event.type) {
    case "charge.succeeded": {
      console.log("CHARGE SUCCEEDED", event);
    }
    case "payment_intent.succeeded": {
      console.log(event);
      const paymentIntent = event.data.object;
      const customer_id = event.data.object.customer;

      console.log("PaymentIntent was successful!");

      // Cognito_User.update(
      //   {stripe_id : "test_stripe4_id"},
      //   {returning: true, where: {email: ???} }
      // )
      break;
    }
    case "payment_method.attached": {
      const paymentMethod = event.data.object;
      console.log("PaymentMethod was attached to a Customer!");
      break;
    }
    // ... handle other event types
    default: {
      // Unexpected event type
      return res.status(400).end();
    }
  }

Technically, I could use the email that the customer submitted to pay for their plan in the Stripe Checkout, but that may not always be the same email they used to log in.

I'm wondering if I can attach additional user information (their email used to login to cognito) to the webhook trigger, OR do I need to ditch the prebuild checkout and create the Stripe payment checkout flow by code?

Upvotes: 1

Views: 1242

Answers (1)

floatingLomas
floatingLomas

Reputation: 8747

You could either save the Checkout Session ID once you've created it and before you redirect, or provide an already-existing Client Reference ID from your system when you create the Session.

Either way would work.

Upvotes: 0

Related Questions