0% found this document useful (0 votes)
377 views

Integrate API With Telebirr

Uploaded by

wubshet adane
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
377 views

Integrate API With Telebirr

Uploaded by

wubshet adane
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

You said:

how to connect telebirr api with my online food ordering system give me sample php code

ChatGPT said:
ChatGPT

To integrate Telebirr API (which is a mobile money payment platform by Ethio Telecom) into
your online food ordering system, you would need to interact with Telebirr's payment gateway.
The specific steps depend on Telebirr's official API documentation, which may not be publicly
available. However, I can guide you through a general approach for integrating a payment
gateway API into a PHP-based system.

Assuming Telebirr provides a RESTful API for payments (as most modern APIs do), you can
follow the steps below to integrate Telebirr into your food ordering system using PHP.

General Steps:

1. Set up an Account with Telebirr: First, you need to register as a merchant with Telebirr
to get access to their API keys and other necessary credentials.
2. Get API Documentation: Ensure you have access to Telebirr's API documentation,
which should provide you with endpoint URLs, authentication methods, required
parameters, and sample responses.
3. Install Guzzle HTTP Client: To interact with Telebirr’s API, you may use the Guzzle
HTTP client for making API requests from your PHP backend.
4. Implement the Payment Flow: Once the user places an order in your food ordering
system, you will redirect them to Telebirr for payment or use Telebirr's API to create a
payment request.

Here is a sample PHP code for making a payment request to an external API like Telebirr (you
will need to modify it based on their actual API specifications):

1. Install Guzzle (if using Composer):

If you don’t have Guzzle installed, you can use Composer to install it:

composer require guzzlehttp/guzzle

2. PHP Code Example:

Here’s a sample code for interacting with a payment API in PHP:

<?php
// Include the Guzzle HTTP client
require 'vendor/autoload.php';

use GuzzleHttp\Client;
class TelebirrPayment {
private $client;
private $apiUrl = "https://api.telebirr.com/payment"; // Replace with
Telebirr's actual API URL
private $apiKey = "your_api_key"; // Replace with your API key from
Telebirr
private $merchantId = "your_merchant_id"; // Replace with your merchant
ID from Telebirr

public function __construct() {


$this->client = new Client();
}

// Function to create a payment request


public function createPaymentRequest($orderId, $amount, $currency = 'ETB',
$callbackUrl) {
$data = [
'merchant_id' => $this->merchantId,
'order_id' => $orderId,
'amount' => $amount,
'currency' => $currency,
'callback_url' => $callbackUrl, // URL to which Telebirr will
send payment status updates
'description' => "Food Order Payment", // Description of the
transaction
];

try {
$response = $this->client->post($this->apiUrl, [
'headers' => [
'Authorization' => 'Bearer ' . $this->apiKey, // Include
the API Key in the Authorization header
'Content-Type' => 'application/json',
],
'json' => $data, // Send the data as a JSON body
]);

$statusCode = $response->getStatusCode(); // Get the HTTP


response code
$responseBody = $response->getBody()->getContents(); // Get the
response content

// Decode the JSON response


$responseData = json_decode($responseBody, true);

if ($statusCode == 200 && isset($responseData['payment_url'])) {


// If the response is successful, redirect the user to the
Telebirr payment page
header("Location: " . $responseData['payment_url']);
exit();
} else {
// Handle the error if no payment URL is returned
echo "Error: " . $responseData['message'];
}

} catch (\Exception $e) {


echo 'Request failed: ' . $e->getMessage();
}
}

// Function to handle the callback from Telebirr after payment


public function handleCallback($requestData) {
// Process the callback data from Telebirr (e.g., payment status,
order ID)
// For example:
$orderId = $requestData['order_id'];
$status = $requestData['status']; // Example response, replace with
actual data
$amount = $requestData['amount'];

if ($status == 'success') {
// Mark the order as paid in your database
echo "Payment for Order ID $orderId was successful!";
} else {
echo "Payment failed for Order ID $orderId.";
}
}
}

// Example usage:

$orderId = "12345"; // Order ID from your system


$amount = 500; // Amount to be paid in ETB
$callbackUrl = "https://yourwebsite.com/payment-callback.php"; // Your
callback URL to get payment updates

