Dev.to Security πŸ” Cybersecurity πŸ‘ 0 πŸ“– 11 min read

How to Prevent Payment Amount Tampering in E-Commerce APIs (Node.js + Stripe)

Imagine a customer adds a $199 product to an online shopping cart. The checkout page displays the correct amount, and the payment gateway is functioning normally. Before submitting the checkout request, the customer man

How to Prevent Payment Amount Tampering in E-Commerce APIs (Node.js + Stripe)

How to Prevent Payment Amount Tampering in E-Commerce APIs (Node.js + Stripe)

Imagine a customer adds a $199 product to an online shopping cart. The checkout page displays the correct amount, and the payment gateway is functioning normally.

Before submitting the checkout request, the customer manipulates the payment amount and changes it to $1. Before submitting the checkout request, they manipulate the payment amount and change it to $1.

If the backend trusts that modified amount instead of retrieving the actual product price from its own database, the customer could potentially complete the purchase for just $1.

The payment provider might successfully authorize the transaction. The checkout could display a successful payment confirmation. Yet the merchant would receive the wrong amount.

This is a payment amount tampering vulnerability, and it's a business-logic problem rather than a traditional payment gateway failure.

In this tutorial, we'll explore how pricing manipulation happens, build a safer checkout API using Node.js and Stripe, and identify the additional safeguards needed before deploying a payment integration to production.

What Is Payment Amount Tampering?

Payment amount tampering occurs when an application allows customer-controlled data to influence the amount charged without proper server-side verification.

In e-commerce applications, browsers frequently send information such as:

  • Product identifiers
  • Quantities
  • Coupon codes
  • Shipping selections
  • Cart contents

These values are useful inputs, but they cannot automatically be trusted.

The problem begins when a backend also accepts the product price, discount amount, or final order total from the browser as authoritative.

Consider a checkout request for headphones with a legitimate total of $149.99. If the server accepts the total supplied by the browser without verifying it, someone could modify the request to submit a total of $0.99 instead.

This demonstrates why the server must calculate payment amounts using trusted product information.

Client-side controls don't solve this problem.

A customer can modify requests using browser developer tools, scripts, or HTTP clients. Even a completely read-only price field in the interface doesn't make the underlying request trustworthy.

The important rule is simple: the browser may request a purchase, but the server must determine the amount to charge.

Why Payment Gateways Cannot Automatically Prevent This

Payment providers are responsible for processing payment requests according to their APIs and security controls.

They don't necessarily know whether a particular product is supposed to cost $20, $200, or $2,000.

If your backend instructs a payment provider to create a transaction for $1, the provider generally cannot determine that your internal product catalog lists the item at $199.

That distinction matters.

Payment authorization validates aspects of the payment transaction. It doesn't automatically validate the merchant's catalog pricing or promotional rules.

Pricing integrity therefore remains an application-level responsibility.

The Vulnerable Checkout Pattern

Consider a simplified Express endpoint:

app.post("/checkout", async (req, res) => {
  const { productId, amount } = req.body;

  const session = await stripe.checkout.sessions.create({
    mode: "payment",
    line_items: [
      {
        price_data: {
          currency: "usd",
          product_data: {
            name: productId
          },
          unit_amount: amount
        },
        quantity: 1
      }
    ],
    success_url: `${process.env.APP_URL}/success`,
    cancel_url: `${process.env.APP_URL}/cart`
  });

  res.json({ url: session.url });
});

The vulnerability comes from assigning the client-supplied amount directly to Stripe's unit_amount parameter. Because the server doesn't independently verify the product price, a manipulated request could result in an incorrect charge.

The variable comes directly from the incoming request.

Nothing establishes whether that amount corresponds to the product's actual price.

Even if the frontend normally sends the correct amount, the API is accepting a customer-supplied value as the source of truth.

This is precisely the type of pricing-integrity failure that secure business-logic design should prevent.

A Safer Checkout Architecture

A Safer Checkout Architecture

A safer design separates customer-controlled information from authoritative pricing information.

The browser submits product identifiers and quantities. The server looks up the products, validates purchase conditions, calculates the amount, and creates the payment session.

The flow looks like this:

Customer Browser
      |
      | Product IDs + quantities
      v
Backend Checkout API
      |
      | Validate cart inputs
      v
Trusted Product Catalog
      |
      | Retrieve current prices
      v
Server-Side Calculation
      |
      | Apply validated business rules
      v
Payment Provider
      |
      | Create checkout session
      v
Customer Completes Payment

The key difference is that the server never accepts a submitted final price as authoritative.

Building a Safer Checkout API With Node.js

We'll use Node.js, Express, and Stripe Checkout.

The example uses an in-memory product catalog to demonstrate pricing integrity. A production application should normally retrieve products and prices from a controlled database or another trusted server-side source.

Step 1: Install the Dependencies

Create a Node.js project and install Express, Stripe's Node.js SDK, and dotenv.

