← Back to Blog
Payment IntegrationMarch 8, 202621 min read

Payment Gateway Integration Guide: Stripe, Square, and Beyond (2026)

How to integrate payment gateways — hosted vs embedded vs API-direct approaches, PCI compliance, multi-gateway architecture, and testing strategies.

↓ Read article

Accepting payments online sounds simple until you start building it. The moment you move past a basic "buy now" button, you encounter a maze of decisions: which gateway to use, how to embed the payment form, how to handle PCI compliance, what to do when a payment fails asynchronously, and how to test everything without charging real credit cards.

This guide walks through the full lifecycle of payment gateway integration, from choosing a provider through testing and going live. We cover the three main integration approaches (hosted, embedded, and API-direct), explain PCI compliance requirements at each level, and show how to architect a multi-gateway system for resilience and flexibility. At Sunrise Digital Labs, we build payment integrations that handle real-world complexity---failed charges, webhook retries, subscription upgrades, and multi-currency support.

Choosing a Payment Gateway

Before writing any code, you need to select a payment provider that fits your business model, geography, and technical requirements. The right choice depends on several factors:

Transaction Fees

Every gateway takes a cut. Most charge a percentage plus a fixed fee per transaction. The differences seem small on paper but compound at scale. A business processing $1 million annually would pay roughly $29,000 in fees at 2.9% versus $25,000 at 2.5%---a $4,000 annual difference from just 0.4%.

Supported Payment Methods

Customer expectations vary by market. North American buyers expect credit cards and Apple Pay. European customers often prefer SEPA direct debit or iDEAL. Southeast Asian markets rely heavily on local digital wallets. Your gateway must support the payment methods your customers actually use.

Developer Experience

The quality of a gateway's API documentation, SDKs, and sandbox environment directly impacts integration speed and maintenance cost. A well-documented API with clear error codes and test tools saves dozens of engineering hours over a poorly documented one.

Settlement Speed

How quickly funds move from the customer's payment to your bank account varies by provider. Some offer next-day deposits; others hold funds for several business days. For cash-flow-sensitive businesses, settlement speed matters.

Major Gateway Comparison

FactorStripeSquarePayPal/BraintreeAdyen
Standard rate (US)2.9% + $0.302.9% + $0.302.59% + $0.49Custom pricing
Global coverage47+ countries8 countries200+ countries30+ countries
Payment methods100+Cards, wallets, ACHCards, PayPal, Venmo, wallets250+
Hosted checkoutStripe CheckoutSquare Checkout APIPayPal CheckoutDrop-in
Embedded formPayment ElementWeb Payments SDKHosted FieldsWeb Components
Direct APIPayment Intents APIPayments APITransaction APIClassic API
PCI burden (hosted)SAQ ASAQ ASAQ ASAQ A
Sandbox qualityExcellentGoodGoodGood
Best forSaaS, marketplaces, startupsOmnichannel retailGlobal consumer brandsEnterprise

Three Integration Approaches

Every major payment gateway offers multiple ways to integrate. Understanding the trade-offs between them is essential for making the right architectural decision.

1. Hosted Checkout Pages

With hosted checkout, the customer leaves your site, completes payment on the gateway's hosted page, and is redirected back to your confirmation page. This is the simplest integration approach and carries the lowest PCI compliance burden.

Stripe Checkout exemplifies this approach. You create a Checkout Session on your server with the line items and pricing, receive a URL, and redirect the customer. Stripe handles the entire payment UI, validation, and error handling. After payment, the customer returns to your success URL with a session ID you can use to verify the payment.

The Square Checkout API follows a similar pattern. You call the CreatePaymentLink endpoint with your order details and receive a hosted checkout URL. Square handles the payment form, processes the transaction, and redirects the buyer back to your site or displays a Square-hosted confirmation page.

PayPal Checkout offers its own hosted experience with "Smart Payment Buttons" that present PayPal, credit card, and local payment options based on the buyer's location and device.

Advantages:

  • Minimal front-end code (often just a redirect)
  • Gateway handles all PCI-sensitive data---you never touch card numbers
  • Lowest PCI compliance scope (SAQ A)
  • Mobile-responsive out of the box
  • Gateway handles 3D Secure, SCA, and regional compliance requirements

Disadvantages:

  • Customer leaves your domain, which can reduce conversion rates
  • Limited control over the checkout UI and branding
  • Harder to build custom flows (upsells, cross-sells, dynamic pricing)
  • Redirect latency adds friction to the payment experience

