PHP

GENERATE YOUR API KEYS

API keys are your digital references towards PayDunya systems. We use them to identify your account and the applications you will create. These keys are necessary for any integration of the APIs of PayDunya's payments APIs. Here are the steps to follow:

  • First you need have a PayDunya Business account activated. Create one if it is not yet the case.

  • Login to your account and click on Integration API at the menu level on the left.

  • Click on the button Set up a new application and fill out the form.

  • Choose Test mode, I want to make payment tests and Enable production mode.

INSTALLATION

Installation via Composer


Composer is a tool for handling dependencies in PHP. Dependencies, in a project, are all the libraries that your project depends on to function. For example, your project will use the PayDunya library to manage payments, so it "depends" on PayDunya. In other words, PayDunya is an addiction in your project. For more information, please visit the official website of Composer.

composer require paydunya/paydunya

Manual installation


Click here to download the latest version of our PHP client. Then unzip the file and copy the content to a location in the folder containing the source code of your application.

Trick


If you do not know which subfolder to put the PayDunya library, we propose the following subfolder names: libs, libraries or vendor.

BASIC CONFIGURATION

1 - API configuration

You can create a global configuration file that contains the following settings and include it later in each of your files that require the API. First, think of including the PHP client of PayDunya at the level of the global configuration file.

Case of a manual installation

require('path_of_paydunya_php_client_directory/paydunya.php');

Case of an installation via Composer

 Trick


However, if you have chosen installation via Composer, you only need to include the vendor/autoload.php file.

require('vendor/autoload.php');

Login to your PayDunya account, click Integration API then details at the application level that you have created, retrieve the API keys and give them as arguments to the following methods:

Case of a manual installation


Paydunya_Setup::setMasterKey("wQzk9ZwR-Qq9m-0hD0-zpud-je5coGC3FHKW");
Paydunya_Setup::setPublicKey("test_public_kb9Wo0Qpn8vNWMvMZOwwpvuTUja");
Paydunya_Setup::setPrivateKey("test_private_rMIdJM3PLLhLjyArx9tF3VURAF5");
Paydunya_Setup::setToken("IivOiOxGJuWhc5znlIiK");
Paydunya_Setup::setMode("test"); //Optional. Use this option for test payments.

 Trick


If you are under test use the test keys otherwise use the production keys and specify the mode by replacing "test" with "live" in the code above.

Case of an installation via Composer


\Paydunya\Setup::setMasterKey("wQzk9ZwR-Qq9m-0hD0-zpud-je5coGC3FHKW");
\Paydunya\Setup::setPublicKey("test_public_kb9Wo0Qpn8vNWMvMZOwwpvuTUja");
\Paydunya\Setup::setPrivateKey("test_private_rMIdJM3PLLhLjyArx9tF3VURAF5");
\Paydunya\Setup::setToken("IivOiOxGJuWhc5znlIiK");
\Paydunya\Setup::setMode("test"); // Optional. Use this option for test payments.

For more details on the transition to production click here.

2 - Configuring your service/activity/company information


You can configure your service/activity/company information as shown below. PayDunya uses these settings to configure the information that will appear on the payment page, PDF invoices, and printed receipts.You can also include this information at the global configuration file level.

 Mandatory


For the configuration of your service/company information, only the name is required, all other information is optional.


Case of a manual installation



//Configuring your service/company information
Paydunya_Checkout_Store::setName("Sandra's Store"); // Only the name is required
Paydunya_Checkout_Store::setTagline("Elegance has no price");
Paydunya_Checkout_Store::setPhoneNumber("336530583");
Paydunya_Checkout_Store::setPostalAddress("Dakar Plateau - Establishment kheweul");
Paydunya_Checkout_Store::setWebsiteUrl("http://www.chez-sandra.sn");
Paydunya_Checkout_Store::setLogoUrl("http://www.chez-sandra.sn/logo.png");

Case of an installation via Composer