$telebirrPayment = new TelebirrPayment();


$telebirrPayment->createPaymentRequest($orderId, $amount, 'ETB',
$callbackUrl);
?>

3. Callback Handling:

You need to implement a callback URL to handle payment status updates from Telebirr. After
the user completes the payment, Telebirr will send the status (success/failure) to your callback
URL.

Here’s a simple payment-callback.php script that processes the callback:

<?php
// payment-callback.php

// Retrieve callback data from Telebirr (e.g., via POST)


$requestData = json_decode(file_get_contents('php://input'), true);

// Instantiate the TelebirrPayment class to handle the response


$telebirrPayment = new TelebirrPayment();
$telebirrPayment->handleCallback($requestData);
?>
Notes:

1. Telebirr API Endpoint: Make sure you replace the $apiUrl with the correct Telebirr
API endpoint URL for creating a payment request. You will find this in the official API
documentation.
2. Authorization: The above code assumes that the API uses a Bearer token for
authentication (e.g., Authorization: Bearer <API_KEY>). This may vary based on
Telebirr's actual API.
3. Error Handling: Add proper error handling to ensure you manage all possible API
response scenarios, including timeouts, incorrect responses, etc.
4. Testing: Before going live, thoroughly test the integration in a sandbox environment (if
available).
5. Security: Ensure that sensitive data such as the API key and merchant ID are securely
stored and not exposed in your public codebase.

Conclusion:

This example provides a basic structure for integrating Telebirr into your PHP-based food
ordering system. You’ll need to adapt the code based on the actual API documentation that
Telebirr provides. Make sure to handle payment verification and success/failure scenarios
appropriately to ensure smooth user experience.

You said:
add more deescription

ChatGPT said:
ChatGPT

Certainly! Below is an expanded description of how to integrate the Telebirr API with your
online food ordering system, using PHP. The flow is broken down into key components,
including preparation, payment creation, callback handling, and error handling. Each part is
explained in detail.

Overview

Telebirr is a mobile money payment system provided by Ethio Telecom, designed to facilitate
digital payments in Ethiopia. To integrate Telebirr with your online food ordering system, you
will use their API to initiate payment requests and receive payment status updates. This can be
done through API calls made from your PHP server.

Below is a step-by-step breakdown of the process to implement Telebirr payment integration in a


PHP-based system.

1. Pre-Integration Steps
Before writing any PHP code, you need to take care of a few important steps:

a. Register as a Merchant:

 You need to create an account with Telebirr as a merchant in order to get access to their
payment API.
 This process will give you the necessary credentials such as:
o API Key (used for authenticating your API requests).
o Merchant ID (unique to your business for identifying your payment requests).

b. Obtain API Documentation:

 Contact Telebirr for the official API documentation. This will provide details about the endpoints,
request and response format, authentication mechanisms, and possible errors.
 The documentation should also provide URLs for the Telebirr payment gateway, which you’ll use
to redirect customers to complete the payment.

2. Install Guzzle HTTP Client

Guzzle is a popular PHP HTTP client library for making API requests. It simplifies the process
of sending HTTP requests and handling responses.

a. Install Guzzle via Composer:

If you haven’t already, you can install Guzzle by running the following command in the root
directory of your project:

composer require guzzlehttp/guzzle

This will download and install the Guzzle HTTP client, which you can use to make HTTP
requests to the Telebirr API.

3. PHP Code for Payment Request Creation

a. Creating the Payment Request:

Once the customer selects their food order, you will create a payment request to Telebirr, passing
necessary details like the order ID, payment amount, currency, and a callback URL to receive the
payment status.

<?php
require 'vendor/autoload.php';
use GuzzleHttp\Client;

