PHPackages                             albertoadolfo27/mpesa\_sdk - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Payment Processing](/categories/payments)
4. /
5. albertoadolfo27/mpesa\_sdk

ActiveLibrary[Payment Processing](/categories/payments)

albertoadolfo27/mpesa\_sdk
==========================

unofficial Vodacom M-Pesa SDK

v1.0.0(1y ago)011MITPHP

Since Apr 19Pushed 7mo ago1 watchersCompare

[ Source](https://github.com/AlbertoAdolfo27/mpesa_sdk)[ Packagist](https://packagist.org/packages/albertoadolfo27/mpesa_sdk)[ RSS](/packages/albertoadolfo27-mpesa-sdk/feed)WikiDiscussions main Synced today

READMEChangelog (1)DependenciesVersions (2)Used By (0)

PT
==

[](#pt)

M-Pesa SDK PHP (Não Oficial)
============================

[](#m-pesa-sdk-php-não-oficial)

SDK não oficial para integração com a API da Vodacom M-Pesa Moçambique, desenvolvido em PHP.

> Suporte a operações C2B, B2C, B2B, Reversão, Consulta de Transações e Consulta de Nome do Cliente.

---

Instalação
----------

[](#instalação)

```
composer require albertoadolfo27/mpesa_sdk
```

---

Requisitos
----------

[](#requisitos)

- PHP 8.0+
- Extensão `openssl` habilitada
- API Key válida fornecida pela MPESA
- Chave pública fornecida pela MPESA

---

Como Usar
---------

[](#como-usar)

### 1. Instanciar a SDK

[](#1-instanciar-a-sdk)

```
use MpesaSdk\MPesa;

$mpesa = new MPesa(
    apiKey: 'SUA_API_KEY',
    publicKey: 'CHAVE_PUBLICA_DA_VODACOM',
    origin: "*", // Argumento opcional. Valor padrão: '*'
    verifySSL: true // Argumento opcional. Valor padrão: true
);
```

### 2. Enviar pagamento C2B

[](#2-enviar-pagamento-c2b)

```
$response = $mpesa->customerToBusiness(
    transactionReference: 'REF123456',
    customerNumber: '25884XXXXXXX',
    amount: '100',
    thirdPartyReference: 'MEU_REF_INTERNO'
);
```

### 3. Pagamento B2C

[](#3-pagamento-b2c)

```
$response = $mpesa->businessToCustomer(
    transactionReference: 'REF789',
    customerNumber: '25884XXXXXXX',
    amount: '250',
    thirdPartyReference: 'REFCLIENTE123',
    businessCode: '171717'
);
```

### 4. Pagamento B2B

[](#4-pagamento-b2b)

```
$response = $mpesa->businessToBusiness(
    transactionReference: 'REFXYZ',
    amount: '500',
    thirdPartyReference: 'REFB2B001',
    primaryBusinessCode: '171717',
    receiverBusinessCode: '123456'
);
```

### 5. Reverter uma transação

[](#5-reverter-uma-transação)

```
$response = $mpesa->reversal(
    transactionID: 'TX123456789',
    securityCredential: 'SEU_CREDENCIAL_SEGURANCA',
    initiatorIdentifier: 'INICIADOR',
    thirdPartyReference: 'REF001',
    businessCode: '171717',
    amount: '100'
);
```

### 6. Consultar transação

[](#6-consultar-transação)

```
$response = $mpesa->transactionStatus(
    thirdPartyReference: 'REF001',
    queryReference: 'TX123456789',
    businessCode: '171717'
);
```

### 7. Consultar nome do cliente

[](#7-consultar-nome-do-cliente)

```
$response = $mpesa->customerName(
    customerNumber: '25884XXXXXXX',
    businessCode: '171717',
    thirdPartyReference: 'NOMECONSULTA001'
);
```

Códigos de Resposta
-------------------

[](#códigos-de-resposta)

Todos os métodos retornam um objeto contendo:

```
[
  'httpCode' => 200,
  'responseCode' => 'INS-0',
  'responseDescription' => 'Request processed successfully',
  'transactionID' => '...',
  'thirdPartyReference' => '...'
]
```

### Verificando o Código de Resposta

[](#verificando-o-código-de-resposta)

O SDK define uma série de constantes na classe `MPesaResponseCode` para facilitar a verificação dos códigos de resposta retornados pela API. Isso torna seu código mais legível e seguro contra erros de digitação.

#### Exemplo de Uso:

[](#exemplo-de-uso)

```
use MpesaSdk\MPesaResponseCode;

$response = $mpesa->customerToBusiness(
    transactionReference: "TX123456",
    customerNumber: "841234567",
    amount: "100",
    thirdPartyReference: MPesa::generateUniqueReference()
);

if ($response->responseCode === MPesaResponseCode::SUCCESS) {
    echo "Transação realizada com sucesso!";
} else {
    echo "Erro: " . ($response->responseDescription ?? 'Erro desconhecido');
}
```

### Aqui está a tabela de códigos de resposta da classe MPesaResponseCode

[](#aqui-está-a-tabela-de-códigos-de-resposta-da-classe-mpesaresponsecode)

   Constante Código Descrição    SUCCESSINS-0Transação bem-sucedida CREATEDINS-0Transação criada com sucesso INTERNAL\_ERRORINS-1Erro interno INVALID\_API\_KEYINS-2Chave de API inválida USER\_NOT\_ACTIVEINS-4Usuário não está ativo TRANSACTION\_CANCELLEDINS-5Transação cancelada TRANSACTION\_FAILEDINS-6Falha na transação REQUEST\_TIMEOUTINS-9Tempo limite excedido DUPLICATE\_TRANSACTIONINS-10Transação duplicada INVALID\_SHORTCODEINS-13Código de serviço inválido INVALID\_REFERENCEINS-14Referência inválida INVALID\_AMOUNTINS-15Valor inválido TEMPORARY\_OVERLOADINS-16Sobrecarga temporária INVALID\_TRANSACTION\_REFINS-17Referência de transação inválida INVALID\_TRANSACTION\_IDINS-18ID da transação inválido INVALID\_THIRD\_PARTY\_REFINS-19Referência de terceiro inválida MISSING\_PARAMETERSINS-20Parâmetros ausentes PARAMETER\_VALIDATION\_FAILEDINS-21Validação de parâmetro falhou INVALID\_OPERATION\_TYPEINS-22Tipo de operação inválida UNKNOWN\_STATUSINS-23Status desconhecido INVALID\_INITIATOR\_IDINS-24ID do iniciador inválido INVALID\_CREDENTIALINS-25Credencial inválida NOT\_AUTHORIZEDINS-26Não autorizado DIRECT\_DEBIT\_MISSINGINS-993Débito direto ausente DIRECT\_DEBIT\_EXISTSINS-994Débito direto já existe CUSTOMER\_PROFILE\_ISSUEINS-995Problemas com perfil do cliente ACCOUNT\_NOT\_ACTIVEINS-996Conta inativa LINKING\_TRANSACTION\_MISSINGINS-997Transação de vinculação ausente INVALID\_MARKETINS-998Mercado inválido INITIATOR\_AUTH\_ERRORINS-2001Erro de autenticação do iniciador INVALID\_RECEIVERINS-2002Destinatário inválido INSUFFICIENT\_BALANCEINS-2006Saldo insuficiente INVALID\_MSISDNINS-2051Número MSISDN inválido INVALID\_LANGUAGE\_CODEINS-2057Código de idioma inválido ---

Gerando Referência Única
------------------------

[](#gerando-referência-única)

Para facilitar a criação de uma referência única a ser usada no parâmetro `thirdPartyReference`, o SDK oferece o método auxiliar:

```
$uniqueReference = MPesa::generateUniqueReference();
```

Estrutura do Projeto
--------------------

[](#estrutura-do-projeto)

```
src/
├── MPesa.php              # Classe principal da SDK
├── MPesaResponse.php      # Formatação de resposta
└── MPesaResponseCode.php  # Lista de todos os códigos de resposta
```

---

To-Do
-----

[](#to-do)

- Testes unitários com PHPUnit
- Implementar suporte a webhooks

---

Autor
-----

[](#autor)

**Alberto Jordane Adolfo**
[Alberto Jordane Adolfo](https://github.com/AlbertoAdolfo27)

---

Licença
-------

[](#licença)

Este projeto está licenciado sob a licença MIT.

---

EN
==

[](#en)

M-Pesa PHP SDK (Unofficial)
===========================

[](#m-pesa-php-sdk-unofficial)

Unofficial SDK for integrating with the Vodacom M-Pesa Mozambique API, built in PHP.

> Supports C2B, B2C, B2B operations, Reversal, Transaction Status, and Customer Name Lookup.

---

Installation
------------

[](#installation)

```
composer require albertoadolfo27/mpesa_sdk
```

---

Requirements
------------

[](#requirements)

- PHP 8.0+
- `openssl` extension enabled
- Valid API Key provided by MPESA
- Public key provided by MPESA

---

How to Use
----------

[](#how-to-use)

### 1. Instantiate the SDK

[](#1-instantiate-the-sdk)

```
use MpesaSdk\MPesa;

$mpesa = new MPesa(
    apiKey: 'YOUR_API_KEY',
    publicKey: 'VODACOM_PUBLIC_KEY',
    origin: "*", // Optional argument. Default value: '*'
    verifySSL: true // Optional argument. Defaut value: true
);
```

### 2. Send C2B Payment

[](#2-send-c2b-payment)

```
$response = $mpesa->customerToBusiness(
    transactionReference: 'REF123456',
    customerNumber: '25884XXXXXXX',
    amount: '100',
    thirdPartyReference: 'MY_INTERNAL_REF'
);
```

### 3. B2C Payment

[](#3-b2c-payment)

```
$response = $mpesa->businessToCustomer(
    transactionReference: 'REF789',
    customerNumber: '25884XXXXXXX',
    amount: '250',
    thirdPartyReference: 'CLIENTREF123',
    businessCode: '171717'
);
```

### 4. B2B Payment

[](#4-b2b-payment)

```
$response = $mpesa->businessToBusiness(
    transactionReference: 'REFXYZ',
    amount: '500',
    thirdPartyReference: 'REFB2B001',
    primaryBusinessCode: '171717',
    receiverBusinessCode: '123456'
);
```

### 5. Reverse a Transaction

[](#5-reverse-a-transaction)

```
$response = $mpesa->reversal(
    transactionID: 'TX123456789',
    securityCredential: 'YOUR_SECURITY_CREDENTIAL',
    initiatorIdentifier: 'INITIATOR',
    thirdPartyReference: 'REF001',
    businessCode: '171717',
    amount: '100'
);
```

### 6. Check Transaction Status

[](#6-check-transaction-status)

```
$response = $mpesa->transactionStatus(
    thirdPartyReference: 'REF001',
    queryReference: 'TX123456789',
    businessCode: '171717'
);
```

### 7. Get Customer Name

[](#7-get-customer-name)

```
$response = $mpesa->customerName(
    customerNumber: '25884XXXXXXX',
    businessCode: '171717',
    thirdPartyReference: 'NAMEQUERY001'
);
```

Response Codes
--------------

[](#response-codes)

All methods return an object like:

```
[
  'httpCode' => 200,
  'responseCode' => 'INS-0',
  'responseDescription' => 'Request processed successfully',
  'transactionID' => '...',
  'thirdPartyReference' => '...'
]
```

---

### Checking the Response Code

[](#checking-the-response-code)

The SDK defines a set of constants in the `MPesaResponseCode` class to simplify checking the response codes returned by the API. This makes your code more readable and helps prevent typos.

#### Example:

[](#example)

```
use MpesaSdk\MPesaResponseCode;

$response = $mpesa->customerToBusiness(
    transactionReference: "TX123456",
    customerNumber: "841234567",
    amount: "100",
    thirdPartyReference: MPesa::generateUniqueReference()
);

if ($response->responseCode === MPesaResponseCode::SUCCESS) {
    echo "Transaction completed successfully!";
} else {
    echo "Error: " . ($response->responseDescription ?? 'Unknown error');
}
```

### See the Full List of Response Codes from MPesaResponseCode

[](#see-the-full-list-of-response-codes-from-mpesaresponsecode)

   Constant Code Description    SUCCESSINS-0Successful transaction CREATEDINS-0Transaction created successfully INTERNAL\_ERRORINS-1Internal error INVALID\_API\_KEYINS-2Invalid API key USER\_NOT\_ACTIVEINS-4User is not active TRANSACTION\_CANCELLEDINS-5Transaction cancelled TRANSACTION\_FAILEDINS-6Transaction failed REQUEST\_TIMEOUTINS-9Request timeout DUPLICATE\_TRANSACTIONINS-10Duplicate transaction INVALID\_SHORTCODEINS-13Invalid service code INVALID\_REFERENCEINS-14Invalid reference INVALID\_AMOUNTINS-15Invalid amount TEMPORARY\_OVERLOADINS-16Temporary overload INVALID\_TRANSACTION\_REFINS-17Invalid transaction reference INVALID\_TRANSACTION\_IDINS-18Invalid transaction ID INVALID\_THIRD\_PARTY\_REFINS-19Invalid third-party reference MISSING\_PARAMETERSINS-20Missing parameters PARAMETER\_VALIDATION\_FAILEDINS-21Parameter validation failed INVALID\_OPERATION\_TYPEINS-22Invalid operation type UNKNOWN\_STATUSINS-23Unknown status INVALID\_INITIATOR\_IDINS-24Invalid initiator ID INVALID\_CREDENTIALINS-25Invalid credential NOT\_AUTHORIZEDINS-26Not authorized DIRECT\_DEBIT\_MISSINGINS-993Direct debit missing DIRECT\_DEBIT\_EXISTSINS-994Direct debit already exists CUSTOMER\_PROFILE\_ISSUEINS-995Customer profile issues ACCOUNT\_NOT\_ACTIVEINS-996Inactive account LINKING\_TRANSACTION\_MISSINGINS-997Linking transaction missing INVALID\_MARKETINS-998Invalid market INITIATOR\_AUTH\_ERRORINS-2001Initiator authentication error INVALID\_RECEIVERINS-2002Invalid receiver INSUFFICIENT\_BALANCEINS-2006Insufficient balance INVALID\_MSISDNINS-2051Invalid MSISDN number INVALID\_LANGUAGE\_CODEINS-2057Invalid language code ---

Generating a Unique Reference
-----------------------------

[](#generating-a-unique-reference)

To easily generate a unique value to be used in the `thirdPartyReference` parameter, you can use the helper method provided by the SDK:

```
$uniqueReference = MPesa::generateUniqueReference();
```

---

Project Structure
-----------------

[](#project-structure)

```
src/
├── MPesa.php              # Main SDK class
├── MPesaResponse.php      # Response formatting
└── MPesaResponseCode.php  # List of all response codes
```

---

To-Do
-----

[](#to-do-1)

- Unit tests with PHPUnit
- Webhook support

---

Author
------

[](#author)

**Alberto Jordane Adolfo**
[Alberto Jordane Adolfo](https://github.com/AlbertoAdolfo27)

---

License
-------

[](#license)

This project is licensed under the MIT license.

###  Health Score

27

—

LowBetter than 47% of packages

Maintenance55

Moderate activity, may be stable

Popularity5

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity37

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

440d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/22469867?v=4)[Alberto Jordane Adolfo](/maintainers/AlbertoAdolfo27)[@AlbertoAdolfo27](https://github.com/AlbertoAdolfo27)

---

Top Contributors

[![AlbertoAdolfo27](https://avatars.githubusercontent.com/u/22469867?v=4)](https://github.com/AlbertoAdolfo27 "AlbertoAdolfo27 (9 commits)")

### Embed Badge

![Health badge](/badges/albertoadolfo27-mpesa-sdk/health.svg)

```
[![Health](https://phpackages.com/badges/albertoadolfo27-mpesa-sdk/health.svg)](https://phpackages.com/packages/albertoadolfo27-mpesa-sdk)
```

###  Alternatives

[omnipay/coinbase

Coinbase driver for the Omnipay payment processing library

18579.5k1](/packages/omnipay-coinbase)[msilabs/bkash

bKash Payment Gateway API for Laravel Framework.

181.2k](/packages/msilabs-bkash)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