Best for: Businesses that prioritize speed to market over UI customization, low-volume sellers, and any business that wants minimal PCI compliance scope.

2. Embedded Payment Forms

Embedded forms let you collect payment details on your own site using pre-built UI components from the gateway. The components render inside iframes or secure fields hosted by the gateway, so your server never handles raw card data, but the customer experience feels native to your site.

The Stripe Payment Element is the most fully featured embedded payment component available. It renders a complete payment form that dynamically displays relevant payment methods based on the customer's location, currency, and transaction amount. It handles input validation, error messaging, and 3D Secure authentication---all within a customizable UI that can match your brand's fonts, colors, and layout.

The Square Web Payments SDK takes a similar approach. It provides a JavaScript library that renders secure payment inputs on your page. The SDK generates single-use payment tokens that you send to your backend for processing through the Payments API. It supports credit cards, digital wallets (Apple Pay, Google Pay), ACH transfers, Afterpay, and Cash App Pay.

Advantages:

  • Customer stays on your domain throughout checkout
  • Full control over page layout and surrounding UI
  • Gateway handles PCI-sensitive card fields via iframes
  • Still qualifies for reduced PCI scope (SAQ A-EP)
  • Supports custom checkout flows (multi-step, upsells, subscriptions)

Disadvantages:

  • More front-end code than hosted checkout
  • Must handle JavaScript SDK loading, initialization, and error states
  • Testing requires rendering the full page with embedded components
  • Cross-browser compatibility needs verification

Best for: E-commerce sites, SaaS products, and any business where a seamless checkout experience matters for conversion rates.

3. API-Direct Integration

API-direct integration means your server communicates directly with the payment gateway's API. You collect payment details (through your own form or a tokenization step), send them to the gateway, and handle the response. This offers maximum control but carries the highest PCI compliance burden.

With Stripe, this means using the Payment Intents API to create and confirm payments server-side. You can build entirely custom payment flows, handle complex business logic between payment steps, and integrate with systems that do not support client-side JavaScript.

Advantages:

  • Complete control over every aspect of the payment flow
  • No dependency on front-end JavaScript SDKs
  • Can integrate with any system (point-of-sale terminals, IVR systems, batch processing)
  • Suitable for server-to-server payment scenarios (recurring billing engines, marketplace disbursements)

Disadvantages:

  • Highest PCI compliance scope (SAQ D if handling raw card data)
  • Requires secure infrastructure for handling card data
  • More code to write and maintain
  • Must implement your own input validation, error handling, and 3D Secure flows

Best for: Platforms with unique payment flows, server-side recurring billing systems, and businesses with the engineering resources and compliance infrastructure to handle PCI SAQ D requirements.

Choosing the Right Approach

ConsiderationHostedEmbeddedAPI-Direct
Time to integrateHoursDaysWeeks
PCI scopeSAQ ASAQ A-EPSAQ D
UI customizationLimitedHighFull
Conversion optimizationModerateHighHighest (if done well)
Maintenance burdenLowModerateHigh
Mobile experienceGateway-managedCustomCustom
Subscription supportYesYesYes
Multi-step checkoutNoYesYes

For most businesses, embedded payment forms hit the sweet spot: strong conversion rates, reasonable PCI scope, and enough customization to match your brand. Start with embedded and only move to API-direct when you have a specific requirement that embedded cannot satisfy.

PCI Compliance Levels

Any business that accepts, processes, stores, or transmits cardholder data must comply with the Payment Card Industry Data Security Standard (PCI DSS). The PCI Security Standards Council maintains these requirements, and non-compliance can result in fines, increased transaction fees, or loss of the ability to accept card payments.

Your compliance obligations depend on two factors: your annual transaction volume and your integration approach.

Merchant Levels by Transaction Volume

LevelAnnual TransactionsValidation Requirement
Level 1Over 6 millionAnnual on-site audit by QSA + quarterly network scan
Level 21--6 millionAnnual SAQ + quarterly network scan
Level 320,000--1 million (e-commerce)Annual SAQ + quarterly network scan
Level 4Under 20,000 (e-commerce)Annual SAQ (network scan may be required)

SAQ Types by Integration Approach

The Self-Assessment Questionnaire (SAQ) you must complete depends on how your integration handles card data:

SAQ A (fewest requirements): For merchants who fully outsource all cardholder data functions. If you use hosted checkout pages where the customer enters card details entirely on the gateway's domain, you qualify for SAQ A. This covers approximately 22 requirements.

