Symfony (New)

Source Files

Install the MyFatoorah Symfony bundle via myfatoorah/symfony-bundle composer.

composer require myfatoorah/symfony-bundle

Installation steps

❗️

Important Note

The MyFatoorah Symfony Bundle provides examples of how to use the MyFatoorah Library and the MyFatoorah API endpoints. Any validations or security criteria must be taken from your side to ensure a seamless payment experience.

  1. Import MyFatoorahSymfonyBundle routing files by adding the below route in the config/routes.yaml file of your project:
myfatoorah_symfony:
    resource: '@MyFatoorahSymfonyBundle/Resources/config/routing.yaml'
  1. Only for Applications that don't use Symfony Flex, you will need to enable the bundle manually by adding it to the list of registered bundles in the config/bundles.php file of your project:
return [
    // ...
    MyFatoorah\SymfonyBundle\MyFatoorahSymfonyBundle::class => ['all' => true]
];
  1. To test the payment cycle, type the below URL onto your browser. Replace only the {example.com} with your site domain. You can use the test cards listed on the Test Cards page.
https://{example.com}/myfatoorah/create
  1. Copy the vendor/myfatoorah/symfony-bundle/src/Controller/InvoiceController.php file to your controller, then customize it as per your site needs.
<?php

namespace MyFatoorah\SymfonyBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\ParameterBag\ContainerBagInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use MyFatoorah\Library\PaymentMyfatoorahApiV2;

//class InvoiceController  {
class InvoiceController extends AbstractController {

    public $mfObj;

    public const VERSION = '2.0.0';

//-----------------------------------------------------------------------------------------------------------------------------------------

    /**
     * create MyFatoorah object
     */
    public function __construct(ContainerBagInterface $params) {

        $apiKey      = $params->get('myfatoorah.apiKey');
        $countryCode = $params->get('myfatoorah.countryCode');
        $isTest      = $params->get('myfatoorah.isTest');
        $this->mfObj = new PaymentMyfatoorahApiV2($apiKey, $countryCode, $isTest);
    }

//-----------------------------------------------------------------------------------------------------------------------------------------

    /**
     * Create MyFatoorah invoice
     *
     * @Route("/myfatoorah/create", name="myfatoorah_symfony_create")
     * 
     * @return JsonResponse
     */
    public function create() {
        try {

            $paymentMethodId = 0; // 0 for MyFatoorah invoice or 1 for Knet in test mode

            $curlData = $this->getPayLoadData();

            $data = $this->mfObj->getInvoiceURL($curlData, $paymentMethodId);

            $response = ['IsSuccess' => 'true', 'Message' => 'Invoice created successfully.', 'Data' => $data];
        } catch (\Exception $e) {
            $response = ['IsSuccess' => 'false', 'Message' => $e->getMessage()];
        }
        return $this->json($response);
    }

//-----------------------------------------------------------------------------------------------------------------------------------------

    /**
     * 
     * @param int|string $orderId
     * @return array
     */
    private function getPayLoadData($orderId = null) {
        $callbackURL = 'http:' . $this->generateUrl('myfatoorah_symfony_callback', [], UrlGeneratorInterface::NETWORK_PATH);

        return [
            'CustomerName'       => 'FName LName',
            'InvoiceValue'       => '10',
            'DisplayCurrencyIso' => 'KWD',
            'CustomerEmail'      => '[email protected]',
            'CallBackUrl'        => $callbackURL,
            'ErrorUrl'           => $callbackURL,
            'MobileCountryCode'  => '+965',
            'CustomerMobile'     => '12345678',
            'Language'           => 'en',
            'CustomerReference'  => $orderId,
            'SourceInfo'         => 'Symfony ' . \Symfony\Component\HttpKernel\Kernel::VERSION . ' - MyFatoorah ' . self::VERSION
        ];
    }

//-----------------------------------------------------------------------------------------------------------------------------------------

