Learning how to integrate PayPal in PHP gives any custom website a trusted way to accept payments without building card handling from scratch. PayPal’s current approach pairs the JavaScript SDK on the front end with the PayPal Checkout Orders API on your server. Your PHP code creates an order, the buyer approves it in a secure PayPal window, and your server captures the payment and records the result. Card data never touches your server, which keeps your compliance burden low and your buyers’ details safe.
This guide walks through the full flow in order: getting sandbox credentials, creating an order in PHP, adding the checkout buttons, capturing the payment safely, and verifying every transaction before you deliver goods. You will also learn how to handle errors, webhooks, and the security checks that separate a tutorial demo from a production-ready integration. A basic knowledge of PHP and HTML is assumed, but every step is explained so careful beginners can follow along.
How the PayPal PHP Integration Works
Before writing any code, it helps to understand the four moving parts and how they talk to each other:
- Your PHP server creates an order through the PayPal Checkout Orders API, using prices from your own database.
- The PayPal JavaScript SDK on your checkout page renders the payment buttons and opens the approval flow.
- The buyer logs in to PayPal (or pays by card as a guest, where available) and approves the payment.
- Your PHP server captures the approved order, checks the amount matches your records, and only then marks the order as paid.
The single most important principle is that prices live on your server, never in the browser. If the amount comes from JavaScript or a hidden form field, anyone can change it before paying. The browser’s only job is to hand over an order ID and report what the buyer did. Every decision about money happens in PHP, where the buyer cannot interfere.
A second principle is worth stating early: approval is not payment. A buyer approving an order means they agreed to pay; the money only moves when your server captures the order and PayPal confirms the capture completed. Skipping the capture step is the most common beginner mistake, and it leads to orders marked paid that were never actually charged.
Step 1: Set Up Your PayPal Developer Account and Credentials
Start in the PayPal Developer Dashboard, where one login gives you both a sandbox for testing and live credentials for real payments. Create an app under your account to obtain a client ID and secret for each environment. The sandbox includes fake buyer and seller accounts with pretend money, so you can test complete purchases, refunds and failures without moving a cent. Keep the live secret out of your code repository and store it in environment variables or a configuration file outside your web root.
Structure your PHP project around a small configuration file that returns the right client ID, secret and API base URL depending on the environment. The sandbox API lives at api-m.sandbox.paypal.com, while live payments use api-m.paypal.com. Switching environments should require changing configuration only, never editing payment logic. Also decide how your application will obtain an OAuth access token, because every API call needs one — tokens are cached briefly rather than requested for every single operation.
When you create your developer app, note which environment each credential belongs to. Sandbox credentials only work against the sandbox API, and live credentials only against the live API. Mixing them up is a frequent source of “authentication failed” errors that look mysterious until you spot the mismatch. Label your configuration clearly, for example with separate PAYPAL_CLIENT_ID and PAYPAL_SECRET values per environment, and load the right pair based on a single environment flag.
- Create a developer app to get sandbox and live credentials
- Test everything with sandbox buyer and seller accounts first
- Store secrets in environment variables, never in Git
- Use separate API base URLs for sandbox and live modes
- Cache the OAuth access token instead of requesting it constantly
Step 2: Create an Order on the Server With PHP
When a buyer clicks checkout, your JavaScript calls a PHP endpoint such as create-order.php. That endpoint looks up the actual cart or product price from your database, requests an access token, and posts an order to the Orders API with the amount, currency and a clear description. PayPal returns an order ID, which your endpoint passes back to the browser to open the approval flow.
Write this endpoint defensively. Validate that the cart is not empty, format amounts as strings with two decimal places, and use a single currency consistently. Use PHP’s cURL functions with proper timeouts and check every API response for HTTP errors before continuing. Log the PayPal order ID against your internal order record immediately, because that link between the two systems is what lets you reconcile payments, investigate disputes, and confirm exactly what each buyer paid for.

A few details in this step deserve extra care. First, never trust an amount sent from the browser — always re-read the price from your database or product catalogue, keyed by a product ID rather than a price the client supplies. Second, set sensible cURL timeouts (around 10 seconds for connect, 30 for the whole request) so a slow PayPal response does not hang your checkout page indefinitely. Third, return a clean JSON error to the browser when order creation fails, with a friendly message for the buyer and the full error logged server-side for you. And if your checkout runs on WordPress with WooCommerce rather than custom PHP, the hosting underneath still matters — see our guide to the best WordPress hosting for a WooCommerce store before you build on a host that cannot handle payment traffic reliably.
- Create orders server-side using prices from your database
- Validate the cart and format amounts with two decimals
- Request an OAuth token and call the Orders API with cURL
- Handle API errors and timeouts gracefully
- Save the PayPal order ID on your internal order record
Step 3: Add the Checkout Buttons and Approval Flow
With order creation working, add the PayPal JavaScript SDK to your checkout page using your client ID and intended currency. The SDK renders the familiar PayPal and card buttons inside containers you place in your HTML. Its createOrder callback calls your PHP endpoint and returns the order ID, the buyer then logs in and approves inside PayPal’s secure window, and the onApprove callback calls your capture endpoint. This pattern keeps buyers on your site while PayPal handles authentication and payment details.
Design the surrounding experience carefully. Show the order total clearly before the buttons, disable them while a payment is processing to prevent double clicks, and prepare success and failure messages in advance. The SDK also supports funding options such as Pay Later where available, which appear automatically for eligible buyers. Test the flow on mobile as well as desktop, because the approval experience differs and most buyers will complete purchases on their phones.