class TelebirrPayment {
private $client;
private $apiUrl = "https://api.telebirr.com/payment"; // Telebirr API URL
(check the documentation for the correct one)
private $apiKey = "your_api_key"; // Replace with your Telebirr API key
private $merchantId = "your_merchant_id"; // Replace with your merchant
ID

public function __construct() {


// Initialize the Guzzle client
$this->client = new Client();
}

// Function to create a payment request


public function createPaymentRequest($orderId, $amount, $currency = 'ETB',
$callbackUrl) {
// Prepare the data to send in the API request
$data = [
'merchant_id' => $this->merchantId,
'order_id' => $orderId, // The unique ID of the food order
'amount' => $amount, // The amount to be paid
'currency' => $currency, // The currency of the transaction
(typically ETB for Ethiopian Birr)
'callback_url' => $callbackUrl, // The URL to receive updates on
the payment status
'description' => "Food Order Payment", // A short description of
the payment
];

try {
// Send the payment request to the Telebirr API
$response = $this->client->post($this->apiUrl, [
'headers' => [
'Authorization' => 'Bearer ' . $this->apiKey, // API Key
in Authorization header
'Content-Type' => 'application/json', // Indicating JSON
content type
],
'json' => $data, // Send the data in JSON format
]);

// Get the HTTP response code and response content


$statusCode = $response->getStatusCode();
$responseBody = $response->getBody()->getContents();

// Decode the JSON response from Telebirr


$responseData = json_decode($responseBody, true);

if ($statusCode == 200 && isset($responseData['payment_url'])) {


// If successful, redirect the user to the payment page
header("Location: " . $responseData['payment_url']);
exit();
} else {
// Handle the error if no payment URL is returned
echo "Error: " . $responseData['message'];
}

} catch (\Exception $e) {


// Handle any exceptions (e.g., network errors, API issues)
echo 'Request failed: ' . $e->getMessage();
}
}

// Function to handle the callback from Telebirr after payment


public function handleCallback($requestData) {
// Retrieve and process the payment status from the callback data
$orderId = $requestData['order_id']; // Extract order ID from the
callback
$status = $requestData['status']; // Payment status (success/failure)
$amount = $requestData['amount']; // The amount paid (if successful)

// You can now update the order status in your database


if ($status == 'success') {
// Mark the order as paid
echo "Payment for Order ID $orderId was successful!";
} else {
// Handle payment failure
echo "Payment failed for Order ID $orderId.";
}
}
}

// Example usage:

$orderId = "12345"; // Unique order ID for the food order


$amount = 500; // Payment amount in Ethiopian Birr (ETB)
$callbackUrl = "https://yourwebsite.com/payment-callback.php"; // URL to
receive payment status updates

$telebirrPayment = new TelebirrPayment();


$telebirrPayment->createPaymentRequest($orderId, $amount, 'ETB',
$callbackUrl);
?>

Explanation of the Code:

 createPaymentRequest: This function is responsible for initiating the payment process. It


makes a POST request to the Telebirr API, passing the order details (like order ID, amount, and
currency).
o If the payment request is successful, the API response will include a payment_url,
which is the URL where the user will be redirected to complete the payment.
 handleCallback: This function will be used to process the callback from Telebirr after the user
has completed the payment. It will receive the status of the payment (e.g., success or failure)
and update the order status in your system accordingly.
4. Handling the Callback

After the user completes the payment via Telebirr, Telebirr will send a callback to your
predefined URL ($callbackUrl). This URL should point to a PHP file that will process the
response from Telebirr.

Here’s an example payment-callback.php file to handle the callback:

<?php
// payment-callback.php

// Retrieve the callback data (Telebirr will send payment information as JSON)
$requestData = json_decode(file_get_contents('php://input'), true);

// Instantiate the TelebirrPayment class to handle the response


$telebirrPayment = new TelebirrPayment();
$telebirrPayment->handleCallback($requestData);
?>

This script simply extracts the data sent by Telebirr (e.g., order ID, status), and calls the
handleCallback function to process it.

Callback Data Example:

A typical callback from Telebirr might look like this:

{
"order_id": "12345",
"status": "success",
"amount": "500",
"currency": "ETB"
}

5. Error Handling and Logging

It's important to handle errors and unexpected issues:

 Network Issues: If the API request fails due to network problems or the Telebirr server
being down, you should log the error and notify the user that the payment process is
temporarily unavailable.
 Invalid Responses: If Telebirr responds with an invalid or unexpected response, display
a generic error message to the user and log the error for later investigation.