//Configuring your service/company information
\Paydunya\Checkout\Store::setName("Sandra's Store"); // Only the name is required
\Paydunya\Checkout\Store::setTagline("Elegance has no price");
\Paydunya\Checkout\Store::setPhoneNumber("336530583");
\Paydunya\Checkout\Store::setPostalAddress("Dakar Plateau - Establishment kheweul");
\Paydunya\Checkout\Store::setWebsiteUrl("http://www.chez-sandra.sn");
\Paydunya\Checkout\Store::setLogoUrl("http://www.chez-sandra.sn/logo.png");

3 - Configuring IPN (Instant Payment Notification)


The IPN is the URL of the file on which you want to receive payment transaction information for possible backoffice processing. PayDunya uses this URL to send you information about the payment transaction instantly by POST.

 Mandatory


There are two ways to set up the Instant Payment Notification URL: either by going to your PayDunya account at the level of your app's configuration information or directly in your code.

 Info


Using the second option offers you the two possibilities below.

3-1 - Global configuration of instant payment notification URL


This instruction should be included in the configuration of your service/activity.


Case of a manual installation


Paydunya_Checkout_Store::setCallbackUrl("http://magasin-le-choco.com/callback_url.php");

Case of an installation via Composer



\Paydunya\Checkout\Store::setCallbackUrl("http://magasin-le-choco.com/callback_url.php");

3-2 - Configuring the Instant Payment Notification URL on an Invoice Instance


 Alert


This configuration will overwrite the previous global settings if they were defined.

$invoice->setCallbackUrl("http://magasin-le-choco.com/callback_url.php");

 Mandatory


The confirmation of the payment by the customer returns the structure below containing the details of the customer, the URL of its invoice in PDF version and a hash allowing to verify that the received data come from our servers.


Expected answer:


array (
  'data' => 
    array (
     'response_code' => '00',
     'response_text' => 'Transaction Found',
     'hash' => '8c6666a27fe5daeb76dae6abc7308a557dca5be1bda85dfe5d81fa330cdc0bc3c4b37765fe5d2cc36aa2ba0f9284226a80f5488d14740fa70769d6079a179406',
     'invoice' => 
        array (
         'token' => 'test_jkEdPY8SuG',
         'items' => 
            array (
             'item_0' => 
                array (
                  'name' => 'Chaussures Croco',
                  'quantity' => '3',
                  'unit_price' => '10000',
                  'total_price' => '30000',
                  'description' => 'Chaussures faites en peau de crocrodile authentique qui chasse la pauvreté',
               ),
             'item_1' => 
                array (
                 'name' => 'Chemise Glacée',
                 'quantity' => '1',
                 'unit_price' => '5000',
                 'total_price' => '5000',
                 'description' => '',
               ),
           ),
          'taxes' => 
            array (
              'tax_0' => 
                array (
                  'name' => 'TVA (18%)',
                  'amount' => '6300',
               ),
              'tax_1' => 
                array (
                'name' => 'Livraison',
                'amount' => '1000',
              ),
      ),
      'token': 'test_Jh2T8skw1j',
      'total_amount' => '42300',
      'description' => 'Paiement de 42300 FCFA pour article(s) achetés sur Magasin le Choco',
      ),
      'custom_data' => 
        array (
          'categorie' => 'Jeu concours',
          'periode' => 'Noël 2015',
          'numero_gagnant' => '5',
          'prix' => 'Bon de réduction de 50%',
        ),
      'actions' => 
        array (
          'cancel_url' => 'http://magasin-le-choco.com/cancel_url.aspx',
          'callback_url' => 'http://magasin-le-choco.com/callback_url.aspx',
          'return_url' => 'http://magasin-le-choco.com/return_url.aspx',
        ),
      'mode' => 'test',
      'status' => 'completed',
      'customer' => 
        array (
         'name' => 'Alioune Faye',
         'phone' => '774563209',
         'email' => '[email protected]',
        ),
      'receipt_url' => 'https://paydunya.com/sandbox-checkout/receipt/pdf/test_jkEdPY8SuG.pdf',
    ),
  )  

  Mandatory