One practical detail: load the SDK script with your client ID and currency as parameters, and only once per page. Loading it twice can cause buttons to render inconsistently. If your checkout page also has a contact or enquiry form, keep the two flows separate — the payment buttons should only appear once the order total is final. After a successful payment, send the buyer to a thank-you page; if you use Contact Form 7 anywhere on the site, our guide on how to redirect Contact Form 7 to a thank you page shows the same post-submit redirect pattern applied to forms.
- Load the JavaScript SDK with your client ID and currency
- Wire createOrder to your PHP order endpoint
- Call the capture endpoint from the onApprove callback
- Disable buttons during processing to prevent duplicates
- Show clear totals, success, and failure states to buyers
Step 4: Capture the Payment and Verify the Result
Approval is not payment. After the buyer approves, your capture endpoint must call the Orders API capture endpoint with the order ID, and only a response with a completed status means money has actually moved. Read the captured amount and currency from PayPal’s response and compare them against your internal order total. If they differ, flag the order for manual review instead of shipping automatically. This verification step protects you against tampered requests and honest integration mistakes alike.
Once verified, update your database in one careful step: mark the order paid, store the capture ID, and trigger confirmation emails and fulfilment. Make the endpoint idempotent so a repeated call cannot double-capture or double-ship; check the order’s current status before acting. Return a clean success response so the front end can redirect the buyer to a thank-you page. Log capture responses securely, redacting secrets, so support questions weeks later can be answered with facts rather than guesswork.
Idempotency deserves a moment because it is easy to overlook. Browsers retry, buyers double-click, and networks drop responses. If your capture endpoint runs twice on the same order, the second run should see “already paid” and return the stored result instead of capturing again. The simplest way to achieve this is a status check at the top of the endpoint: if the order is already marked paid, return success immediately without calling PayPal again. Combined with a unique constraint on the capture ID in your database, this makes duplicate charges practically impossible.
- Capture the order server-side after buyer approval
- Confirm the status is completed before fulfilling
- Compare captured amount and currency with your records
- Store the capture ID and mark the order paid once
- Make capture handling idempotent to avoid duplicates
Step 5: Webhooks, Error Handling and Going Live Safely
Client-side callbacks can be interrupted by closed browsers and dropped connections, so add webhooks for reliability. Subscribe to payment capture completed and refund events in the developer dashboard and point them at a PHP listener endpoint. Verify each webhook’s signature before trusting it, then update orders from these events as a safety net alongside your capture flow. This combination means a payment is recorded correctly even if the buyer never returns to your thank-you page.
Your webhook listener should be simple and defensive: accept the POST, verify the signature using PayPal’s verification method, check the event type, and update the matching order by capture ID. Return a 200 response quickly — PayPal retries failed deliveries, so a slow listener can cause duplicate events, which your idempotency checks should already handle. Log every webhook you receive, at least in the early weeks, so you can trace any order whose status looks wrong.
Before going live, run the full sandbox test matrix: successful payment, cancelled checkout, insufficient funds, refund, and a mismatched amount. Switch the configuration to live credentials, make one small real purchase yourself, and refund it. Confirm your site uses HTTPS everywhere, your secrets are production values, and error pages never expose API messages to buyers. If your site throws server errors during this testing, our guide on how to fix the WordPress 500 internal server error covers the most common causes. Finally, document the flow for whoever maintains the site next, including where credentials live and how to test after future changes.

- Add verified webhooks for capture and refund events
- Test success, cancellation, failure, and refund cases
- Switch to live credentials and run a real small purchase
- Serve checkout over HTTPS and hide raw API errors
- Document credentials, endpoints, and testing steps
Frequently Asked Questions
Do I need a PayPal business account to accept payments in PHP?
For live payments, yes, a PayPal business account is required to receive funds commercially and access full selling tools. You can build and test the entire integration first using a free developer account and sandbox credentials before upgrading or linking the business account.
Is the old PayPal PHP SDK still recommended?
PayPal’s older SDKs are deprecated, and current integrations should call the REST APIs directly or use the JavaScript SDK plus server-side Orders API calls, as this guide describes. Direct cURL calls from PHP are simple, supported, and avoid depending on unmaintained libraries.
How do I handle refunds in a PHP integration?
Refunds are issued through the Payments API using the capture ID stored when the payment completed. Build an admin action that calls the refund endpoint, listens for the refund webhook, and updates the order status only after PayPal confirms the refund succeeded.
Can buyers pay by card without a PayPal account?
In many countries, yes. The JavaScript SDK can present a card option powered by PayPal, and eligible buyers can check out as guests. Availability varies by country, account type and buyer history, so test the buttons from your target market before promising card-only checkout.
How long does an OAuth access token last?
PayPal access tokens are short-lived, typically valid for a matter of hours. Request one when your cached token expires rather than on every API call, and always handle a 401 response by fetching a fresh token and retrying once.
Putting It All Together
Integrating PayPal in PHP comes down to a clear sequence: create the order on your server, let the buyer approve it through the JavaScript SDK, capture it server-side, verify the amount, and back the whole flow up with webhooks. Prices stay in your database, secrets stay out of your code, and no order is treated as paid until PayPal says the capture completed.
Build it in the sandbox first, test every failure case, then switch to live credentials and make one small real purchase before you open checkout to the public. With that routine in place, your PHP site can take payments reliably — and you will have the logs and checks to prove every transaction that passes through it.

