I maintain flutter_stripe, the package most Flutter apps use to talk to Stripe. Next to it I keep a small open-source example called StripePod that is a full-stack payment integration blueprint made with Flutter and Serverpod. Last week I had finally some time to fix one of the known issues: the endpoint that starts a payment could be called by anyone on the internet, without signing in and the endpoint would return a PaymentIntent to whoever asked. I see the same thing in a lot of first payment integrations, handling payments is the exciting part but making things more secure is less glamorous. In this article I write why it is important to

How a card payment works, in three steps

If you have never built this before, it helps to know that a card payment with Stripe is a conversation between three parties: you, Stripe and the client. The process go roughly like this.

  1. Your server asks Stripe to create a PaymentIntent, which is Stripe’s record of somebody intends to pay this amount. You authenticate yourself to Stripe with your secret key, which never leaves the server so it knows who is asking.
  2. Stripe answers with a client secret for that one PaymentIntent. Your server hands it to the app.
  3. The client fills in the details and the app then sends the card details straight to Stripe together with the client secret and your publishable key. The card number never touches your server and Stripe tells your server the result through a webhook.

The design is good, because the dangerous key stays on the server and the card data stays with Stripe. What it leaves to you is the very first step: an endpoint on your server that says “create a payment for me” and gives back a client secret.

What can go wrong when the caller is anonymous

When building payment functionality it is useful to always keep asking yourself “is this secure?” and “what can go wrong here?”. If you look at not having authentication in place when dealing with payments I can see four threats.

The first is card testing, which is the one most people have heard of. Criminals who buy lists of stolen card numbers need to find out which ones still work. The cheapest way is a script that pushes small payments through somebody else’s checkout. An open pay endpoint is what that script is looking for, because it can ask for a fresh PaymentIntent as often as it likes and try a card against each one with your publishable key, which is public by design. Stripe’s documentation is clear about what this costs the merchant: disputes for the test payments that succeeded, fees and a wave of declines that damages your standing with card issuers. The same page says in so many words that “you can reduce your exposure to card testers by requiring login or session validation before they can make a payment.”

The second is that the payment belongs to nobody. Stripe will tell you that a payment succeeded, but if your own record of it has no owner, how do you know that you actually shipped a product to that customer? In security we call this repudiation and the threat is simply that you can’t show what happened.

The third is that anyone can read anyone’s payment. If your lookup endpoint takes a payment id and returned the payment, including the amount and the status, without checking who was asking you suffer from broken object level authorisation and it is number one on the OWASP API Security Top 10. Payment ids are long and hard to guess, but ids end up in URLs, logs and support emails and you don’t want the privacy of a payment to depend on an id staying secret.

The fourth is that flooding you is cheap. Every call to an open pay endpoint makes your server call Stripe and write a row to your database. So a loop on somebody’s laptop can create thousands of PaymentIntents and eat into your Stripe rate limit while real customers are trying to pay.

Two questions, not one

Having an sign in screen helps you answering two questions:

  1. Authentication: who are you?
  2. Authorisation: am I allowed to this? The server will make the decision for every request using the answers it gets from the authentication.

As you probably have guessed: you need the first to do the second. The first doesn’t give you the second for free: an endpoint can require a login and still hand user A’s payment to user B, because being signed in only proves that you are somebody.

So the fix has two parts. Only signed-in users may start a payment and a payment may only be read by the user who made it.

Use the sign-in your framework already has

One rule that I often apply is to use standard, well-tested mitigations and not to invent your own. Password hashing, email verification codes, password reset and token refresh are all places where a home-made version looks fine and is quietly wrong.

My own StripePod’s backend is written with Serverpod, a backend framework for Dart. Serverpod comes with its own auth module. I chose email and password as the way to sign in and JWTs as the tokens, the module took care of the rest. Two things about it matter for payments. The users live in the same Postgres database as the payments, so the owner of a payment is a plain column in my own database and not an id I have to look up at a third party. Once it is switched on, every endpoint can ask the session who is calling, which keeps the authorisation code as short as you will see below.

