Download the PHP package melaku/telebirr without Composer

On this page you can find all versions of the php package melaku/telebirr. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?
melaku/telebirr
Rate from 1 - 5
Rated 1.00 based on 1 reviews

Informations about the package telebirr

Telebirr PHP Library (Web Checkout & In-App SDK)

GitHub branch checks state GitHub repo size GitHub issues Packagist Downloads Packagist Stars GitHub GitHub Repo stars GitHub forks GitHub commit activity GitHub last commit

A modern PHP library for integrating Telebirr Web Checkout (C2B) payments, and the server side of Telebirr In-App SDK payments for mobile apps. Telebirr is a mobile money service developed by Huawei and owned by Ethio telecom.

This library provides a simple, easy-to-use API for handling Telebirr payments, fully compliant with the Telebirr H5 C2B Web Payment Integration Guide.

πŸš€ Quick Start

Installation

Basic Usage

That's it! The library handles token management, order creation, and checkout URL generation automatically.

Merchant order id charset: a merch_orderid must match ^[A-Za-z0-9]+$ (ASCII letters and digits only β€” no -, `,.or spaces). Invalid ids now throw anInvalidParameterExceptioninstead of being silently rewritten. Pass null` to have a valid id generated for you, and read it back from the result.

Payee and payer (2.6.1+): every order carries payee_type "5000", payee_identifier (your merchantCode) and payee_identifier_type "04". If you know the customer's telebirr number, pass it as the last argument β€” $client->createCheckoutUrl('Order 123', '100.00', null, '0911223344') β€” and payer_type "1000", payer_identifier "251911223344" and payer_identifier_type "01" are sent too.

In-App SDK Payment

If your mobile app's Telebirr SDK initiates the payment instead of a browser redirect, use createInAppPayment(). There's no checkout URL for this flow β€” the receiveCode must be passed to the mobile SDK (native Android/iOS, or a Flutter plugin wrapping them) to continue the payment. This is the whole body of your app's "create order" endpoint:

Token management (with caching) is handled for you, as in createCheckoutUrl(). A runnable endpoint is in examples/inapp_create_order.php.

The rest of the flow is the same as web checkout: Telebirr POSTs the signed notification to your notifyUrl (see Handle Payment Notifications), and getOrderStatus($result->getMerchOrderId()) confirms the payment server-to-server. The result the mobile SDK hands your app is only a hint β€” it can be missing (an expired Telebirr session returns nothing) or wrong, so never fulfil on it alone.

Need the raw response or your own token handling? The lower-level createInAppOrder($fabricToken, $title, $amount) is still available and returns the full API response, with the code at $order['biz_content']['receiveCode'].

Upgrade to 2.5.0 if you create in-app orders. 2.4.0 and earlier sent trade_type: "InApp". The gateway accepts it and returns a receiveCode, but the Telebirr app then refuses the order with "The trade type is not filled in, or it is incorrect". 2.5.0 sends "Cross-App", confirmed with a paid order on the testbed.

πŸ“‹ Configuration

Required Credentials

You'll receive these from Telebirr:

Key formats β€” bare base64 is fine

Ethio Telecom issues merchant keys as bare base64 DER (a single long MIIEvgIBADANBgk… line, no -----BEGIN…----- armor). Pass it exactly as issued β€” the library normalizes it to PEM automatically, picking the right header (PKCS#8 vs PKCS#1) for you. Proper PEM works too, including PEM whose newlines were flattened to literal \n by a .env file.

Environment Setup

The library automatically uses the correct URLs based on environment:

Config::fromEnvironment() reads (any explicit option overrides its variable; $_ENV, $_SERVER, and getenv() are all checked, so it works under php-fpm/Laravel too):

Variable Maps to
TELEBIRR_ENVIRONMENT (then APP_ENV) environment
TELEBIRR_FABRIC_APP_ID fabricAppId
TELEBIRR_APP_SECRET appSecret
TELEBIRR_MERCHANT_APP_ID merchantAppId
TELEBIRR_MERCHANT_CODE merchantCode
TELEBIRR_PRIVATE_KEY privateKey (PEM or bare base64)
TELEBIRR_NOTIFY_URL notifyUrl
TELEBIRR_REDIRECT_URL redirectUrl
TELEBIRR_PUBLIC_KEY telebirrPublicKey

Default endpoints used by the library:

πŸ’‘ Key Features

πŸ“– Common Use Cases

Verify a payment (getOrderStatus)

The one-call, server-to-server way to confirm what actually happened to an order β€” the verification counterpart to createCheckoutUrl. Token handling and response mapping are done for you:

Handle Payment Return

Return-URL parameters (the raw contract)

Telebirr redirects the user's browser to your redirectUrl with these query parameters appended (snake_case):

Parameter Meaning
merch_order_id Your merchant order id, echoed back verbatim
payment_order_id Telebirr's transaction reference
trade_status e.g. PAY_SUCCESS, PAY_FAILED, PAY_CANCEL
total_amount Order amount
trans_currency Currency (ETB)
trans_end_time Transaction end time
sign, sign_type RSA-PSS signature over the other params

ReturnUrlHandler::handle() verifies the signature and maps these for you β€” the table is here for when you're debugging the raw redirect.

The idempotent settlement pattern (recommended)

The browser return and the server notification race β€” either can arrive first, both can arrive, and neither should be trusted on its own. The production-correct shape:

  1. On checkout, store a row keyed by merchOrderId with status='pending' and the expected amount.
  2. On both the return handler and the notify handler, call $client->getOrderStatus($merchOrderId) β€” never trust the callback params.
  3. Verify $status->paid === true and $status->amount matches your stored amount.
  4. Grant idempotently with a compare-and-set, so the racing paths can't double-fulfill:

Notification acknowledgement contract

Handle Payment Notifications

NotificationHandler::handle() is the recommended entry point β€” it parses, unwraps, verifies and extracts in one call, and fails closed by throwing on a missing or invalid signature.

The lower-level parse() / verify() / isPaymentSuccessful() / extractPaymentInfo() calls remain available and unchanged if you need the steps separately.

Notify parameters (the raw contract)

Telebirr POSTs a JSON body to your notifyUrl. It does not use the same conventions as the return URL β€” the differences below are handled for you, but they are the reason a hand-rolled notify handler tends to fail silently.

Parameter Meaning
merch_order_id Your merchant order id, echoed back verbatim
payment_order_id Telebirr's transaction reference
transId Short transaction id β€” the one on the customer's SMS receipt
trade_status Completed β€” not PAY_SUCCESS as on the return leg
total_amount Order amount
trans_currency Currency (ETB)
trans_end_time, notify_time Epoch milliseconds β€” the return URL sends Y-m-d H:i:s strings instead
merch_code, appid, notify_url Echoed back; part of the signed payload, so they must be kept when verifying
sign, sign_type RSA-PSS signature over the other params

Three consequences, all handled by handle():

Framework usage: instead of ->send(), build a native response, e.g. in Laravel: return response(json: $resp->getBody(), status: $resp->getStatusCode());

The three legs do not share a vocabulary

Telebirr describes the same payment differently depending on which leg reports it. The library normalizes all three, so isSuccess / OrderStatus::$paid and the extracted arrays mean the same thing everywhere β€” but the raw differences matter when you are reading gateway logs or debugging by hand:

Concept notify return URL queryOrder
status field trade_status trade_status order_status
success value Completed PAY_SUCCESS PAY_SUCCESS
transaction id transId (signed as trans_id) absent trans_id
timestamp field trans_end_time trans_end_time trans_time
timestamp format epoch milliseconds Y-m-d H:i:s Y-m-d H:i:s

ReturnUrlHandler::handle() and NotificationHandler::extractPaymentInfo() return the same keys, so settlement code does not need to know which leg it is holding. Fields a given leg does not carry come back as empty strings, and timestampUnix / notifyTimeUnix are null when the value is not an epoch rather than being guessed at.

What the signature check tolerates

Telebirr's own payloads are not internally consistent, and the library absorbs two specific discrepancies so you do not have to. Both only widen which string or which bytes are accepted as the signed material β€” every candidate is checked against the same public key, so forging one still requires Telebirr's private key.

If a signature you believe is genuine is still refused, the cause is almost always the public key rather than the payload: the key issued for the developer portal is not the key a production merchant signs with.

Query Order Status (low level)

Prefer getOrderStatus() above; the raw call remains available when you need the untouched response:

Check gateway health

The sandbox can be flaky; probe it before a user-facing checkout if you want to degrade gracefully:

Process Refund

πŸ”§ Requirements

βš™οΈ Advanced Configuration

TLS & timeouts

The default HTTP client verifies the gateway's TLS certificate and applies timeouts (a payment gateway must not be called over an unverified or unbounded connection).

The Telebirr test gateway serves an incomplete certificate chain (leaf only, missing intermediate), which used to fail verification with cURL error 60 and push people toward 'verifySsl' => false. The library now ships the gateway's CA chain (src/certs/telebirr-ca.pem): when system-store verification fails with error 60 and no custom bundle was supplied, the request is retried once against the bundled chain β€” so verification works out of the box. The bundled chain can only validate hosts issued under it (the Telebirr gateways); it never loosens verification for anything else. If verification still fails, the error explains the options.

Token caching

createCheckoutUrl() and getOrderStatus() cache the fabric token until its expirationDate (minus a 60s safety margin) within the client instance and reuse it, saving a gateway round-trip whenever one request performs several calls (e.g. a settle path). A rejected token (HTTP 401) drops the cache automatically. Note PHP's request lifecycle: the cache does not persist across requests. Opt out for strictly stateless behavior:

applyFabricToken() always performs a real network call (and refreshes the cache), so existing manual flows are unaffected.

Retrying transient gateway errors

The test gateway regularly throws transient infra errors (see the sandbox note below). Retry is opt-in with exponential backoff:

Only failures where ApiException::isTransient() is true are retried: known Telebirr infra codes (49401024991 "southbound service unavailable"), HTTP 502/503/504, and cURL timeouts/connection drops. Parameter or auth errors fail immediately. The code list is ApiException::TRANSIENT_TELEBIRR_ERROR_CODES.

PSR-3 logging

Injecting a custom HTTP client (testing)

The third constructor argument accepts any Melaku\Telebirr\Http\HttpClientInterface, so you can unit-test without hitting the network:

Catching errors

Every exception the library throws implements Melaku\Telebirr\Exceptions\TelebirrExceptionInterface, so you can catch them all in one place. API failures throw ApiException, which now carries Telebirr's parsed error envelope β€” no more json_decode($e->getResponseBody()):

Amounts & rounding

amount accepts string|int|float and is formatted to exactly 2 decimals β€” Telebirr's wire format for ETB. If you store amounts in minor units (cents), divide before passing ($cents / 100). Prefer passing a string ('100.50') when the value came from user input or a DB decimal column, sidestepping binary floating-point surprises.

⚠️ Sandbox instability

The test gateway is frequently unstable and returns transient infra errors that look exactly like integration bugs β€” most commonly:

If your request worked before and suddenly throws a 4940… code with an errorSolution suggesting a retry, it's the gateway, not your code. Wait and retry (or enable the retry option above). Don't spend an hour debugging a correct integration.

πŸ“š Documentation

For detailed documentation, API reference, and advanced usage examples, visit our documentation site:

πŸ”— Full Documentation (Coming Soon)

The documentation includes:

πŸ› οΈ Helper Classes

The library provides several helper classes to simplify common tasks:

πŸ”’ Security Notes

🀝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

πŸ“„ License

This project is licensed under the MIT License.

πŸ”— Links


Need help? Check out the full documentation or open an issue on GitHub.


All versions of telebirr with dependencies

PHP Build Version
Package Version
Requires php Version >=7.4.0
ext-curl Version *
ext-json Version *
ext-openssl Version *
phpseclib/phpseclib Version ^3.0
psr/log Version ^1.1 || ^2.0 || ^3.0
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package melaku/telebirr contains the following files

Loading the files please wait ...