McTaba Labs logo
Software EngineeringThe WhiteboardProjectsEventsMasterclassesWebinarsLearn
Book Call

500+ developers already in the community

Get answers, find accountability partners, and stay ahead

Join Discord →
McTaba Labs logo

Educating 1 million students in tech by 2030.

Programs

  • HighSchool Graduates Launchpad
  • AI & Business Automation
  • Corporate Training
  • McTaba Story & Mission
  • Full-Stack Curriculum
  • Course Pricing & Plans
  • Frequently Asked Questions

Resources

  • Join Discord Community
  • Tech Events in Nairobi
  • Masterclasses
  • Free Resources
  • Learn
  • Campus
  • Africa Tech Talent Report
  • Partner With Us
  • Start a Project
  • Our Work

Contact Us

  • 124 Manyani East Road, Lavington, Nairobi
  • +254727795603
  • Book a Discovery Call

Office Hours:

Mon-Fri: 9am - 2pm EAT

Sat: 10am - 12pm EAT

© 2027 McTaba Labs - A product of Edtech Industries. All rights reserved.

Privacy PolicyTerms of ServiceRefund Policy
  1. Learn
  2. Paystack for African Developers
  3. Accept Payments with Paystack in Symfony
Bonaventure OgetoBy Bonaventure Ogeto|Updated July 20, 2026

Accept Payments with Paystack in Symfony

To accept Paystack payments in Symfony, inject the HttpClientInterface, create a PaystackService that wraps API calls, and build controllers for initialization and callback handling. Use environment variables for your secret key and verify every transaction server-side.

In this article

  1. 1. Setup
  2. 2. PaystackService
  3. 3. Payment Controller
  4. 4. Service Configuration
  5. 5. Security Checklist
  6. 6. Ship Payments Faster

Setup

Add your Paystack keys to .env:

PAYSTACK_SECRET_KEY=sk_test_xxxxxxxxxxxxxxxxxxxxx

Bind it as a parameter in config/services.yaml:

parameters:
    paystack_secret_key: '%env(PAYSTACK_SECRET_KEY)%'

PaystackService

// src/Service/PaystackService.php
namespace App\Service;

use Symfony\Contracts\HttpClient\HttpClientInterface;

class PaystackService
{
    private HttpClientInterface $client;
    private string $secretKey;

    public function __construct(HttpClientInterface $client, string $paystackSecretKey)
    {
        $this->client = $client;
        $this->secretKey = $paystackSecretKey;
    }

    public function initializeTransaction(string $email, int $amountKobo, string $reference, string $callbackUrl): array
    {
        $response = $this->client->request('POST', 'https://api.paystack.co/transaction/initialize', [
            'headers' => [
                'Authorization' => 'Bearer ' . $this->secretKey,
                'Content-Type' => 'application/json',
            ],
            'json' => [
                'email' => $email,
                'amount' => $amountKobo,
                'reference' => $reference,
                'callback_url' => $callbackUrl,
            ],
        ]);

        return $response->toArray();
    }

    public function verifyTransaction(string $reference): array
    {
        $response = $this->client->request('GET', 'https://api.paystack.co/transaction/verify/' . $reference, [
            'headers' => [
                'Authorization' => 'Bearer ' . $this->secretKey,
            ],
        ]);

        return $response->toArray();
    }
}

Get weekly developer tips

Join 25,000+ developers. Practical guides, job tips, and new content — straight to your inbox.

No spam. Unsubscribe anytime.

Payment Controller

// src/Controller/PaymentController.php
namespace App\Controller;

use App\Service\PaystackService;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Uid\Uuid;

class PaymentController extends AbstractController
{
    #[Route('/pay', methods: ['POST'])]
    public function initialize(Request $request, PaystackService $paystack): Response
    {
        $email = $request->request->get('email');
        $amount = (int) ($request->request->get('amount', 5000) * 100);
        $reference = 'order_' . Uuid::v4()->toRfc4122();

        // TODO: Save order to database

        $result = $paystack->initializeTransaction(
            $email, $amount, $reference,
            $this->generateUrl('payment_callback', [], 0)
        );

        if ($result['status'] ?? false) {
            return $this->redirect($result['data']['authorization_url']);
        }

        return new Response('Failed: ' . ($result['message'] ?? 'Unknown'), 400);
    }

    #[Route('/payment/callback', name: 'payment_callback')]
    public function callback(Request $request, PaystackService $paystack): Response
    {
        $reference = $request->query->get('reference') ?? $request->query->get('trxref');

        if (!$reference) {
            return new Response('Missing reference', 400);
        }

        $result = $paystack->verifyTransaction($reference);

        if (($result['status'] ?? false) && $result['data']['status'] === 'success') {
            // TODO: Verify amount, mark order as paid
            return $this->render('payment/success.html.twig', ['reference' => $reference]);
        }

        return $this->render('payment/failed.html.twig');
    }
}