npm init -y
npm install express stripe dotenv

Create a .env file:

STRIPE_SECRET_KEY=sk_test_your_test_key
APP_URL=http://localhost:3000
PORT=3000

Use a Stripe test-mode key for development.

Never expose the secret API key in browser code or commit it to a public repository.

Step 2: Define the Product Catalog

For our example, we'll define product prices in integer cents.

const products = {
  headphones: {
    name: "Wireless Headphones",
    priceInCents: 14999,
    currency: "usd"
  },
  keyboard: {
    name: "Mechanical Keyboard",
    priceInCents: 8999,
    currency: "usd"
  }
};

Using integer minor units helps avoid problems associated with floating-point arithmetic when representing monetary amounts.

In this example, both products use USD.

Real systems need currency-aware handling because different currencies have different minor-unit conventions.

Step 3: Create the Checkout Endpoint

Create an index.js file:



require("dotenv").config();

const express = require("express");
const Stripe = require("stripe");

const app = express();
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);

app.use(express.json({ limit: "16kb" }));


const products = {
  headphones: {
    name: "Wireless Headphones",
    priceInCents: 14999,
    currency: "usd"
  },
  keyboard: {
    name: "Mechanical Keyboard",
    priceInCents: 8999,
    currency: "usd"
  }
};


app.post("/checkout", async (req, res) => {
try {
const { items } = req.body ?? {};

if (!Array.isArray(items) ||
items.length === 0 ||
items.length > 10) {
return res.status(400).json({
error: "Invalid cart"
});
}

const seen = new Set();
const lineItems = [];

for (const item of items) {
if (!item || typeof item !== "object") {
return res.status(400).json({
error: "Invalid item"
});
}

const { productId, quantity } = item;

if (
  typeof productId !== "string" ||
  !Number.isInteger(quantity) ||
  quantity < 1 ||
  quantity > 10 ||
  seen.has(productId)
) {
  return res.status(400).json({
    error: "Invalid cart item"
  });
}

const product = Object.hasOwn(
  products,
  productId
) ? products[productId] : null;

if (!product) {
return res.status(400).json({
error: "Unknown product"
});
}

seen.add(productId);

lineItems.push({
price_data: {
currency: product.currency,
product_data: {
name: product.name
},
unit_amount: product.priceInCents
},
quantity
});
}

const session = await stripe.checkout.sessions.create({
mode: "payment",
line_items: lineItems,
success_url:
`${process.env.APP_URL}/success?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${process.env.APP_URL}/cart`
});

return res.json({
checkoutUrl: session.url
});

} catch (error) {
console.error("Checkout creation failed:", error);

return res.status(500).json({
error: "Unable to create checkout"
});
}
});

app.listen(process.env.PORT || 3000);

The code demonstrates an important security boundary.

The customer controls which known products they request and the quantities within the permitted range.

The server controls the corresponding prices and currency.

The seen set rejects duplicate product entries, preventing repeated entries from being used to bypass per-item quantity limits.

This example rejects duplicate product entries and limits each product to 10 units, but it does not enforce a maximum quantity across the entire cart. If a business requires an order-wide quantity limit, that restriction must also be validated server-side.

This example intentionally omits authentication, inventory reservations, persistent orders, taxes, shipping, and discount processing. Those concerns must be addressed separately in a production checkout.

Step 4: Send a Valid Checkout Request

Start the server:

node index.js

Submit a request using curl:



curl -X POST http://localhost:3000/checkout \
-H "Content-Type: application/json" \
-d '{
"items": [
{
"productId": "headphones",
"quantity": 1
}
]
}'

If the Stripe configuration is valid, the API should return a hosted checkout URL.

The product price is retrieved from the trusted catalog rather than from the request.

Step 5: Test a Manipulated Price

To test the protection, submit a checkout request for one pair of headphones and include an additional priceInCents field with a value of 1.

The server should ignore this customer-supplied amount and retrieve the actual product price of 14,999 cents ($149.99) from its trusted catalog.

As a result, the attempted price manipulation should not change the amount charged.

This example ignores unknown properties rather than rejecting them. A stricter request schema could reject unexpected fields entirely.

The important protection remains the same: customer-supplied monetary values do not determine the charge.

What About Discounts and Coupon Codes?

Removing client-supplied prices is only part of the solution.

Discounts can introduce similar risks if they are calculated incorrectly.

Suppose a customer submits a checkout request containing the coupon code WELCOME10 along with an unauthorized discount amount of $100.

If the server trusts the submitted discount value, the customer could potentially receive a discount they aren't entitled to.

Instead, the server should validate the coupon and independently calculate any applicable discount using trusted business rules.

For example, validation may need to consider:

  • Whether the coupon exists and is active.
  • Whether it applies to the selected products.
  • Whether the customer qualifies.
  • Whether redemption or usage limits have been reached.
  • Whether it can be combined with other promotional offers.
  • Whether the resulting order total is permitted.