The hash returned by PayDunya is the hash of your MasterKey. This hash will allow you to make sure that the data you have received comes from our servers. The algorithm used to obtain the hash is SHA-512. In the expected response, a failure message is entered in the fail_reason node only for failed or canceled bank card transactions.

 Mandatory


PayDunya Make a Post request of type application/x-www-form-urlencoded on your callback endpoint and post a data table containing the payment information. You must use the "data" key before recovering a node. The returned structure is located under the index "data" .


For example to recover the payment status, the customer name and the hash, here is the code to execute:

4 - Recovery of payment status


$status = $_POST['data']['status'];

5 - Recovery of the total payment amount


$amount = $_POST['data']['invoice']['total_amount'];

6 - Recovering the hash


$hash = $_POST['data']['hash'];

 Info


The hash returned by PayDunya is the hash of your MasterKey. This hash will allow you to make sure that the data you have received comes from our servers.

7 - Sample IPN verification code


try {
  //Take your MasterKey, hash it and compare the result to the received hash by IPN
  if($_POST['data']['hash'] === hash('sha512', "VOTRE_CLE_PRINCIPALE")) {

    if ($_POST['data']['status'] == "completed") {
        //Do your backoffice treatments here ...
    }

    } else {
          die("This request was not issued by PayDunya");
    }
  } catch(Exception $e) {
    die();
  }

  Mandatory


Hashez your main key and compare the result to the hash received by IPN.

  Good practices


Never put your API keys in a file of your source code, instead use for example environment variables.

APIS

SERVICES PAR AND PER

1 - initialization

Initialization of a Payment With Redistribution :

PayDunya's "Payment With Redistribution" service allows you to create an invoice and redirect your customer to our platform so that it can complete the payment process. We recommend using the API of "Payment With Redistribution" as it is the most suitable in 99% of cases. The main advantage of this option is that customers can choose to pay from a variety of payment options available on our platform. In addition, if a new option is added in the future, it will appear directly on the payment page without you having to change anything in your source code.

In the source code file that should perform the action, do this if you want to redirect your clients to our website so that they can complete the payment process :


Case of a manual installation


$invoice = new Paydunya_Checkout_Invoice();

Case of an installation via Composer


$invoice = new \Paydunya\Checkout\CheckoutInvoice();

2 - Adding payment information


2-1 - Adding articles and invoice description :


It is important to know that billing items are primarily used for presentation purposes on the payment page. PayDunya will not use any of the amounts declared to bill the customer. To do this, you must explicitly use the setTotalAmount API method to specify the exact amount to bill the customer.


//To be inserted into the source code file that must perform the action

/* Adding items to your bill is very basic.
The expected parameters are product name, quantity, unit price,
the total price and an optional description.*/
$invoice->addItem("Croco shoes", 3, 10000, 30000, "Shoes made of genuine crocodile skin that hunts poverty");
$invoice->addItem("Ice Shirt", 1, 5000, 5000);

 Trick


You can optionally define a general invoice description that will be used in cases where you need to include additional information in your invoice.


$invoice->setDescription("Optional Description");

2-2 - Configuration of the total amount of the invoice:


PayDunya expects you to specify the total amount of the customer's bill. This will be the amount that will be billed to your client. We consider that you have already done all calculations at your server before setting this amount.

  Info


PayDunya will not perform calculations on its servers. The total amount of the invoice set from your server will be the one that PayDunya will use to bill your customer.

$invoice->setTotalAmount(42300);

PAR case : Redirection to the PayDunya payment page


After adding items to your invoice and configuring the total invoice amount, you can redirect your customer to the payment page by calling the create method from your invoice object $invoice. Please note that the $invoice->create() method returns a boolean (true or false) depending on whether the invoice was created successfully or not. This allows you to put an if - else statement and handle the result as you see fit.


//To be inserted into the source code file that must perform the action

// The following code describes how to create a payment invoice at our servers,
// then redirect the customer to the payment page
// and then post his payment receipt if successful.
if($invoice->create()) {
    header("Location: ".$invoice->getInvoiceUrl());
}else{
    echo $invoice->response_text;
}