Service Configuration

# config/services.yaml
services:
    App\Service\PaystackService:
        arguments:
            $paystackSecretKey: '%paystack_secret_key%'

Security Checklist

  1. Validate amounts server-side. Look up prices from your database.
  2. Set up webhooks. See Handle Paystack Webhooks in Symfony.
  3. Use HTTPS. Required for callback and webhook URLs.
  4. Verify every transaction. The redirect alone is not proof of payment.

Ship Payments Faster

This guide is part of the Paystack integration guides by language and framework series.

Sign up for the McTaba newsletter

Key Takeaways

  • ✓Symfony HttpClient provides a clean API for calling the Paystack REST endpoints.
  • ✓Store your Paystack keys in .env and bind them as service parameters.
  • ✓Create a PaystackService that you inject into controllers via autowiring.
  • ✓Amounts are in kobo (NGN), pesewas (GHS), or cents. Convert before sending.
  • ✓Always verify the transaction server-side after the redirect callback.
  • ✓No external packages needed. Symfony HttpClient handles all Paystack API calls.

Frequently Asked Questions

Does Symfony need CSRF exemption for webhooks?
Symfony does not have automatic CSRF protection on all POST routes like Laravel does. If you use the Symfony Form component, CSRF is form-specific. Your webhook route does not need special CSRF handling.
Can I use Guzzle instead of Symfony HttpClient?
Yes, but Symfony HttpClient is built into the framework and integrates better with dependency injection. Guzzle works fine too.
How do I test PaystackService?
Mock the HttpClientInterface in your unit tests. Symfony provides a MockHttpClient for this purpose.

Learn Paystack Integration

KES 2,999

The definitive guide to building payment systems with Paystack — from your first transaction to production-grade payment infrastructure across Africa. 9 modules, 47 lessons. Free preview available.

Start Paystack Course

Not ready? Create Free Account

Keep reading

Paystack Integration Guides by Language and Framework

A complete directory of Paystack integration guides organized by programming language and framework. Each guide covers accepting payments, verifying transactions, handling webhooks, and building subscriptions in your specific stack.

Read more

Accept Payments with Paystack in Svelte and SvelteKit

Accept Paystack payments in SvelteKit using server endpoints for backend logic and Svelte components for the frontend. This guide covers initializing transactions, inline popup checkout, redirect checkout, and verification in a single full-stack SvelteKit project.

Read more

Verify Paystack Payments in Flask

Verify Paystack payments server-side in your Flask application. This guide covers calling the Paystack verify endpoint, validating amounts and currencies, building reusable verification helpers, and preventing double-granting.

Read more

Build Paystack Subscriptions in ASP.NET Core

Implement Paystack recurring billing in ASP.NET Core. This guide covers creating plans, subscribing customers through transaction initialization, handling renewal webhooks with C#, and cancelling subscriptions.

Read more

Reconciling Dedicated Virtual Account Deposits

Dedicated Virtual Accounts (DVAs) let each customer have a permanent bank account number linked to your Paystack integration. When a customer transfers money to their DVA, Paystack notifies you. But matching those deposits to the right customer, handling partial payments, and reconciling against your records requires careful engineering. This guide walks through the reconciliation workflow.

Read more

Paystack Subaccount Settlement Missing

Your subaccount received transactions but the settlement never arrived in their bank account. Here is how to trace the problem from split to settlement to bank.

Read more

Explore related topics

M-Pesa & African Stack

M-Pesa Daraja API tutorials, USSD development, and WhatsApp Business API guides. The African Stack that global bootcamps do not teach.

Learn to Code in Kenya

Everything a Kenyan needs to know before writing their first line of code. Career paths, real costs, hardware requirements, and honest answers about what it takes.

Learning to Code

Roadmaps, language guides, and practical advice for learning to code and launching a programming career.

Breaking Into Tech

Practical, no-nonsense guides for anyone looking to start or change their career in tech. From choosing your first language to acing interviews.

The African Stack: Skills for This Market

The skills that make Kenyan developers hard to replace: M-Pesa, USSD, WhatsApp, fintech, and building for the African market.

Bonaventure Ogeto

Bonaventure Ogeto

Founder, McTaba Labs

Bonaventure is the founder of McTaba Labs, a coding bootcamp in Nairobi, Kenya. He has spent years building products for the African market and mentoring the next generation of developers across the continent.