6. Security Considerations
 Secure API Key Storage: Do not hard-code sensitive information like your API key
directly in the codebase, especially in production. Store it securely, such as in
environment variables or configuration files outside the public web directory.
 Input Validation: Always validate and sanitize the data you receive from users or
external systems (such as Telebirr) to avoid potential security risks like SQL injection or
cross-site scripting (XSS).
 SSL: Ensure your website uses HTTPS (SSL) to securely transmit payment data between
your users and the server.

7. Conclusion

This guide gives a basic overview of how to integrate the Telebirr payment gateway with a PHP-
based online food ordering system. The key steps involve:

1. Creating the payment request: Using the Telebirr API to initiate the payment process.
2. Handling the callback: Processing the payment status once Telebirr has completed the
transaction.
3. Error handling and security: Ensuring a smooth user experience and protecting sensitive data.

Make sure to review Telebirr’s official API documentation for specific details, such as the exact
endpoint URLs, authentication methods, and response structures.

You said:
describe detail about request and response

ChatGPT said:
ChatGPT

To successfully integrate Telebirr’s API with your online food ordering system, it’s crucial to
understand the request and response structures when interacting with the Telebirr API. This will
help you build the integration properly and handle data appropriately in your PHP code.

Since Telebirr’s official API documentation is required for exact details, we will assume that the
API follows a common RESTful design. The descriptions below are based on typical payment
gateway APIs but need to be adapted according to Telebirr’s official documentation once
available.

1. Telebirr API Request Structure

a. Payment Request (POST)

When a user places an order in your system and is ready to pay via Telebirr, you’ll make a
POST request to Telebirr’s payment gateway to initiate the payment.
Here’s a detailed explanation of the request body that you would typically send:

Request Endpoint Example:


POST https://api.telebirr.com/v1/payments/initiate

Request Headers:

 Authorization: This header will contain your API Key or Bearer token to authenticate your
request.
o Example: Authorization: Bearer your_api_key
 Content-Type: Set to application/json since the request body is in JSON format.
o Example: Content-Type: application/json

Request Body:

The body of the request will contain various parameters related to the order and payment.

Example of the JSON request body:

{
"merchant_id": "your_merchant_id",
"order_id": "12345",
"amount": 500, // Amount in Ethiopian Birr (ETB)
"currency": "ETB", // Currency code, typically ETB for Ethiopian Birr
"description": "Payment for food order #12345", // A description of the
order
"callback_url": "https://yourwebsite.com/payment-callback", // URL to
receive payment status updates
"redirect_url": "https://yourwebsite.com/thank-you", // URL to redirect
users after successful payment
"payment_type": "mobile", // Typically "mobile" if it's a mobile-based
payment like Telebirr
"user_phone": "0912345678" // Optional: Phone number of the customer, if
required
}

Key Parameters in the Payment Request:

 merchant_id: Your unique merchant identifier given by Telebirr.


 order_id: A unique identifier for the order from your system. This will be used to match the
payment with the order.
 amount: The total amount to be paid, in the specified currency (usually Ethiopian Birr).
 currency: The currency code for the transaction (typically ETB for Ethiopian Birr).
 description: A brief description of the transaction or order being paid for. This helps the
customer recognize the payment purpose.
 callback_url: The URL where Telebirr will send the payment status (success or failure) after
the user completes the payment. This is where you’ll handle updates in your system.
 redirect_url: The URL to which users will be redirected after completing the payment. This is
typically a "thank you" or order confirmation page.
 payment_type: Defines the type of payment (e.g., mobile or web). For Telebirr, this will
typically be mobile.
 user_phone (optional): If required by Telebirr, this would be the phone number of the user
making the payment.

b. Example Request Code in PHP (using Guzzle HTTP Client)


use GuzzleHttp\Client;