PER CASE : Payment And Redistribution


This option is very interesting if you want to create your own payment solution over PayDunya or if you have to pay a certain percentage for each sale (in the case of a marketplace for example). The money is redistributed on the various PayDunya accounts of the recipients and the service is not invoiced.

You can transfer funds to other PayDunya customer accounts from your account via the Payment And Redistribution API. For security reasons, you must explicitly enable the Payment And Redistribution option in your integration/application configuration by going to your PayDunya account. You can always enable or disable the Payment And Redistribution service by updating the configuration of your integration/application by going to your PayDunya account.


//To be inserted into the source code file that must perform the action

$direct_pay = new Paydunya_DirectPay();
if ($direct_pay->creditAccount("EMAIL_OU_NUMERO_MOBILE_DU_CLIENT_PAYDUNYA", "MONTANT_A_TRANSFERER")) {
    echo $direct_pay->description;
    echo $direct_pay->response_text;
    echo $direct_pay->transaction_id;
}else{
    echo $direct_pay->response_text;
}

ADDITIONNAL API METHODS

1 - Add taxes (optional)


You can add tax information on the payment page. This information will then be displayed on the payment page, PDF invoices and printed receipts, electronic receipts.


//To be inserted into the source code file that must perform the action
// The parameters are the name of the tax and the amount of the tax.
$invoice->addTax("TVA (18%)", 6300);
$invoice->addTax("Livraison", 1000);

2 - Adding additional data (optional)


If you need to add additional data to your payment request information for future use, we offer you the option of backing up custom data on our servers and recovering it once the payment is successful.

 Info


Custom data is not displayed anywhere on the checkout page, invoices/receipts, downloads, and impressions. They are only retrieved using our confirm callback action at the API level.


//To be inserted into the source code file that must perform the action

// Custom data allows you to add additional data to your billing information
// that can be retrieved later using our callback Confirm action
$invoice->addCustomData("category", "Contest");
$invoice->addCustomData("period", "Christmas 2015");
$invoice->addCustomData("numero_gagnant", 5);
$invoice->addCustomData("price","50% discount voucher");

3 - Restriction of the means of payment to display (optional)


By default, the payment methods activated in your integration configuration will all be displayed on the payment page for all your invoices. However, if you want to keep the list of payment methods to display on the payment page of a given invoice, we offer you the possibility to do so by using the methods addChannel and addChannels.

  Info


To obtain the names of the operators to assign as values ​​to the channels key, please consult this link which lists the different operators available.


// Addition of means of payment individually
$invoice->addChannel('free-money-senegal')
$invoice->addChannel('card')

// Addition of several payment methods at a time
$invoice->addChannels(['card', 'wave-senegal', 'orange-money-senegal'])

4 - Configuring a redirect URL after canceling payment


You can optionally define a URL to which your customers will be redirected after an order cancellation.

 Trick


There are two ways to configure the order cancellation URL: either globally at the configuration information level of your application or by order.

  Alert


Using the second option overwrites the global settings if they have already been defined.


4-1 - Global configuration of the redirection URL after canceling payment


This instruction should be included in the configuration of your service/activity.


// Case of a manual installation
Paydunya_Checkout_Store::setCancelUrl("http://magasin-le-choco.com/cancel_url.php");

// Case of an installation via Composer
\Paydunya\Checkout\Store::setCancelUrl("http://magasin-le-choco.com/cancel_url.php");

4-2 - Configuring the redirection URL after canceling payment on an invoice instance


This configuration will overwrite the global redirection settings if they have already been defined.

$invoice->setCancelUrl("http://magasin-le-choco.com/cancel_url.php");

5 - Configuring a redirect URL after payment confirmation


PayDunya does a great job of managing downloads and receipt printing of payments after your customer has successfully paid for their order. However, there may be cases where you would want to redirect your customers to another URL after they have successfully paid for their order. The configuration below meets this need.

 Info