SAQ A-EP (moderate requirements): For merchants who partially outsource payment processing but whose website controls the redirect to the payment page, or who use embedded payment fields (iframes). This covers approximately 139 requirements---significantly more than SAQ A.

SAQ D (full requirements): For merchants who handle cardholder data directly. If your server processes, stores, or transmits card numbers, you must complete SAQ D, which covers all 300+ PCI DSS requirements.

How Integration Approach Affects PCI Scope

Stripe's security documentation notes that PCI compliance is a "shared responsibility" between Stripe and the merchant. Stripe itself is PCI Level 1 certified---the highest level---through annual audits by independent assessors. By using Stripe's hosted or embedded payment components, merchants inherit much of that compliance, dramatically reducing their own obligations.

The practical takeaway: every level of indirection between your server and raw card data reduces your PCI scope. Hosted checkout means card data never touches your infrastructure at all. Embedded forms mean card data passes through Stripe-hosted iframes on your page but never reaches your server. API-direct integration with tokenization means your client tokenizes card data before it reaches your server. Only if you handle raw card numbers on your server do you face the full SAQ D burden.

Practical Compliance Steps

Regardless of your SAQ level, every merchant should:

  1. Use HTTPS everywhere. There is no excuse for transmitting any data over unencrypted connections.
  2. Never log card data. Ensure your application logs, error tracking, and analytics tools cannot capture card numbers, CVVs, or full expiration dates.
  3. Restrict access. Only personnel who need access to payment systems should have it. Use role-based access controls and audit logs.
  4. Keep systems patched. Unpatched software is the most common entry point for payment data breaches.
  5. Monitor for anomalies. Set up alerts for unusual transaction patterns, failed authentication attempts, and unexpected API calls.

Multi-Gateway Architecture

Relying on a single payment gateway creates a single point of failure. When that gateway goes down (and every gateway has outages), your business cannot process payments. A multi-gateway architecture provides redundancy, optimizes costs, and lets you route transactions to the best provider for each scenario.

Why Use Multiple Gateways

  • Redundancy: If your primary gateway is experiencing an outage, transactions automatically route to the backup
  • Cost optimization: Different gateways offer better rates for different card types, currencies, or transaction sizes
  • Geographic optimization: A gateway with strong local acquiring relationships in a specific region will have higher authorization rates there
  • Feature coverage: One gateway might handle subscriptions better while another excels at marketplace payouts

Architecture Patterns

Active-Passive Failover: Your application sends all transactions to the primary gateway. If a request fails with a gateway error (not a card decline), the system retries with the secondary gateway. This is the simplest pattern to implement.

Intelligent Routing: A routing layer evaluates each transaction and selects the optimal gateway based on rules: card type, currency, amount, geographic origin, or historical success rates. This maximizes authorization rates and minimizes fees but requires more infrastructure.

Split by Function: Different gateways handle different payment types. For example, Stripe handles card payments and subscriptions, Square handles in-person payments, and PayPal handles buyer-initiated payments. This avoids the complexity of full routing logic while still leveraging each gateway's strengths.

Implementation Considerations

// Simplified multi-gateway payment service pattern
class PaymentService {
  async processPayment(order, paymentMethod) {
    const gateway = this.selectGateway(order, paymentMethod);

    try {
      const result = await gateway.charge(order.amount, paymentMethod);
      return { success: true, gateway: gateway.name, transactionId: result.id };
    } catch (error) {
      if (this.isGatewayError(error)) {
        // Gateway issue, try fallback
        const fallback = this.getFallbackGateway(gateway);
        const result = await fallback.charge(order.amount, paymentMethod);
        return { success: true, gateway: fallback.name, transactionId: result.id };
      }
      // Card decline or validation error, do not retry
      throw error;
    }
  }
}

Critical rule: Never retry a declined transaction on a different gateway. A card decline means the issuing bank rejected the transaction---retrying it elsewhere will not change the outcome and may flag your merchant account for suspicious activity. Only retry on gateway infrastructure errors (timeouts, 5xx responses, network failures).

Reconciliation Challenges

With multiple gateways, reconciliation becomes more complex. Each gateway has its own transaction IDs, settlement schedules, and reporting formats. Build a unified payment record in your database that stores the gateway used, its native transaction ID, the mapped status, and all amounts. This becomes your source of truth for refunds, disputes, and accounting.

Testing Strategies

Payment testing requires a disciplined approach because you are dealing with real money, real customer data, and real compliance obligations. Every major gateway provides sandbox environments specifically for this purpose.

Sandbox and Test Mode