class TelebirrPayment {
private $client;
private $apiUrl = "https://api.telebirr.com/v1/payments/initiate"; //
Replace with actual Telebirr endpoint
private $apiKey = "your_api_key"; // Your API key
private $merchantId = "your_merchant_id"; // Your merchant ID

public function __construct() {


$this->client = new Client();
}

public function createPaymentRequest($orderId, $amount, $currency = 'ETB',


$callbackUrl, $redirectUrl, $userPhone = '') {
$data = [
'merchant_id' => $this->merchantId,
'order_id' => $orderId,
'amount' => $amount,
'currency' => $currency,
'description' => "Food Order Payment for Order #$orderId",
'callback_url' => $callbackUrl,
'redirect_url' => $redirectUrl,
'payment_type' => 'mobile',
'user_phone' => $userPhone, // Optional field if needed
];

try {
$response = $this->client->post($this->apiUrl, [
'headers' => [
'Authorization' => 'Bearer ' . $this->apiKey,
'Content-Type' => 'application/json',
],
'json' => $data,
]);

$statusCode = $response->getStatusCode();
$responseBody = $response->getBody()->getContents();
$responseData = json_decode($responseBody, true);

if ($statusCode == 200 && isset($responseData['payment_url'])) {


// If the request was successful, redirect the user to the
payment page
header("Location: " . $responseData['payment_url']);
exit();
} else {
echo "Error: " . $responseData['message'];
}
} catch (\Exception $e) {
echo 'Request failed: ' . $e->getMessage();
}
}
}

2. Telebirr API Response Structure

After initiating the payment request, Telebirr will respond with the payment details. Here’s what
you can expect:

a. Response Body (JSON)

The response will usually contain the status of the request and additional details like a payment
URL.

Example of a Successful Response:


{
"status": "success",
"payment_url": "https://telebirr.com/pay/12345", // URL to redirect user
to complete the payment
"order_id": "12345", // The same order ID you sent in the request
"message": "Payment request initiated successfully.",
"payment_type": "mobile",
"currency": "ETB",
"amount": 500
}

Key Response Parameters:

 status: Indicates whether the payment request was successful or failed.


o Possible values: success, failure, error
 payment_url: The URL where the customer is redirected to complete the payment. Your
system will redirect the user to this URL.
 order_id: The same order ID you sent in the request. This helps you associate the payment
with a specific order in your system.
 message: A human-readable message providing more details about the request (e.g., success or
failure).
 payment_type: Indicates the type of payment method (e.g., mobile).
 currency: The currency in which the payment was requested.
 amount: The total amount of money requested for payment.

Example of a Failed Response:


{
"status": "failure",
"message": "Invalid merchant_id or API key.",
"error_code": "400",
"order_id": "12345"
}
 status: Indicates that the request failed.
 message: Provides a description of the failure, such as invalid credentials, missing parameters,
etc.
 error_code: A specific code related to the error type.
 order_id: The order ID provided in the request, allowing you to identify the request even if it
failed.

3. Handling Telebirr API Responses in PHP

Once you receive a response from the Telebirr API, you need to handle it properly:

 If the status is success and a payment_url is returned, you will redirect the user to that URL for
payment completion.
 If the status is failure, you will need to handle the error and notify the user appropriately,
perhaps by showing an error message.

Handling a Successful Response:


if ($statusCode == 200 && isset($responseData['payment_url'])) {
header("Location: " . $responseData['payment_url']);
exit();
}

Handling an Error Response:


if ($statusCode !== 200 || isset($responseData['status']) &&
$responseData['status'] == 'failure') {
echo "Error: " . $responseData['message'];
}

4. Payment Status Callback (POST to Callback URL)

After the user completes the payment, Telebirr will send a POST request to your callback URL
to notify you about the payment status.

Example of the callback data sent by Telebirr (as a JSON payload):

{
"order_id": "12345",
"status": "success",
"amount": 500,
"currency": "ETB"
}

Callback Parameters:

 order_id: The unique ID of the order.


 status: The status of the payment (success, failure, etc.).
 amount: The amount of money that was paid.
 currency: The currency in which the payment was made.

You need to write a handler for this callback, verify the status, and update your system (e.g.,
mark the order as paid).

Conclusion

The integration of Telebirr’s payment API involves making a POST request to initiate the
payment, receiving a response with the payment URL, and handling the callback after the user
completes the payment. Understanding both the request and response structures is essential for
building a smooth payment flow in your system.

2/2

ChatGPT can make mistakes. Check important info.

You might also like