albertoadolfo27 / mpesa_sdk
unofficial Vodacom M-Pesa SDK
README
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
composer require albertoadolfo27/mpesa_sdk
Requisitos
- PHP 8.0+
- Extensão
openssl
habilitada - Chave pública fornecida pela Vodacom
- API Key válida
Como Usar
1. Instanciar a SDK
use MpesaSdk\MPesa; $mpesa = new MPesa( apiKey: 'SUA_API_KEY', publicKey: 'CHAVE_PUBLICA_DA_VODACOM' );
2. Enviar pagamento C2B
$response = $mpesa->customerToBusiness( transactionReference: 'REF123456', customerNumber: '25884XXXXXXX', amount: '100', thirdPartyReference: 'MEU_REF_INTERNO' );
3. Pagamento B2C
$response = $mpesa->businessToCustomer( transactionReference: 'REF789', customerNumber: '25884XXXXXXX', amount: '250', thirdPartyReference: 'REFCLIENTE123', businessCode: '171717' );
4. Pagamento B2B
$response = $mpesa->businessToBusiness( transactionReference: 'REFXYZ', amount: '500', thirdPartyReference: 'REFB2B001', primaryBusinessCode: '171717', receiverBusinessCode: '123456' );
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
$response = $mpesa->transactionStatus( thirdPartyReference: 'REF001', queryReference: 'TX123456789', businessCode: '171717' );
7. Consultar nome do cliente
$response = $mpesa->customerName( customerNumber: '25884XXXXXXX', businessCode: '171717', thirdPartyReference: 'NOMECONSULTA001' );
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
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:
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
Constante | Código | Descrição |
---|---|---|
SUCCESS | INS-0 | Transação bem-sucedida |
CREATED | INS-0 | Transação criada com sucesso |
INTERNAL_ERROR | INS-1 | Erro interno |
INVALID_API_KEY | INS-2 | Chave de API inválida |
USER_NOT_ACTIVE | INS-4 | Usuário não está ativo |
TRANSACTION_CANCELLED | INS-5 | Transação cancelada |
TRANSACTION_FAILED | INS-6 | Falha na transação |
REQUEST_TIMEOUT | INS-9 | Tempo limite excedido |
DUPLICATE_TRANSACTION | INS-10 | Transação duplicada |
INVALID_SHORTCODE | INS-13 | Código de serviço inválido |
INVALID_REFERENCE | INS-14 | Referência inválida |
INVALID_AMOUNT | INS-15 | Valor inválido |
TEMPORARY_OVERLOAD | INS-16 | Sobrecarga temporária |
INVALID_TRANSACTION_REF | INS-17 | Referência de transação inválida |
INVALID_TRANSACTION_ID | INS-18 | ID da transação inválido |
INVALID_THIRD_PARTY_REF | INS-19 | Referência de terceiro inválida |
MISSING_PARAMETERS | INS-20 | Parâmetros ausentes |
PARAMETER_VALIDATION_FAILED | INS-21 | Validação de parâmetro falhou |
INVALID_OPERATION_TYPE | INS-22 | Tipo de operação inválida |
UNKNOWN_STATUS | INS-23 | Status desconhecido |
INVALID_INITIATOR_ID | INS-24 | ID do iniciador inválido |
INVALID_CREDENTIAL | INS-25 | Credencial inválida |
NOT_AUTHORIZED | INS-26 | Não autorizado |
DIRECT_DEBIT_MISSING | INS-993 | Débito direto ausente |
DIRECT_DEBIT_EXISTS | INS-994 | Débito direto já existe |
CUSTOMER_PROFILE_ISSUE | INS-995 | Problemas com perfil do cliente |
ACCOUNT_NOT_ACTIVE | INS-996 | Conta inativa |
LINKING_TRANSACTION_MISSING | INS-997 | Transação de vinculação ausente |
INVALID_MARKET | INS-998 | Mercado inválido |
INITIATOR_AUTH_ERROR | INS-2001 | Erro de autenticação do iniciador |
INVALID_RECEIVER | INS-2002 | Destinatário inválido |
INSUFFICIENT_BALANCE | INS-2006 | Saldo insuficiente |
INVALID_MSISDN | INS-2051 | Número MSISDN inválido |
INVALID_LANGUAGE_CODE | INS-2057 | Código de idioma inválido |
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:
use MpesaSdk\MPesa; $uniqueReference = MPesa::generateUniqueReference();
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
- Testes unitários com PHPUnit
- Implementar suporte a webhooks
Autor
Alberto Jordane Adolfo
Alberto Jordane Adolfo
Licença
Este projeto está licenciado sob a licença MIT.
EN
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
composer require albertoadolfo27/mpesa_sdk
Requirements
- PHP 8.0+
openssl
extension enabled- Public key provided by Vodacom
- Valid API Key
How to Use
1. Instantiate the SDK
use MpesaSdk\MPesa; $mpesa = new MPesa( apiKey: 'YOUR_API_KEY', publicKey: 'VODACOM_PUBLIC_KEY' );
2. Send C2B Payment
$response = $mpesa->customerToBusiness( transactionReference: 'REF123456', customerNumber: '25884XXXXXXX', amount: '100', thirdPartyReference: 'MY_INTERNAL_REF' );
3. B2C Payment
$response = $mpesa->businessToCustomer( transactionReference: 'REF789', customerNumber: '25884XXXXXXX', amount: '250', thirdPartyReference: 'CLIENTREF123', businessCode: '171717' );
4. B2B Payment
$response = $mpesa->businessToBusiness( transactionReference: 'REFXYZ', amount: '500', thirdPartyReference: 'REFB2B001', primaryBusinessCode: '171717', receiverBusinessCode: '123456' );
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
$response = $mpesa->transactionStatus( thirdPartyReference: 'REF001', queryReference: 'TX123456789', businessCode: '171717' );
7. Get Customer Name
$response = $mpesa->customerName( customerNumber: '25884XXXXXXX', businessCode: '171717', thirdPartyReference: 'NAMEQUERY001' );
Response Codes
All methods return an object like:
[ 'httpCode' => 200, 'responseCode' => 'INS-0', 'responseDescription' => 'Request processed successfully', 'transactionID' => '...', 'thirdPartyReference' => '...' ]
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:
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
(The HTML table you asked for earlier contains the full list.)
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:
use MpesaSdk\MPesa; $uniqueReference = MPesa::generateUniqueReference();
Project Structure
src/ ├── MPesa.php # Main SDK class ├── MPesaResponse.php # Response formatting └── MPesaResponseCode.php # List of all response codes
To-Do
- Unit tests with PHPUnit
- Webhook support
Author
Alberto Jordane Adolfo
Alberto Jordane Adolfo
License
This project is licensed under the MIT license.