Payment gateway integration PHP projects follow one reliable shape: create your own order first, send the customer to the gateway's hosted checkout, treat the browser return as informational, and confirm payment only through a signature-verified, idempotent server-to-server webhook. Get that sequence right and gateway-specific details become configuration.
Parameter names, endpoints and signature formats differ between providers such as Stripe, PayPal or Razorpay. Use each gateway's official documentation for exact fields, test on a current PHP version, and never put real keys in code samples, repositories or tickets.
Payment gateway integration PHP: the flow end to end
Most hosted-gateway integrations look like this:
- The customer submits the cart; your server creates an order with status pending.
- Your server asks the gateway to create a payment session or order, passing the amount, currency, your order reference and return URLs.
- The customer is redirected to the gateway's page (or an embedded hosted form) and pays.
- The gateway sends the browser back to your success or cancel URL.
- Independently, the gateway sends a webhook to your server announcing the result.
- Your server verifies that webhook and marks the order paid, then triggers fulfilment.
The key insight is that steps 4 and 5 are different channels with different trust levels. The browser return can be skipped (the user closes the tab), faked (anyone can visit your success URL) or repeated. The webhook is your source of truth.
Create the order first
Create the order in your database before talking to the gateway. This gives you a stable internal ID to send as a reference and to match against later.
- Calculate the amount on the server from your own price data. Never trust an amount posted from the browser.
- Store amount, currency and a status such as pending, paid, failed or refunded.
- Store the gateway's session or payment ID against the order as soon as you receive it.
- Use integer minor units (for example cents) or a decimal type rather than floats to avoid rounding errors.
- Keep an unchanging history of status changes for support and reconciliation.
If you are working through the planning side first, what to plan for when adding Stripe or PayPal covers requirements and architecture; this guide stays at code level.
Redirect or hosted checkout
Hosted checkout pages and gateway-provided card fields keep card numbers off your servers, which greatly reduces your compliance scope compared with handling card data yourself. For most business applications this is the right choice. Check the gateway's guidance and your own obligations; payment-card rules change and you should confirm them with your provider or a qualified adviser.
When creating the session, pass both a success and a cancel URL, include your order reference in metadata so the webhook can find the order, and set an expiry if the gateway supports it. On the success page, show a "we are confirming your payment" message that reads the order status from your database. Do not mark the order paid there. If the status is still pending, poll or refresh gently; webhooks usually arrive within seconds but not instantly.
Verify callbacks and signatures
A webhook URL is public, so anyone can post to it. Verification proves the request came from the gateway and was not altered. Most providers sign the raw request body with a shared secret and put the signature in a header; some also include a timestamp to limit replay.
$payload = file_get_contents('php://input');$signature = $_SERVER['HTTP_X_SIGNATURE'] ?? '';$expected = hash_hmac('sha256', $payload, $webhookSecret);if (!hash_equals($expected, $signature)) { http_response_code(400); exit;}// then json_decode($payload, true) and processThat sample is generic; the header name, algorithm and what exactly is signed vary, so follow your gateway's documentation or its official PHP library. Points that matter in every case:
- Verify against the raw body before any parsing or re-encoding.
- Compare with
hash_equalsto avoid timing leaks. - Keep the secret in environment configuration, not in source code.
- Respond with a client error on failure, and log the attempt without logging secrets.
- Where a timestamp is supplied, reject requests outside a short tolerance.
Even a valid signature does not replace checking the data: confirm that the amount and currency match your order. The wider security picture is in our PHP security checklist based on OWASP.
Idempotent webhook handling
Gateways deliver webhooks at least once. That means duplicates, retries after timeouts and out-of-order events are normal. Idempotency means processing the same event twice has the same result as processing it once.
- Store each event ID in a table with a unique constraint. If the insert fails because the ID exists, return success without repeating the work.
- Make state changes conditional: update the order to paid only if it is currently pending, in a single statement or a transaction.
- Do the minimum inside the request: record the event, update status, queue slow work (emails, fulfilment) for a background worker, and return a success status quickly.
- Do not assume ordering. A refund event could arrive before you finish handling the payment event; design status transitions to tolerate that.
- Return an error status only when you want the gateway to retry.
Refunds and failures
Plan for the unhappy paths from the start. Decline, expired session, abandoned payment, partial payment, dispute and refund are all different states with different business consequences.
- Initiate refunds server-side through the gateway API, record the refund against the order and wait for the confirming webhook before showing it as completed.
- Support partial refunds by tracking the refunded amount, not only a flag.
- Show customers a clear failed-payment message with a way to retry without creating a second order.
- Expire stale pending orders with a scheduled job, releasing reserved stock.
- Build a simple admin view showing order status next to gateway status to help reconciliation.
Test mode to live checklist
Use the gateway's sandbox and its test card or test account scenarios to exercise failures as well as success: declined payment, insufficient funds, authentication challenge, cancelled checkout, delayed confirmation and duplicate webhook delivery. Many providers let you resend events or use a command-line tool or dashboard to replay them.
Before going live:
- Swap test keys for live keys through configuration, and confirm none are committed to version control.
- Register the live webhook endpoint with its own secret.
- Confirm HTTPS on all callback URLs.
- Run one real low-value transaction and refund it.
- Check logs do not contain card data or secrets.
- Set up alerts for failed webhooks and a growing pending-order backlog.
- Document the reconciliation process for whoever handles finance.
Putting it together
Order first, hosted checkout, signed webhook, idempotent processing: that sequence holds across gateways. If you also sell subscriptions, see setting up subscription billing, and for a US-oriented view of delivery see our software development page for the USA.
Frequently asked questions
Why verify a gateway callback server-side?
Your callback URL is public, so anyone can send a forged request claiming a payment succeeded. Verifying the signature on the raw body with your secret, and checking amount and currency against your own order, proves the message is genuine and unmodified. The customer's browser return alone is never proof of payment.
What is webhook idempotency?
It means handling the same event twice gives the same result as handling it once. Gateways retry deliveries, so duplicates happen. Store each event ID with a unique constraint and make status changes conditional, such as updating an order to paid only if it is still pending.
How do I test failure cases?
Use the gateway's sandbox and its test scenarios for declined cards, authentication challenges, cancelled checkouts and delayed confirmations. Replay or resend webhook events to confirm duplicate handling, and test expired sessions and partial refunds. Keep a written test list so every release repeats the same scenarios.