php

Paystack Payment Integration with AJAX and PHP

When integrating a secure and efficient payment gateway into your web application, Paystack is a popular choice for developers working in Africa. We’ve written a guide will walk you through integrating Paystack using AJAX and PHP, enabling seamless payment processing and real-time feedback for your users.

Step 1: Set Up a Paystack Account

To get started with Paystack payment integration with AJAX and PHP, you need an account. Follow these steps:

  1. Go to Paystack’s website and create an account.
  2. Verify your account and complete the required setup process.
  3. Navigate to the Settings > API Keys & Webhooks section to access your public and secret keys. You will use these keys for integration.

Step 2: Create a Payment Page

You’ll need a frontend form where users can initiate payments. Here’s a basic HTML form:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Paystack Integration</title>
    <script src="https://js.paystack.co/v1/inline.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <h2>Paystack Payment Integration</h2>
    <form id="paymentForm">
        <label for="email">Email:</label>
        <input type="email" id="email" required><br><br>

        <label for="amount">Amount (in Naira):</label>
        <input type="number" id="amount" required><br><br>

        <button type="button" >

Step 3: Backend Payment Verification with PHP

The callback in the above script sends the payment reference to a PHP backend script for verification. Below is the verify-payment.php script:

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $reference = $_POST['reference']; // Get the transaction reference

    if (!$reference) {
        echo json_encode(['status' => false, 'message' => 'No reference supplied']);
        exit;
    }

    $url = 'https://api.paystack.co/transaction/verify/' . $reference;

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer your-secret-key-here' // Replace with your Paystack secret key
    ]);

    $response = curl_exec($ch);
    curl_close($ch);

    $result = json_decode($response, true);

    if ($result['status'] && $result['data']['status'] === 'success') {
        // Payment was successful
        echo json_encode([
            'status' => true,
            'message' => 'Payment verified successfully',
            'reference' => $reference
        ]);
    } else {
        // Payment verification failed
        echo json_encode([
            'status' => false,
            'message' => 'Payment verification failed',
            'reference' => $reference
        ]);
    }
}
?>

Step 4: Testing Your Integration

  1. Use the test keys provided by Paystack to test your integration.
  2. Navigate to the Paystack documentation and use the test card details for simulated payments.
  3. Ensure that your verification script handles errors appropriately.
  4. Once testing is complete, replace the test keys with live keys.

See also FlutterWave Payment Integration With PHP

See also Remita Payment Integration

Best Practices

  1. Secure Your Keys:
    • Never expose your secret key on the frontend.
    • Use environment variables to store your keys securely.
  2. Validate Inputs:
    • Ensure that the email and amount fields are properly validated before initiating payments.
  3. Handle Errors Gracefully:
    • Inform users if something goes wrong during payment or verification.
    • Provide clear steps for retrying the payment.
  4. Logging:
    • Log all payment references and verification responses for auditing purposes.

Conclusion

Paystack payment integration with AJAX and PHP can provide a seamless payment experience for your users. By following this guide, you’ve set up a secure and efficient payment flow with real-time feedback. Remember to test your implementation thoroughly and follow best practices to ensure a smooth experience for your users.

Recent Posts

Why parseInt(’09’) Returns 0

If you've ever encountered the puzzling behavior of parseInt('09') returning 0 in JavaScript, you're not…

3 days ago

Event Bubbling and Capturing: Why Your Click Listener Fires Twice (And How to Fix It)

If you’ve ever built an interactive web application, you may have encountered a puzzling issue:…

1 week ago

Practical Array Methods for Everyday Coding

Arrays are the backbone of programming, used in nearly every application. Whether you're manipulating data,…

2 weeks ago

What the Heck Is the Event Loop? (Explained With Pizza Shop Analogies)

If you've ever tried to learn JavaScript, you’ve probably heard about the "Event Loop"—that mysterious,…

2 weeks ago

Why [] === [] Returns false in JavaScript (And How to Properly Compare Arrays & Objects)

JavaScript can sometimes behave in unexpected ways, especially when comparing arrays and objects. If you've…

2 weeks ago

Recursion for Beginners

Recursion is a programming technique where a function calls itself to solve smaller instances of…

2 weeks ago