Giter VIP home page Giter VIP logo

laravel-mtn-momo's Introduction

Laravel MTM MOMO API Integration

Total Downloads Latest Stable Version License Code Quality Code Coverage Tests Documentation

Introduction

This package helps you integrate the MTN MOMO API into your Laravel application. It provides a wrapper around the core MTN MOMO API services, leaving you to worry about other parts of your application.

To get started, install the package via the Composer package manager:

Laravel Package Installation
^6.0 2.0 composer require bmatovu/laravel-mtn-momo ^2.0
^7.0 3.0 composer require bmatovu/laravel-mtn-momo ^3.0
^8.0 ... ^10.0 master composer require bmatovu/laravel-mtn-momo

Configuration customization

If you wish to customize the default configurations, you may export the default configuration using

php artisan vendor:publish --provider="Bmatovu\MtnMomo\MtnMomoServiceProvider" --tag="config"

Database Migration

The package service provider registers it's own database migrations with the framework, so you should migrate your database after installation. The migration will create a tokens tables your application needs to store access tokens from MTN MOMO API.

php artisan migrate

Prerequisites

You will need the following to get started with you integration...

  1. Create a developer account with MTN MOMO.
  2. Subscribe to a product/service that you wish to consume.

If you already subscribed to a product, the subscription key can be found in your profile.

Getting started (Sandbox)

Register your client details.

php artisan mtn-momo:init

Next you need to register your client app ID.

php artisan mtn-momo:register-id

You may want to verify your client ID at this stage

php artisan mtn-momo:validate-id

Then request for a client secret (key).

php artisan mtn-momo:request-secret

Usage

use Bmatovu\MtnMomo\Products\Collection;

$collection = new Collection();

$referenceId = $collection->requestToPay('yourTransactionId', '46733123454', 100);

See test numbers

Exception handling

use Bmatovu\MtnMomo\Products\Collection;
use Bmatovu\MtnMomo\Exceptions\CollectionRequestException;

try {
    $collection = new Collection();
    
    $referenceId = $collection->requestToPay('yourTransactionId', '46733123453', 100);
} catch(CollectionRequestException $e) {
    do {
        printf("\n\r%s:%d %s (%d) [%s]\n\r", 
            $e->getFile(), $e->getLine(), $e->getMessage(), $e->getCode(), get_class($e));
    } while($e = $e->getPrevious());
}

Collection

  1. Collect money

    $collection->requestToPay($yourTransactionId, $partyId, $amount)
  2. Check transaction status

    $collection->getTransactionStatus($referenceId)
  3. Check account balance

    $collection->getAccountBalance()
  4. Check account status

    $collection->isActive($partyId)
  5. Get OAuth token

    $collection->getToken()
  6. Get Account Holder Info

    $collection->getAccountHolderBasicInfo($partyId)

Disbursement

  1. Disburse money

    $disbursement->transfer($yourTransactionId, $partyId, $amount)
  2. Check transaction status

    $disbursement->getTransactionStatus($referenceId)
  3. Check account balance

    $disbursement->getAccountBalance()
  4. Check account status

    $disbursement->isActive($partyId)
  5. Get OAuth token

    $disbursement->getToken()
  6. Get Account Holder Info

    $disbursement->getAccountHolderBasicInfo($partyId)

Remittance

  1. Remit money

    $remittance->transfer($yourTransactionId, $partyId, $amount)
  2. Check transaction status

    $remittance->getTransactionStatus($referenceId)
  3. Check account balance

    $remittance->getAccountBalance()
  4. Check account status

    $remittance->isActive($partyId)
  5. Get OAuth token

    $remittance->getToken()
  6. Get Account Holder Info

    $remittance->getAccountHolderBasicInfo($partyId)

Go live

You will need to make some changes to your setup before going live. Read more.

Support Groups

Join MTN's Skype & WhatsApp support groups. Here

Reporting bugs

If you've stumbled across a bug, please help us by leaving as much information about the bug as possible, e.g.

  • Steps to reproduce
  • Expected result
  • Actual result

This will help us to fix the bug as quickly as possible, and if you wish to fix it yourself feel free to fork the package and submit a pull request!

laravel-mtn-momo's People

Contributors

alhaji-aki avatar hamzamugabo avatar mtvbrianking avatar muluhgodson avatar spekulatius avatar stevebaros avatar yondifon avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

laravel-mtn-momo's Issues

Remittance dont work in tinker

I want to use the transfer of funds from mtn with your package, instead collection when I put remittance it does not work in tinker.

I work with laravel, here is a part of my controller:

namespace App\Http\Controllers;
use Bmatovu\MtnMomo\Products\Remittance;
use Bmatovu\MtnMomo\Exceptions\RemittanceRequestException;
use Illuminate\Http\Request;