    /**
     * Get MyFatoorah payment information
     * 
     * @Route("/myfatoorah/callback", name="myfatoorah_symfony_callback")
     * 
     * @param Request $request
     * @return JsonResponse
     */
    public function callback(Request $request): JsonResponse {
        //http://127.0.0.1:8000/myfatoorah/callback?paymentId=100202217186102325
        try {
            $paymentId = $request->query->get('paymentId');

            $data = $this->mfObj->getPaymentStatus($paymentId, 'PaymentId');
            if ($data->InvoiceStatus == 'Paid') {
                $msg = 'Invoice is paid.';
            } else if ($data->InvoiceStatus == 'Failed') {
                $msg = 'Invoice is not paid due to ' . $data->InvoiceError;
            } else if ($data->InvoiceStatus == 'Expired') {
                $msg = 'Invoice is expired.';
            }

            $response = ['IsSuccess' => 'true', 'Message' => $msg, 'Data' => $data];
        } catch (\Exception $e) {
            $response = ['IsSuccess' => 'false', 'Message' => $e->getMessage()];
        }
        return $this->json($response);
    }

//-----------------------------------------------------------------------------------------------------------------------------------------
}

📘

MyFtoorah Library

MyFatoorah Symfony-Bundle uses the MyFatoorah Library composer package. Check the PHP library to help you Customize your Symfony website.


Merchant Configurations

Edit the vendor/myfatoorah/symfony-bundle/src/Resources/config/services.yaml file with your correct vendor data.

  • Live Configuration: set "isTest" with "false" and use your live token.
  • Test Configuration: set "isTest" with "true" and use the test token. Also, use the list of test cards to explore the payment process.

After that, run the below cmd to reload the new configurations.

./bin/console cache:clear
#File: vendor/myfatoorah/symfony-bundle/src/Resources/config/services.yaml
parameters:
    
    #API Token Key
    #Live Token: https://myfatoorah.readme.io/docs/live-token
    #Test Token: https://myfatoorah.readme.io/docs/test-token
    myfatoorah.apiKey: 'rLtt6JWvbUHDDhsZnfpAhpYk4dxYDQkbcPTyGaKp2TYqQgG7FGZ5Th_WD53Oq8Ebz6A53njUoo1w3pjU1D4vs_ZMqFiz_j0urb_BH9Oq9VZoKFoJEDAbRZepGcQanImyYrry7Kt6MnMdgfG5jn4HngWoRdKduNNyP4kzcp3mRv7x00ahkm9LAK7ZRieg7k1PDAnBIOG3EyVSJ5kK4WLMvYr7sCwHbHcu4A5WwelxYK0GMJy37bNAarSJDFQsJ2ZvJjvMDmfWwDVFEVe_5tOomfVNt6bOg9mexbGjMrnHBnKnZR1vQbBtQieDlQepzTZMuQrSuKn-t5XZM7V6fCW7oP-uXGX-sMOajeX65JOf6XVpk29DP6ro8WTAflCDANC193yof8-f5_EYY-3hXhJj7RBXmizDpneEQDSaSz5sFk0sV5qPcARJ9zGG73vuGFyenjPPmtDtXtpx35A-BVcOSBYVIWe9kndG3nclfefjKEuZ3m4jL9Gg1h2JBvmXSMYiZtp9MR5I6pvbvylU_PP5xJFSjVTIz7IQSjcVGO41npnwIxRXNRxFOdIUHn0tjQ-7LwvEcTXyPsHXcMD8WtgBh-wxR8aKX7WPSsT1O8d8reb2aR7K3rkV3K82K_0OgawImEpwSvp9MNKynEAJQS6ZHe_J_l77652xwPNxMRTMASk1ZsJL'
    
    #Country ISO Code
    #Accepted value: KWT, SAU, ARE, QAT, BHR, OMN, JOD, or EGY.
    myfatoorah.countryCode: 'KWT'
    
    #Test Mode
    #Accepted value: 'true' for the test mode or 'false' for the live mode
    myfatoorah.isTest: true
    
services:
    _defaults:
        autowire: true      # Automatically injects dependencies in your services.
        autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.
        
    MyFatoorah\SymfonyBundle\:
        resource: '../../'