On the app side the module brings a ready-made sign-in widget and this is where it saved me the most time. I dropped it into a screen and got registration, the email verification step, sign-in and password reset, without writing a single form or validator myself:

SignInWidget(
  client: client,
  onError: (error) => ScaffoldMessenger.of(context).showSnackBar(
    SnackBar(content: Text('Sign in failed: $error')),
  ),
)

Whatever stack you use, the point is the same: look for the auth your framework or platform already ships before you build one. The interesting work is in the next section and not in a password form, a problem that has been solved millions of times. Side note: the setup for Serverpod’s auth is in their authentication docs, so I’ll skip it here.

The three changes that matter

The first change is that a payment gets an owner. In Serverpod you describe your tables in a small YAML file and the change is one field and an index on it:

  createdAt: DateTime
  userId: UuidValue?
indexes:
  payments_user_id_idx:
    fields: userId

The field is nullable on purpose, so that existing payments survive the migration. They have no owner, which means nobody can read them through the API anymore, for old rows I think that is the right default.

The second change closes the endpoint for anonymous callers and stamps every new payment with the caller:

class PayEndpoint extends Endpoint {
  @override
  bool get requireLogin => true;

  Future<StripePaymentInfo> pay(Session session, int productId) async {
    // ... look up the product, create the PaymentIntent at Stripe ...
    await Payment.db.insertRow(
      session,
      Payment(
        stripeId: json['id']!,
        amount: product.priceInCents,
        currency: 'usd',
        status: PaymentStatus.pending,
        createdAt: DateTime.now(),
        userId: session.authenticated!.authUserId,
      ),
    );

If you look at the client’s definition you notice it can only send one thing and that is: product id. The amount comes from the server’s own product list and the user id comes from the session. I chose this on purpose because anything the client sends is something the client can change.

The third change is the one that is easiest to forget, and it is the authorisation half of the story:

Future<Payment> getPaymentById(Session session, String stripeIntentId) async {
  final payment = await Payment.db.findFirstRow(
    session,
    where: (table) =>
        table.stripeId.equals(stripeIntentId) &
        table.userId.equals(session.authenticated!.authUserId),
  );
  if (payment == null) {
    throw ApiException(404, 'Payment not found');
  }
  return payment;
}

The ownership check sits inside the query, so there is no moment where the server holds somebody else’s payment and has to remember not to return it. Asking for another user’s payment gives the same “not found” as asking for one that doesn’t exist. The endpoint doesn’t tell a curious caller which ids are real.

A mitigation without a test is a hope, so the last piece is a test that inserts a payment for one user and asks for it as another:

await Payment.db.insertRow(
  sessionBuilder.build(),
  _payment(stripeId: 'pi_test_other_user', userId: otherUserId),
);

await expectLater(
  () => PayEndpoint().getPaymentById(userSession.build(), 'pi_test_other_user'),
  throwsA(isA<ApiException>().having((e) => e.message, 'message', 'Payment not found')),
);

The whole change is in StripePod on GitHub if you want to read it in context.

What sign-in doesn’t fix

Sign-in is not the end of it and I would be overselling if I said it was. A bot can register accounts too, so a determined card tester is slowed down by a verified email address and not stopped by it. Stripe’s advice is to keep rate limiting payments after login as well. My example doesn’t have that rate limit yet. Another thing it doesn’t yet check that the caller is my real app and not a script, which is what app attestation is for. Those are the next two things I’m building.

On the UX side there is also a fair objection, which is that plenty of shops let you pay as a guest. That is a business decision and often the right one, but it doesn’t remove the risks mentioned before. The server still needs something to tie the payment to, such as an order or a session it created itself and it needs a CAPTCHA or strict rate limits where the login would have been. What you can’t do is skip both and hope.

Conclusion

Decide who is allowed to create a payment and who is allowed to read one before you write your first line of Stripe code and make that decision on the server. Hiding a button in the app protects nothing. With the user in the session it cost me one getter, one column and one extra condition in a query, which is a lot cheaper than explaining to Stripe where all those declined cards came from.