Stripe's testing documentation provides a comprehensive sandbox environment where developers can "test Stripe functionality without affecting your live integration." Stripe provides test card numbers for every scenario: successful charges, declined cards, fraudulent cards, and specific error codes. The canonical test card number 4242 4242 4242 4242 simulates a successful Visa transaction. Any three-digit CVC and any future expiration date work in test mode.

Square's sandbox provides separate application credentials and test endpoints. The Web Payments SDK operates identically in sandbox and production, making the transition straightforward.

Test Scenarios to Cover

A thorough payment test suite should cover these scenarios:

Happy path:

  • Successful one-time payment with various card brands
  • Successful subscription creation and first charge
  • Successful payment with alternative methods (ACH, wallets)

Decline scenarios:

  • Insufficient funds
  • Expired card
  • Incorrect CVC
  • Card reported stolen
  • Generic decline

Edge cases:

  • Payment succeeds on gateway but your webhook handler fails
  • Duplicate payment attempts (customer double-clicks)
  • Partial amount authorization
  • Currency conversion with rounding
  • Extremely large and extremely small amounts
  • Unicode characters in billing names and addresses

Infrastructure failures:

  • Gateway timeout during payment creation
  • Network failure after payment is confirmed but before your system records it
  • Webhook delivery failure and retry
  • Idempotency key collisions

Automated Testing Approach

Structure your payment tests in layers:

  1. Unit tests: Test your payment service logic with mocked gateway responses. Cover routing logic, error handling, retry behavior, and data mapping without making real API calls.
  2. Integration tests: Test against the gateway's sandbox API to verify that your request formatting, authentication, and response handling work correctly.
  3. End-to-end tests: Use browser automation to test the complete payment flow from product selection through checkout completion, including embedded payment forms.

Webhook Handling

Payments are inherently asynchronous. A customer submits a payment, the gateway processes it, the issuing bank authorizes (or declines) it, and funds eventually settle. Webhooks are how the gateway notifies your system about each state change.

Stripe's webhook documentation describes webhooks as the mechanism to "respond to asynchronous events, such as when a customer's bank confirms a payment, a customer disputes a charge, or a recurring payment succeeds."

Essential Webhook Events

At minimum, your integration should handle:

EventWhat It MeansWhat to Do
payment_intent.succeededPayment confirmedFulfill the order, send confirmation email
payment_intent.payment_failedPayment declinedNotify customer, offer retry
charge.refundedRefund processedUpdate order status, adjust inventory
charge.dispute.createdCustomer filed chargebackPause fulfillment, gather evidence
customer.subscription.updatedSubscription changedUpdate access level, notify customer
invoice.payment_failedRecurring payment failedSend dunning email, retry per policy

Webhook Security

Never process a webhook without verifying its authenticity. Stripe signs every webhook with your endpoint secret, and their documentation recommends you "verify that webhook events originate from Stripe before acting on them" using signature verification. The signature includes a timestamp to prevent replay attacks, with a default tolerance window of five minutes.

Webhook Best Practices

Based on Stripe's guidance and our implementation experience:

  1. Return 200 immediately. Process the event asynchronously after acknowledging receipt. If your handler takes too long, the gateway will assume delivery failed and retry, potentially causing duplicate processing.
  2. Handle duplicates. Gateways retry failed deliveries. Store processed event IDs and skip duplicates.
  3. Subscribe selectively. Only subscribe to events you actually handle. Each unnecessary event type adds load to your webhook endpoint.
  4. Process asynchronously. Enqueue webhook events for background processing rather than handling them in the HTTP request cycle.
  5. Log everything. Webhook events are your audit trail for payment state transitions. Log the raw event, your processing result, and any errors.
  6. Roll endpoint secrets periodically. Rotate your webhook signing secrets on a regular schedule to limit exposure if a secret is compromised.

Subscription and Recurring Payments

Recurring billing adds complexity beyond one-time payments. You must handle trial periods, plan upgrades and downgrades, proration, dunning (failed payment retry), and cancellation flows.

Key Concepts

Payment Methods on File: When a customer subscribes, you store a reference to their payment method (not the actual card number) for future charges. The gateway handles secure storage; you store only a token.

Dunning Management: When a recurring payment fails (expired card, insufficient funds), you need a strategy for retrying. Most gateways support configurable retry schedules. Best practice is to combine automated retries with customer notification emails that include a link to update their payment method.

Proration: When a customer changes plans mid-cycle, you need to calculate the credit for unused time on the old plan and the charge for the new plan. Most gateways handle this automatically, but you should verify the calculations match your pricing expectations.

