Integrating Payment Gateways with PHP: A Complete Guide

WebandSEOadvisor
4 min readAug 19, 2024

--

Photo by Sergey Zolkin on Unsplash

Integrating payment gateways into your PHP application is essential for enabling e-commerce functionality, such as accepting payments for products, services, or subscriptions. Payment gateways handle the processing of transactions, ensuring that they are secure and efficient. This guide will walk you through the process of integrating popular payment gateways like Stripe and PayPal into your PHP applications.

Prerequisites

Before starting, ensure you have:

  • Basic knowledge of PHP and web development.
  • Access to a web server with PHP installed.
  • Accounts with the payment gateways you wish to integrate (e.g., Stripe, PayPal).

Step 1: Choose a Payment Gateway

The first step is to choose a payment gateway that suits your needs. Popular options include:

  • Stripe: Known for its simplicity and powerful API.
  • PayPal: Widely used, especially for international transactions.
  • Square: Suitable for both online and offline payments.

For this guide, we’ll focus on integrating Stripe and PayPal.

Step 2: Setting Up Stripe

1. Create a Stripe Account

  • Sign up for a Stripe account at stripe.com.
  • After registering, you’ll gain access to the Stripe Dashboard, where you can find your API keys.

2. Install the Stripe PHP SDK

To interact with Stripe, you’ll need to install the Stripe PHP SDK using Composer:

composer require stripe/stripe-php

Process Payments with Stripe

Create a Payment Form:

  1. Create a checkout.php file that includes a form for users to enter their payment details:
<form action="charge.php" method="post" id="payment-form">
<div class="form-row">
<label for="card-element">
Credit or debit card
</label>
<div id="card-element">
<!-- A Stripe Element will be inserted here. -->
</div>

<!-- Used to display form errors. -->
<div id="card-errors" role="alert"></div>
</div>

<button type="submit">Submit Payment</button>
</form>
  • You’ll also need to include Stripe.js and initialize the card element. This code should be included in the same checkout.php file:
<script src="https://js.stripe.com/v3/"></script>
<script>
var stripe = Stripe('YOUR_PUBLIC_STRIPE_KEY');
var elements = stripe.elements();

var card = elements.create('card');
card.mount('#card-element');

card.addEventListener('change', function(event) {
var displayError = document.getElementById('card-errors');
if (event.error) {
displayError.textContent = event.error.message;
} else {
displayError.textContent = '';
}
});

var form = document.getElementById('payment-form');
form.addEventListener('submit', function(event) {
event.preventDefault();

stripe.createToken(card).then(function(result) {
if (result.error) {
var errorElement = document.getElementById('card-errors');
errorElement.textContent = result.error.message;
} else {
stripeTokenHandler(result.token);
}
});
});

function stripeTokenHandler(token) {
var form = document.getElementById('payment-form');
var hiddenInput = document.createElement('input');
hiddenInput.setAttribute('type', 'hidden');
hiddenInput.setAttribute('name', 'stripeToken');
hiddenInput.setAttribute('value', token.id);
form.appendChild(hiddenInput);

form.submit();
}
</script>

2. Handle the Payment on the Server:

Create a charge.php file to process the payment on the server side:

<?php
require 'vendor/autoload.php';

\Stripe\Stripe::setApiKey('YOUR_SECRET_STRIPE_KEY');

$token = $_POST['stripeToken'];
$charge = \Stripe\Charge::create([
'amount' => 5000, // Amount in cents
'currency' => 'usd',
'description' => 'Example charge',
'source' => $token,
]);

echo 'Payment Successful!';
?>
  • eplace YOUR_SECRET_STRIPE_KEY with your actual secret key from the Stripe dashboard.

4. Test the Integration

  • Use Stripe’s test mode to simulate payments using test card numbers provided by Stripe.
  • After testing, switch to live mode by replacing the test keys with live keys.

Related article PHP Solutions for Managing WordPress SEO Plugins https://medium.com/@wwwebadvisor/php-solutions-for-managing-wordpress-seo-plugins-optimizing-performance-and-integration-2fcdd08fdd82

Step 3: Setting Up PayPal

1. Create a PayPal Account

  • Sign up for a PayPal Developer account at developer.paypal.com.
  • After registering, create a sandbox account for testing and obtain your API credentials.

2. Install the PayPal PHP SDK

To integrate PayPal, install the PayPal PHP SDK via Composer:

composer require paypal/rest-api-sdk-php

Process Payments with PayPal

  1. Create a Payment Request:

Create a paypal_pay.php file to handle the payment creation:

<?php
require 'vendor/autoload.php';

$apiContext = new \PayPal\Rest\ApiContext(
new \PayPal\Auth\OAuthTokenCredential(
'YOUR_CLIENT_ID',
'YOUR_CLIENT_SECRET'
)
);

$payer = new \PayPal\Api\Payer();
$payer->setPaymentMethod('paypal');

$amount = new \PayPal\Api\Amount();
$amount->setTotal('50.00');
$amount->setCurrency('USD');

$transaction = new \PayPal\Api\Transaction();
$transaction->setAmount($amount);
$transaction->setDescription('Payment description');

$redirectUrls = new \PayPal\Api\RedirectUrls();
$redirectUrls->setReturnUrl('http://localhost/paypal_success.php')
->setCancelUrl('http://localhost/paypal_cancel.php');

$payment = new \PayPal\Api\Payment();
$payment->setIntent('sale')
->setPayer($payer)
->setTransactions([$transaction])
->setRedirectUrls($redirectUrls);

try {
$payment->create($apiContext);
header('Location: ' . $payment->getApprovalLink());
} catch (Exception $ex) {
die($ex);
}
?>
  • Replace YOUR_CLIENT_ID and YOUR_CLIENT_SECRET with your actual PayPal API credentials.

2. Handle the Payment Success:

  • Create a paypal_success.php file to handle the successful payment:
<?php
require 'vendor/autoload.php';

$apiContext = new \PayPal\Rest\ApiContext(
new \PayPal\Auth\OAuthTokenCredential(
'YOUR_CLIENT_ID',
'YOUR_CLIENT_SECRET'
)
);

$paymentId = $_GET['paymentId'];
$payment = \PayPal\Api\Payment::get($paymentId, $apiContext);

$execution = new \PayPal\Api\PaymentExecution();
$execution->setPayerId($_GET['PayerID']);

try {
$result = $payment->execute($execution, $apiContext);
echo 'Payment Successful!';
} catch (Exception $ex) {
die($ex);
}
?>
  • The paymentId and PayerID are passed via the query string when PayPal redirects back to your site after the user approves the payment.

3. Handle the Payment Cancellation:

  • Create a paypal_cancel.php file to handle the case where the user cancels the payment:
<?php
echo 'Payment Cancelled!';
?>

4. Test the Integration

  • Use PayPal’s sandbox environment to test your integration.
  • After testing, replace the sandbox credentials with live credentials for production.

Step 4: Securing the Payment Process

To ensure security:

  • Always use HTTPS for all payment-related communications.
  • Validate all inputs and sanitize user data.
  • Implement proper error handling to manage exceptions.

Step 5: Going Live

After thoroughly testing your integration:

  • Switch to live mode by updating API keys and URLs.
  • Monitor transactions closely to ensure everything is functioning correctly.

Conclusion

Integrating payment gateways like Stripe and PayPal into your PHP application enables you to accept payments securely and efficiently. By following this guide, you’ve learned how to set up both Stripe and PayPal, process payments, and handle success and cancellation scenarios. This integration is crucial for any e-commerce application, providing users with a seamless and secure payment experience.

--

--