MTN Mobile Money API Client in Go

mtnmomo-go

Build codecov Scrutinizer Code Quality Go Report Card GitHub contributors GitHub license PkgGoDev

This package provides a generic go client template for the MTN Mobile Money API

Installation

mtnmomo-go is compatible with modern Go releases in module mode, with Go installed:

go get github.com/NdoleStudio/mtnmomo-go

Alternatively the same can be achieved if you use import in a package:

import "github.com/NdoleStudio/mtnmomo-go"

Implemented

  • API User
    • POST {baseURL}/apiuser: Create API User
    • POST {baseURL}/apiuser/{APIUser}/apikey: Create API Key
    • GET {baseURL}/apiuser/{APIUser}: Get API user information
  • Collection
    • POST {baseURL}/collection/token/: Create access token
    • POST {baseURL}/collection/v1_0/requesttopay: Request a payment from a consumer
    • GET {baseURL}/collection/v1_0/requesttopay/{referenceId}: Get the status of a request to pay
    • GET {baseURL}/collection/v1_0/account/balance: Get the balance of the account

Usage

Initializing the Client

An instance of the client can be created using New().

package main

import (
    "github.com/NdoleStudio/mtnmomo-go"
)

func main()  {
    client := mtnmomo.New(
        mtnmomo.WithBaseURL("https://sandbox.momodeveloper.mtn.com/v1_0"),
        mtnmomo.WithSubscriptionKey(""/* Subscription key */),
    )
}

Error handling

All API calls return an error as the last return object. All successful calls will return a nil error.

apiUser, response, err := statusClient.APIUser.CreateAPIUser(context.Background())
if err != nil {
    //handle error
}

API User

POST {baseURL}/apiuser: Create API User

Used to create an API user in the sandbox target environment.

userID, response, err := client.APIUser.CreateAPIUser(
	context.Background(),
	uuid.NewString(),
	"providerCallbackHost",
)

if err != nil {
    log.Fatal(err)
}

log.Println(response.HTTPResponse.StatusCode) // 201

POST {baseURL}/apiuser/{APIUser}/apikey: Create API Key

Used to create an API key for an API user in the sandbox target environment.

apiKey, response, err := client.APIUser.CreateAPIKey(context.Background(), "userID")

if err != nil {
    log.Fatal(err)
}

log.Println(apiKey) // e.g "f1db798c98df4bcf83b538175893bbf0"

GET {baseURL}/apiuser/{APIUser}: Get API user information

Used to get API user information.

apiUser, response, err := client.APIUser.CreateAPIKey(context.Background(), "userID")

if err != nil {
    log.Fatal(err)
}

log.Println(apiUser.TargetEnvironment) // e.g "sandbox"

Collection

POST {baseURL}/collection/token/: Create access token

This operation is used to create an access token which can then be used to authorize and authenticate towards the other end-points of the API.

authToken, response, err := client.Collection.Token(context.Background())
if err != nil {
	log.Fatal(err)
}

log.Println(authToken.AccessToken) // e.g eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9....

POST {baseURL}/collection/v1_0/requesttopay: Request a payment from a consumer

This operation is used to request a payment from a consumer (Payer). The payer will be asked to authorize the payment. The transaction will be executed once the payer has authorized the payment.

callbackURL := "http://callback-url.com"
response, err := client.Collection.RequestToPay(
	context.Background(),
	referenceID,
	&mtnmomo.RequestToPayParams{
		Amount:     "10",
		Currency:   "EUR",
		ExternalID: uuid.NewString(),
		Payer: &mtnmomo.RequestToPayPayer{
			PartyIDType: "MSISDN",
			PartyID:     "673978334",
		},
		PayerMessage: "Test Payer Message",
		PayeeNote:    "Test Payee Note",
	},
	&callbackURL,
)

if err != nil {
    log.Fatal(err)
}

log.Println(response.HTTPResponse.StatusCode) // e.g 201 (Accepted)

GET {baseURL}/collection/v1_0/requesttopay/{referenceId}: Get the status of a request to pay

This operation is used to get the status of a request to pay. X-Reference-Id that was passed in the post is used as reference to the request.

status, _, err := client.Collection.GetRequestToPayStatus(context.Background(), referenceID)
if err != nil {
	log.Fatal(err)
}

log.Println(status.Status) // SUCCESSFUL

GET {baseURL}/collection/v1_0/account/balance: Get the balance of the account

balance, _, err := client.Collection.GetAccountBalance(context.Background())
if err != nil {
    log.Fatal(err)
}
log.Println(balance.AvailableBalance) // "1000"

Testing

You can run the unit tests for this client from the root directory using the command below:

go test -v

Security

If you discover any security related issues, please email [email protected] instead of using the GitHub issues.

Credits

License

This project is licensed under the MIT License - see the LICENSE file for details

Similar Resources

Go PowerDNS 4.x API Client

PowerDNS 4.x API bindings for Golang This community project provides bindings for the currently latest version of PowerDNS Authoritative Server. Featu

Dec 12, 2022

Golang client for querying SecurityTrails API data

Golang client for querying SecurityTrails API data

haktrails haktrails is a Golang client for querying SecurityTrails API data, sponsored by SecurityTrails. SecurityTrails $50 Bug Bounty Hunter Plan Sa

Jan 4, 2023

Go client for the Notion API.

go-notion go-notion is a client for the Notion API, written in Go. Features The client supports all (non-deprecated) endpoints available in the Notion

Jan 2, 2023

Go/Golang client library to interact with the Stein API

go-stein This Go / Golang client helps you interact with the Stein API. Stein is a suite of programs to help you turn any Google Sheet to a database.

Aug 23, 2022

Notion Official API Go Client.

go-notion Go SDK for Notion Official API. go get github.com/sorcererxw/go-notion Overview Getting Started Pagination Error Handling Reverse Proxy OAut

Aug 4, 2021

Go client for the Foreign exchange rates and currency conversion API 💰

fixer Go client for Fixer.io (Foreign exchange rates and currency conversion API) You need to register for a free access key if using the default Fixe

Nov 14, 2022

Go client library for accessing the Football Data API

football-data-sdk football-data-sdk is a Go client library for accessing the Football Data API. Successful queries return native Go structs. Services

Oct 13, 2022

Teraswitch Go API Client

GoTSW The official Teraswitch Go client. Install go get -u github.com/teraswitch/gotsw Usage import "github.com/teraswitch/gotsw" Authentication packa

Apr 1, 2022

Client for the OpenWeather API, written in Go

Weather This is a Go project template, intended for students at the Bitfield Institute of Technology—but everyone's welcome to try it if you're intere

Nov 9, 2021
Godaddy-domains-client-go - Godaddy domains api Client golang - Write automaticly from swagger codegen

Go API client for swagger Overview This API client was generated by the swagger-codegen project. By using the swagger-spec from a remote server, you c

Jan 9, 2022
Tailscale-client-go - A client implementation for the Tailscale HTTP API

tailscale-client-go A client implementation for the Tailscale HTTP API Example p

Sep 8, 2022
An API Client package for Studyplus for School SYNC API

Studyplus for School SYNC API Client This project is currently alpha, possibility having breaking changes. studyplus_for_school_sync_go is a API clien

Aug 2, 2021
Go API Client for Metasploit RPC API

go-msf-rpc Golang based RPC client to communicate with Metasploit. Based on code initially developed by Wyatt Dahlenburg repo. Extended to include oth

Nov 18, 2022
iceportal-api is a Golang client implementation to interact with the REST API of iceportal.de when connected to the WiFi-Network offered in German ICE Trains.
iceportal-api is a Golang client implementation to interact with the REST API of iceportal.de when connected to the WiFi-Network offered in German ICE Trains.

iceportal-api is a Golang client implementation to interact with the REST API of iceportal.de when connected to the WiFi-Network offered in German ICE Trains.

Aug 20, 2022
Prisma Client Go is an auto-generated and fully type-safe database client

Prisma Client Go Typesafe database access for Go Quickstart • Website • Docs • API reference • Blog • Slack • Twitter Prisma Client Go is an auto-gene

Jan 9, 2023
The Dual-Stack Dynamic DNS client, the world's first dynamic DNS client built for IPv6.

dsddns DsDDNS is the Dual-Stack Dynamic DNS client. A dynamic DNS client keeps your DNS records in sync with the IP addresses associated with your hom

Sep 27, 2022
Go Substrate RPC Client (GSRPC)Go Substrate RPC Client (GSRPC)

Go Substrate RPC Client (GSRPC) Substrate RPC client in Go. It provides APIs and types around Polkadot and any Substrate-based chain RPC calls. This c

Nov 11, 2021
Server and client implementation of the grpc go libraries to perform unary, client streaming, server streaming and full duplex RPCs from gRPC go introduction

Description This is an implementation of a gRPC client and server that provides route guidance from gRPC Basics: Go tutorial. It demonstrates how to u

Nov 24, 2021
Comunicación de envios de archivos entres cliente-servidor, client-client.

Client - Server - Client Estes es un proyecto simple de comunicacion de envios de archivos del cliente al servidor y viceversamente, y de cliente a cl

Jul 16, 2022