Subscription Lifecycle Events: Track the full lifecycle: trial start, trial end, first payment, renewal, upgrade, downgrade, pause, resume, cancellation, and expiration. Each event may require updates to your application's access controls, notification to the customer, and financial record-keeping.

Going Live Checklist

Before accepting real payments, verify every item on this list:

Security

  • HTTPS enforced on all pages (not just checkout)
  • Webhook signature verification implemented and tested
  • API keys stored in environment variables, never in code
  • PCI SAQ completed and filed with your acquiring bank
  • Content Security Policy headers include gateway script domains
  • No card data in server logs, error tracking, or analytics

Functionality

  • Successful payment flow tested with live credentials (small real charge)
  • Decline handling tested and user-friendly error messages displayed
  • Refund flow tested end-to-end
  • Webhook handling verified for all subscribed events
  • Idempotency keys implemented to prevent duplicate charges
  • Currency and locale handling verified for target markets

Operations

  • Monitoring and alerting configured for payment failures
  • On-call procedure defined for payment outages
  • Reconciliation process tested between gateway and accounting system
  • Dispute/chargeback response process documented
  • Subscription dunning policy configured and tested

Compliance

  • Terms of service and privacy policy updated for payment processing
  • Refund policy clearly displayed before checkout
  • Receipt/confirmation emails include required transaction details
  • Tax collection configured for applicable jurisdictions

Frequently Asked Questions

Should I use Stripe or Square for my online store?

It depends on your business model. Stripe is purpose-built for online payments and offers the most flexible API for custom integrations, subscriptions, marketplaces, and complex billing logic. Square is strongest when you need both online and in-person payment processing from a single platform---its point-of-sale hardware and software are tightly integrated with its online payment tools. If you sell exclusively online and need maximum customization, Stripe is typically the better choice. If you have physical retail locations alongside your online store, Square's unified ecosystem is compelling.

What PCI compliance level do I need?

For most online businesses processing fewer than 6 million transactions annually, you are a Level 2, 3, or 4 merchant and can self-assess using the appropriate SAQ. If you use hosted checkout (like Stripe Checkout), you qualify for SAQ A, which has the fewest requirements. If you use embedded payment forms, you likely need SAQ A-EP. If you handle raw card data on your server, you need the full SAQ D. The simplest path to compliance is choosing an integration approach that keeps card data off your servers entirely.

How do I handle failed payments without losing customers?

Implement a dunning strategy that combines automated retries with proactive customer communication. Configure your gateway to retry failed payments on an escalating schedule (for example, 1 day, 3 days, 5 days after failure). Send a friendly notification email after the first failure that includes a direct link to update their payment method. Display an in-app banner when their payment method needs attention. Only cancel the subscription after all retry attempts are exhausted and the customer has had adequate notice---typically 14 to 21 days from the first failure.

Can I switch payment gateways without disrupting existing customers?

Yes, but it requires careful planning. The biggest challenge is migrating stored payment methods. Some gateways support payment method migration tools (Stripe offers a card migration program for qualifying businesses). For subscriptions, you will need to re-collect payment details from existing subscribers unless your current and new gateways support token migration. Plan for a transition period where both gateways are active: new customers use the new gateway while existing subscriptions continue on the old one until they naturally renew or update their payment method.

What is the cost of building a payment integration?

The cost varies dramatically based on complexity. A basic Stripe Checkout integration (hosted page, one-time payments) can be built by an experienced developer in a few hours. An embedded payment form with subscription management, multi-currency support, and webhook handling typically takes 2 to 4 weeks of development time. A full multi-gateway architecture with intelligent routing, comprehensive dunning, and custom reporting can take 2 to 3 months. The ongoing maintenance cost is equally important---plan for 10 to 20 percent of the initial development cost annually for gateway API updates, new payment method support, and compliance changes.

Getting Started with Payment Integration

Payment gateway integration is one of those areas where getting it right from the start saves enormous time and cost down the road. The wrong architectural decision---choosing API-direct when embedded would suffice, or skipping webhook handling to save time---creates technical debt that compounds with every transaction.

If you are building a new payment integration or re-architecting an existing one, our payment integration team can help you choose the right approach, build the integration, and ensure it meets PCI compliance requirements. We also offer systems integration services that connect your payment platform with your accounting, CRM, inventory, and fulfillment systems into a unified workflow.

Sources

payment gatewaystripesquarepayment integrationecommercepci compliance

Have a Project in Mind?

We build custom software, SaaS products, and web applications. Let's talk about what you need.

Get in Touch