class MomoController extends Controller
{
try {
$remittance = new Remittance();

    // Request a user to pay
    $momoTransactionId = $remitance->transact('transactionId', '07XXXXXXXX', 100);
} catch(RemittanceRequestException $e) {
    do {
        printf("\n\r%s:%d %s (%d) [%s]\n\r",
            $e->getFile(), $e->getLine(), $e->getMessage(), $e->getCode(), get_class($e));
    } while($e = $e->getPrevious());
}

thank you in advance

Error on Laravel 6.1.*

in the previous versions of laravel, the arrays were showin number on running
php artisan mtn-momo:init,

but in Laravel 6.1.*, i get this error when selecting the currency and the product.

Use 'EUR' for sandbox environment

?[32mMOMO_CURRENCY?[39m [?[33mEUR?[39m]:

?[1mProduct?[22m

?[32mMOMO_PRODUCT?[39m [?[33mcollection?[39m]:
[?[33m0?[39m] collection
[?[33m1?[39m] disbursement
[?[33m2?[39m] remittance

issue

Callback URI

Callback URI always return Invalid URI. #IETF RFC3986.
eg. 'http:127.0.0.1:8000/callback/'

400 Bad Request response

Whenever i use the $collection->requestToPay($transactionId, $partyId, $amount) i get an exception. when i print the exception it states a 400 bad request . Here is the exception
\vendor\guzzlehttp\guzzle\src\Exception\RequestException.php:113 Client error: POST https://ericssonbasicapi1.azure-api.net/collection/v1_0/requesttopay` resulted in a 400 Bad Request response (400) [GuzzleHttp\Exception\ClientException]`

Am wondering what could be the possible causes of that. despite being able to verify the a telephone number is active using this
$collection->isActive($partyId) without any excepitons

Transfer unsuccessful. (0)

var/www/html/e-guot/vendor/bmatovu/laravel-mtn-momo/src/Products/Remittance.php:218 Transfer unsuccessful. (0) [Bmatovu\MtnMomo\Exceptions\RemittanceRequestException] /var/www/html/e-guot/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php:113 Client error: POST https://sandbox.momodeveloper.mtn.com/remittance/v1_0/transfer resulted in a 400 Bad Request response (400) [GuzzleHttp\Exception\ClientException]

Access denied

Status: 401 Access Denied

Body: { "statusCode": 401, "message": "Access denied due to invalid subscription key. Make sure to provide a valid key for an active subscription." }
please am getting access denied due to invalid subscription key... even though the key provided is correct

Need a guidance

Hello, I have been using Paystack for some times but now want to try MoMo API for our new project and I tried this package and done with the setup. But when trying to run it, an error threw saying Call to a member function isPast() on string even thought the token has been generated after the setup. I am totally new to MoMo API so if you know any tutorials in relation to this package for me to learn, please share it with me. Thanks :).

Dynamic currency

I want to be able to pass the currency in parameter of the method "transact". Can you please add this functionality? I think is more flexible than just hard writing it in the .env file.

Package Installing Error.

Hello,

  • I am implementing the mtn payment system with the laravel. But I am getting troubles with installing the package using this command.

  • Please have a look at this screenshot. https://prnt.sc/w5ct5b

  • So can you please help me with this.

Thanks

During the registration of client id, i get this error

GuzzleHttp\Exception\RequestException : cURL error 60: SSL certificate problem: unable to get local issuer certificate (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)

at \vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php:201
197|
198| // Create a connection exception if it was a specific error code.
199| $error = isset($connectionErrors[$easy->errno])
200| ? new ConnectException($message, $easy->request, null, $ctx)

201| : new RequestException($message, $easy->request, $easy->response, null, $ctx);
202|
203| return \GuzzleHttp\Promise\rejection_for($error);
204| }
205|

Exception trace:

1 GuzzleHttp\Handler\CurlFactory::createRejection(Object(GuzzleHttp\Handler\EasyHandle))
vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php:155

2 GuzzleHttp\Handler\CurlFactory::finishError(Object(GuzzleHttp\Handler\CurlHandler), Object(GuzzleHttp\Handler\EasyHandle), Object(GuzzleHttp\Handler\CurlFactory))
vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php:105

Add support for Lumen.

After adding the library and manually registering the provider
in production, it fires 500 indicating missing files.

My question is, does it fully support lumen or i need to get my hands a little more dirty ?

Add support for using multiple products in the same application.

Hye, great work here by the way.

I would like to use both disbursements and collections but during the setup, you can only choose one product. Is there a way to do this? is it currently possible?

I get
Bmatovu \ OAuthNegotiator \ Exceptions \ TokenRequestException Unable to obtain a new access token. when I try to use a second product after the first one have been registered.

Thanks

400 Bad Request

Callback URL

  • If the X-Callback-Url header is present, it can't be empty
  • A wrong callback URL will result in an error

Sandbox
Your Callback URL host must match the ProviderCallbackHost you registered.
You can validate the latter using the ValidateApiUserId endpoint.

Live
You must register your callback URL on the MTN Partner Portal first.
You may need to write to your MTN account manager to allow / whitelist your callback host - in case you're not receiving callback, but collections are successful

Call to undefined method requestTopay()

i get this error Symfony\Component\Debug\Exception\FatalThrowableError: Call to undefined method Bmatovu\MtnMomo\Products\Collection::requestToPay() in file.
am using laravel 6, i checked the collection class and that method is missing

Can't install it on Laravel ^9.2

Step to reproduce

  • laravel new test
  • cd test
  • composer require bmatovu/laravel-mtn-momo

And got :

Your requirements could not be resolved to an installable set of packages.

Problem 1
- bmatovu/laravel-mtn-momo[v4.1.0, ..., 4.x-dev] require illuminate/console ^8.0 -> found illuminate/console[v8.0.0, ..., 8.x-dev] but these were not loaded, likely because it conflicts with another require.
- Root composer.json requires bmatovu/laravel-mtn-momo ^4.1 -> satisfiable by bmatovu/laravel-mtn-momo[v4.1.0, 4.x-dev].

Installation failed, reverting ./composer.json and ./composer.lock to their original content.


Screenshot :
https://pic.li/i/Zf3H

Unable to obtain a new access token

I getting this error when try to get balance or request to pay on live environment

Bmatovu\OAuthNegotiator\Exceptions\TokenRequestException {#1492 ▼
#message: "Unable to obtain a new access token."
#code: 0
#file: "/home/orionass/orionpay/vendor/bmatovu/oauth-negotiator/src/OAuth2Middleware.php"
#line: 275
trace: {▶}
}

Default to mtn naming conversion.

Redirect URI -> Callback URI

Client ID -> apiUser

Client Secret -> apiKey

$collection->transact(...) => $collection->requestToPay(...)

PayerMessage and PayeeNote are required.

From a user in production.

If either PayerMessage or PayeeNote is empty, you will get an Internal Server Error.

TODO:

Improve Collection::requestToPay to require these two

Am getting error that "unable to generate new access code"

` try {

        $collection = new Collection();

        //in other words=> $collection->requestToPay($transactionId, $partyId, $amount)



        $collection->isActive("250784093143");





        $momoTransactionId = $collection->requestToPay('78', '250784093143', 100);



        $data = $collection->getTransactionStatus($momoTransactionId);



        $balance = $collection->getAccountBalance();



        dd($data);



    } catch(CollectionRequestException $e) {`

Combine request exceptions.

Combine CollectionRequestException + DisbursementRequestException + RemittanceRequestException = RequestException

use Bmatovu\MtnMomo\Exceptions\RequestException as MtnMomoRequestException

Fix callback in sandbox

YES. It works in sandbox

  • Change URI to HOST in registerClientId

Default to the application's URL host

parse_url(config('app.url'))['host']

  • Allow sending a callback URI in requestToPay, if not empty

Validate the domain in the callback URI --- it must match the one registered against the Client App

… create a config entry for the client app host / domain so that you don't query MTN for the same

It's likely to be a BC

Errors with the Access Token.

I used tinker and got this error:
Bmatovu/OAuthNegotiator/Exceptions/TokenRequestException with message 'Unable to obtain a new access token.'

I checked the log files and got this:
[2020-06-19T12:07:06.512590+00:00] ** Logger.INFO: [Request] POST /collection/token/ HTTP/1.1 Content-Length: 35 Accept: application/json Ocp-Apim-Subscription-Key: 31dfe3425a214f019aa0406769f4ca2b User-Agent: GuzzleHttp/6.5.5 curl/7.68.0 PHP/7.4.3 Content-Type: application/json Host: sandbox.momodeveloper.mtn.com Authorization: Basic NWEyMTQ5MmItZTI4ZC00NDRjLTkzOWMtOGYwMGUzMzA3NmQ1Og== {"grant_type":"client_credentials"} [Response] HTTP/1.1 500 Server Error Cache-Control: no-store Pragma: no-cache Content-Length: 24 Content-Type: application/json;charset=utf-8 Request-Context: appId=cid-v1:e996501c-e721-4ac1-97ff-dc6887b85e8c Date: Fri, 19 Jun 2020 12:07:08 GMT {"error":"login_failed"} [Error] NULL. [] []**

referrence to ips ands domain.

Can i put my credentials to go live when am on the localhost ,in other words going live offline, on your documentations you have said the incoming ips on mtn must be whitelisted. now can we go live offline when you have your credentials

question

how to make check balance on mtn momo with your system and how to test by send nothing on api mtn momo payment

Error Inserting callback URL in Laravel 6.1

Registering Client ID
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
GuzzleHttp\Exception\RequestException : cURL error 60: SSL certificate problem: unable to get local issuer certificate (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)

at C:\wamp64\www\myli\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php:186
182|
183| // Create a connection exception if it was a specific error code.
184| $error = isset($connectionErrors[$easy->errno])
185| ? new ConnectException($message, $easy->request, null, $ctx)

186| : new RequestException($message, $easy->request, $easy->response, null, $ctx);
187|
188| return \GuzzleHttp\Promise\rejection_for($error);
189| }
190|

Exception trace:

1 GuzzleHttp\Handler\CurlFactory::createRejection(Object(GuzzleHttp\Handler\EasyHandle))
C:\wamp64\www\myli\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php:149

2 GuzzleHttp\Handler\CurlFactory::finishError(Object(GuzzleHttp\Handler\CurlHandler), Object(GuzzleHttp\Handler\EasyHandle), Object(GuzzleHttp\Handler\CurlFactory))
C:\wamp64\www\myli\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php:102

Please use the argument -v to see more details.

Creating a request to pay fail

When i type in tinker $momoTransactionId = $collection->requestToPay('transactionId', '46733123453', 100); here's the answer it returns to me Bmatovu/OAuthNegotiator/Exceptions/TokenRequestException with message 'Unable to obtain a new access token.'
any solutions ?? thanks
transactionFail

Valid MSISDN

function msisdn($phoneNumber, $countryCode = '256', $networkCodes = '39|76|77|78')
{
    $phoneNumber = preg_replace('/[^\d]/', '', $phoneNumber);

    if(! preg_match("/^(0|{$countryCode})({$networkCodes})[\d+]{7}$/", $phoneNumber, $matches)) {
        throw new \InvalidArgumentException('Invalid phone number');
    }

    if($matches[1] == '0') {
        $phoneNumber = substr_replace($phoneNumber, $countryCode, 0, 1);
    }

    return $phoneNumber;
}

echo msisdn('0788123456'); // 256788123456 - OK
echo msisdn('0700123456'); // Invalid phone number
echo msisdn('256788123456'); // 256788123456 - OK
echo msisdn('+256788123456'); // 256788123456 - OK
echo msisdn('+256 (788) 123456'); // 256788123456 - OK
echo msisdn('+46 (788) 123456'); // Invalid phone number

Getting invalid subscription key

Status: 401 Access Denied

Body: { "statusCode": 401, "message": "Access denied due to invalid subscription key. Make sure to provide a valid key for an active subscription." }
I keep getting invalid subscription key anytime i run this php artisan mtn-momo:register-id . the keys i provide too is correct. its from my profile under the product disbursement. what can be the cause of this.

Going live: 404 Resource Not Found

Hi Brian, thanks for this amazing API. I've an issue which I can't pin point the cause!
When running 'php artisan mtn-momo:register-id' after choosing live environment, I get

Registering Client ID
. . . . . . . . . . . . . . . . . . . . . . . .
Status: 404 Resource Not Found

Body: { "statusCode": 404, "message": "Resource not found" }

MOMO_COLLECTION_SUBSCRIPTION_KEY={primary key}
environment : mtnliberia
IP & Domain are whitelisted
MOMO_API_BASE_URI="https://proxy.momoapi.mtn.com/" in config file as well as in .env
Running without registering ID gives: Unable to obtain a new access token (as expected)

Could you please guide me through the steps to rectify? Thanks

Refactor

Separate into PHP only app and Laravel app

Return GuzzleHttp responses

Throw GuzzleHttp exceptions - Remove extra exceptions

Failure to get new access token

Hello
Every time i try to test in my terminal your Usage code i get this error

Bmatovu\OAuthNegotiator\Exceptions\TokenRequestException with message 'Unable to obtain a new access token.'

please tell me what to do

Implement missing endpoints

Claim a consent by the account holder for the requested scopes.

POST /bc-authorize

Claim a consent by the account holder for the requested scopes.

POST /oauth2/token/

Claim a consent by the account holder for the requested scopes.

GET /oauth2/v1_0/userinfo/

Send additional Notification to an end user.

POST /requesttopay/{referenceId}/deliverynotification

Get personal information of the account holder (without their consent)

GET /v1_0/accountholder/msisdn/{accountHolderMSISDN}/basicuserinfo

Getting invalid subscription key

{
"statusCode": 401,
"message": "Access denied due to invalid subscription key. Make sure to provide a valid key for an active subscription."
}

Add troubleshooting section to readme

Steps

  • Clear application cache
php artisan config:clear
  • Delete existing access token(s) from the database
\Bmatovu\MtnMomo\Models\Token::truncate();
  • Confirm package configuration
config('mtn-momo')

* Refer to the GoLive wiki when migrating from sandbox to live environment

Not a issue but question

How do i get the whole response object not only the transactionid but the message also thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.