The same principle applies to shipping costs, taxes, gift-card balances, and store credits.

Every monetary adjustment must be validated against trusted business rules.

Five Additional Security Checks Before Production

A secure checkout requires more than correcting the initial payment amount.

1. Recalculate the Final Total Server-Side

The backend should independently determine the amount owed using authoritative information.

The final charge must account for applicable pricing rules, quantity limits, discounts, shipping, and taxes.

Avoid allowing values calculated solely in browser JavaScript to override those results.

2. Protect Against Price Changes During Checkout

Prices and inventory can change between cart creation and payment completion.

A production application should establish when the quoted price becomes binding.

Depending on the business model, this may involve storing an order snapshot, enforcing quote expiration, and reserving available inventory.

Do not assume a cart created hours earlier is still valid.

3. Verify the Actual Payment Before Fulfillment

A redirect to a success page isn't sufficient proof that a payment has completed.

Use trusted payment-provider confirmation mechanisms to verify the payment status, amount, currency, and associated order.

Fulfillment should occur only when the verified payment outcome satisfies the application's business rules.

For asynchronous payment methods, this may require waiting for later confirmation.

4. Enforce Authorization and Quantity Limits

A correctly calculated price doesn't guarantee the customer is authorized to purchase the item.

The backend should verify whether the product is available, whether the customer may purchase it, and whether requested quantities fall within permitted limits.

For example, quantity restrictions should apply to the entire order, not merely each individual line item.

5. Protect Stored Order Data

The backend should create and control the authoritative order record.

Customers should not be allowed to edit stored order totals, payment states, discounts, or fulfillment statuses through unauthorized API requests.

Payment records should be associated with the correct order using trusted identifiers and server-side verification.

A Payment Amount Tampering Test Checklist

Before releasing an e-commerce checkout integration, developers should test several scenarios to ensure the system maintains pricing integrity and prevents unauthorized changes.

Price Manipulation: Try submitting a payment request with a lower price than the actual product price. The server should ignore or reject the modified amount and calculate the correct price using trusted product data.

Invalid Product Identifiers: Submit a checkout request using a product ID that does not exist in the catalog. The system should reject the request rather than process an unknown product.

Invalid Quantities: Test negative quantities, fractional values, and unusually large quantities. The checkout API should reject invalid values and enforce appropriate purchase limits.

Duplicate Product Entries: Add the same product multiple times within a single checkout request. The system should validate the combined quantity against the applicable order limits to prevent restrictions from being bypassed.

Unauthorized Discounts: Attempt to apply a discount or coupon that is invalid, expired, or not available to the customer. The server should reject the unauthorized discount.

Currency Manipulation: Modify the currency value in a checkout request. The server should use the currency permitted by its trusted pricing configuration rather than accepting an unauthorized customer-supplied currency.

Payment Confirmation: Open the checkout success URL without completing a payment. The application must not mark the order as paid or begin fulfillment solely because the success page was accessed.

Order Amount Verification: Test a situation where the confirmed payment amount differs from the amount recorded in the original order. The system should flag the discrepancy and prevent fulfillment until the issue is resolved.

The objective of these tests is not simply to check whether the payment API returns an error. It is to confirm that the application protects pricing, order totals, and payment integrity regardless of the information submitted by the customer.

Common Implementation Mistakes

Even teams that use a reputable payment provider can introduce pricing vulnerabilities through application logic.

A few patterns deserve particular attention.

Trusting hidden form fields: A field marked as hidden in HTML remains customer-controlled.

Validating only in JavaScript: Frontend validation improves usability but cannot establish the integrity of a payment amount.

Accepting the cart total from local storage: Browser storage should never be treated as an authoritative pricing source.

Applying discounts without eligibility checks: A valid coupon code doesn't necessarily mean every customer or product qualifies.

Assuming payment success proves pricing correctness: A successful charge can still be for an incorrectly calculated amount.

These mistakes share the same underlying problem: the application crosses a trust boundary without validating the information.

Final Thoughts

Payment amount tampering is a useful reminder that payment security extends beyond encryption, tokenization, and API authentication.

A payment provider can securely process exactly the transaction your application requests while your application still charges the wrong amount.

For developers, the essential responsibility is maintaining a clear distinction between customer input and authoritative business data.

Customers should be able to choose products, quantities, and eligible offers. They should not be able to dictate the final payable amount.

A secure checkout begins with the serverβ€”not the payment button.

Technical References

For further reading and implementation verification:

OWASP β€” Business Logic Security Cheat Sheet

OWASP β€” Testing Payment Functionality

Stripe β€” Create a Checkout Session

Stripe β€” Fulfill Orders with Checkout

Stripe β€” API Keys

Implementation note: The code is an illustrative integration example, not a tested or production-ready checkout system. Validate it against your installed SDK version and test it thoroughly before deployment.

πŸ“° Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.