PayDunya will add ?token=invoice_token to your URL. We will explain how to use this token in the next chapter.


5-1 - Global configuration of the redirect URL after payment confirmation.


This instruction should be included in the configuration of your service/activity


// Case of a manual installation
Paydunya_Checkout_Store::setReturnUrl("http://magasin-le-choco.com/return_url.php");

// Case of an installation via Composer
\Paydunya\Checkout\Store::setReturnUrl("http://magasin-le-choco.com/return_url.php");

5-2 - Configuring the redirect URL after confirming payment on an invoice instance


  Alert


Using the second option overwrites the global settings if they have already been defined.

$invoice->setReturnUrl("http://magasin-le-choco.com/return_url.php");

CHECKING THE PAYEMENT STATUS

Our API allows you to check the status of all payment transactions using the invoice token. You can therefore keep your invoice token and use it to check the payment status of the invoice. The status of an invoice can be either pending (pending) , canceled (canceled) , or completed (completed) depending on if yes or not the customer has paid the bill.

  Info


However, this option is suitable for PAR payments as it would allow you for example to know the payment status of your bill even if the customer is still on our payment page.


Case of a manual installation



//To be inserted into the source code file that must perform the action

// PayDunya will automatically add the invoice token as a QUERYSTRING "token"
// if you have set a "return_url" or "cancel_url".
// Get the pure PHP token via $_GET['token']
$token = $_GET['token'];

$invoice = new Paydunya_Checkout_Invoice();
if ($invoice->confirm($token)) {

  // Retrieve payment status
  // The payment status can be either completed, pending, cancelled
  echo $invoice->getStatus();

  // You can retrieve the name, email address and
  // customer's phone number using
  // the following methods
  echo $invoice->getCustomerInfo('name');
  echo $invoice->getCustomerInfo('email');
  echo $invoice->getCustomerInfo('phone');

  // The following methods will be available if and
  // only if the payment status is equal to "completed".

  // Retrieve the URL of the electronic PDF receipt for download
  echo $invoice->getReceiptUrl();

  // Recover any of the custom data that
  // you had to add to the bill previously.
  // Please make sure to use the same keys used
  // during the configuration.
  echo $invoice->getCustomData("category");
  echo $invoice->getCustomData("period");
  echo $invoice->getCustomData("numero_gagnant");
  echo $invoice->getCustomData("price");

  // You can also recover the total amount specified previously
  echo $invoice->getTotalAmount();

}else{
  echo $invoice->getStatus();
  echo $invoice->response_text;
  echo $invoice->response_code;
}

Case of an installation via Composer



//To be inserted into the source code file that must perform the action

// PayDunya will automatically add the invoice token as a QUERYSTRING "token"
// if you have configured a "return_url" or "cancel_url".
// Get the pure PHP token via $_GET['token']
$token = $_GET['token'];

$invoice = new \Paydunya\Checkout\CheckoutInvoice();
if ($invoice->confirm($token)) {

  //Retrieve payment status
  // The payment status can be either completed, pending, cancelled
  echo $invoice->getStatus();

  // You can retrieve the name, email address and
  // customer's phone number using
  // the following methods
  echo $invoice->getCustomerInfo('name');
  echo $invoice->getCustomerInfo('email');
  echo $invoice->getCustomerInfo('phone');

  // The following methods will be available if and
  // only if the payment status is equal to "completed".

  // Retrieve the URL of the electronic PDF receipt for download
  echo $invoice->getReceiptUrl();

  // Recover any of the custom data that
  // you had to add to the bill previously.
  // Please make sure to use the same keys used
  // during the configuration.
  echo $invoice->getCustomData("category");
  echo $invoice->getCustomData("period");
  echo $invoice->getCustomData("numero_gagant");
  echo $invoice->getCustomData("price");

  // You can also recover the total amount specified previously
  echo $invoice->getTotalAmount();

}else{
  echo $invoice->getStatus();
  echo $invoice->response_text;
  echo $invoice->response_code;
}