How do you integrate Slim Framework with a payment gateway?

How do you integrate Slim Framework with a payment gateway?

To integrate the Slim Framework with a payment gateway, follow these minimal steps:

1. Choose a Payment Gateway:

Select a payment gateway, such as Stripe, PayPal, or Authorize.Net. This example will use Stripe.

2. Install the Stripe PHP SDK:

Use Composer to install the Stripe PHP SDK:

Example

composer require stripe/stripe-php

3. Set Up Stripe Configuration:

Create a configuration file to store your Stripe credentials (API keys):

Example

<?php
// config.php
return [
    'stripe' => [
        'secret_key' => 'your_secret_key',
        'publishable_key' => 'your_publishable_key',
    ],
];
?>

4. Create Routes for Payment Processing:

Define routes in your Slim application to handle payment requests and webhooks.

Payment Form Route:

Example

<?php
$app->get('/payment', function ($request, $response) {
    // Render a payment form view with the publishable key
    return $this->view->render($response, 'payment.twig', [
        'publishable_key' => $this->get('settings')['stripe']['publishable_key'],
    ]);
});
?>

Process Payment Route:

Example

<?php
$app->post('/charge', function ($request, $response) {
    $data = $request->getParsedBody();
    \Stripe\Stripe::setApiKey($this->get('settings')['stripe']['secret_key']);

    try {
        // Create a charge
        $charge = \Stripe\Charge::create([
            'amount' => $data['amount'], // Amount in cents
            'currency' => 'usd',
            'source' => $data['stripeToken'], // Obtained with Stripe.js
            'description' => 'Payment for Order',
        ]);

        return $response->withJson(['status' => 'success', 'charge' => $charge]);
    } catch (\Stripe\Exception\CardException $e) {
        return $response->withJson(['status' => 'error', 'message' => $e->getMessage()], 400);
    }
});
?>

5. Create a Payment Form:

Create a simple HTML form for the payment. Use Stripe.js to handle the payment securely:

Example

<?php
<form action="/charge" method="post" id="payment-form">
    <input type="text" name="amount" placeholder="Amount in cents" required>
    <button id="submit">Pay</button>
    <div id="card-element"></div>
    <div id="card-errors" role="alert"></div>
</form>

<script src="https://js.stripe.com/v3/"></script>
<script>
    var stripe = Stripe('your_publishable_key');
    var elements = stripe.elements();
    var cardElement = elements.create('card');
    cardElement.mount('#card-element');

    var form = document.getElementById('payment-form');
    form.addEventListener('submit', function(event) {
        event.preventDefault();
        stripe.createToken(cardElement).then(function(result) {
            if (result.error) {
                document.getElementById('card-errors').textContent = result.error.message;
            } else {
                var hiddenInput = document.createElement('input');
                hiddenInput.setAttribute('type', 'hidden');
                hiddenInput.setAttribute('name', 'stripeToken');
                hiddenInput.setAttribute('value', result.token.id);
                form.appendChild(hiddenInput);
                form.submit();
            }
        });
    });
</script>
?>

6. Handle Webhooks (Optional):

If your payment gateway supports webhooks (like Stripe), set up a route to handle them:

Example

<?php
$app->post('/webhook', function ($request, $response) {
    $payload = $request->getBody()->getContents();
    $sigHeader = $request->getHeaderLine('Stripe-Signature');
    
    try {
        $event = \Stripe\Webhook::constructEvent($payload, $sigHeader, 'your_webhook_secret');

        // Handle the event
        switch ($event->type) {
            case 'payment_intent.succeeded':
                // Payment succeeded
                break;
            // Handle other event types
        }

        return $response->withStatus(200);
    } catch (\UnexpectedValueException $e) {
        return $response->withStatus(400);
    } catch (\Stripe\Exception\SignatureVerificationException $e) {
        return $response->withStatus(400);
    }
});
?>

7. Test the Integration:

  • Run your Slim application.
  • Access the /payment route to display the payment form.
  • Submit the form with test card details to ensure everything works as expected.

By following these steps, you can integrate the Slim Framework with a payment gateway like Stripe to handle payments securely and efficiently.

Related Questions & Topics