mtnmomo

package module
v0.0.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 11, 2022 License: MIT Imports: 11 Imported by: 0

README

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
  • Disbursements
    • POST {baseURL}/disbursement/token/: Create access token
    • POST {baseURL}/disbursement/v1_0/transfer: Transfer money to a customer's account.
    • GET {baseURL}/disbursement/v1_0/transfer/{referenceId}: Get the status of a transfer.
    • GET {baseURL}/disbursement/v1_0/account/balance: Get the balance of the disbursement 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 arnoldewin@gmail.com instead of using the GitHub issues.

Credits

License

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

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type APIUser

type APIUser struct {
	UserID               string `json:"userId"`
	ProviderCallbackHost string `json:"providerCallbackHost"`
	TargetEnvironment    string `json:"targetEnvironment"`
}

APIUser contains information about an API User

type AccountBalance

type AccountBalance struct {
	AvailableBalance string `json:"availableBalance"`
	Currency         string `json:"currency"`
}

AccountBalance is available balance of the account

type AccountHolder added in v0.0.4

type AccountHolder struct {
	PartyIDType string `json:"partyIdType"`
	PartyID     string `json:"partyId"`
}

AccountHolder identifies an account holder in the wallet platform.

type AuthToken

type AuthToken struct {
	AccessToken string `json:"access_token"`
	TokenType   string `json:"token_type"`
	ExpiresIn   int64  `json:"expires_in"`
}

AuthToken is A JWT token which is to authorize against the other API end-points.

type Client

type Client struct {
	APIUser      *apiUserService
	Collection   *collectionService
	Disbursement *disbursementsService
	// contains filtered or unexported fields
}

Client is the campay API client. Do not instantiate this client with Client{}. Use the New method instead.

func New

func New(options ...Option) *Client

New creates and returns a new campay.Client from a slice of campay.ClientOption.

type CollectionTransactionStatus added in v0.0.4

type CollectionTransactionStatus struct {
	Amount                 string         `json:"amount"`
	Currency               string         `json:"currency"`
	ExternalID             string         `json:"externalId"`
	ReferenceID            string         `json:"referenceId"`
	Payer                  *AccountHolder `json:"payer"`
	Status                 string         `json:"status"`
	FinancialTransactionID *string        `json:"financialTransactionId,omitempty"`
	Reason                 *string        `json:"reason,omitempty"`
}

CollectionTransactionStatus is the status of a request to pay request.

func (*CollectionTransactionStatus) IsCancelled added in v0.0.4

func (status *CollectionTransactionStatus) IsCancelled() bool

IsCancelled checks if a transaction is cancelled

func (*CollectionTransactionStatus) IsFailed added in v0.0.4

func (status *CollectionTransactionStatus) IsFailed() bool

IsFailed checks if a transaction is in failed status

func (*CollectionTransactionStatus) IsPending added in v0.0.4

func (status *CollectionTransactionStatus) IsPending() bool

IsPending checks if a transaction is in pending status

func (*CollectionTransactionStatus) IsSuccessful added in v0.0.4

func (status *CollectionTransactionStatus) IsSuccessful() bool

IsSuccessful checks if a transaction is successful

type DisbursementTransactionStatus added in v0.0.4

type DisbursementTransactionStatus struct {
	Amount                 string         `json:"amount"`
	Currency               string         `json:"currency"`
	ExternalID             string         `json:"externalId"`
	ReferenceID            string         `json:"referenceId"`
	Payee                  *AccountHolder `json:"payee"`
	Status                 string         `json:"status"`
	FinancialTransactionID *string        `json:"financialTransactionId,omitempty"`
	PayerMessage           string         `json:"payerMessage"`
	PayeeNote              string         `json:"payeeNote"`
}

DisbursementTransactionStatus is the status of a request to pay request.

func (*DisbursementTransactionStatus) IsCancelled added in v0.0.4

func (status *DisbursementTransactionStatus) IsCancelled() bool

IsCancelled checks if a transaction is cancelled

func (*DisbursementTransactionStatus) IsFailed added in v0.0.4

func (status *DisbursementTransactionStatus) IsFailed() bool

IsFailed checks if a transaction is in failed status

func (*DisbursementTransactionStatus) IsPending added in v0.0.4

func (status *DisbursementTransactionStatus) IsPending() bool

IsPending checks if a transaction is in pending status

func (*DisbursementTransactionStatus) IsSuccessful added in v0.0.4

func (status *DisbursementTransactionStatus) IsSuccessful() bool

IsSuccessful checks if a transaction is successful

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option is options for constructing a client

func WithAPIKey

func WithAPIKey(apiKey string) Option

WithAPIKey sets the API key.

func WithAPIUser

func WithAPIUser(apiUser string) Option

WithAPIUser sets the API user.

func WithBaseURL

func WithBaseURL(baseURL string) Option

WithBaseURL set's the base url for the flutterwave API

func WithHTTPClient

func WithHTTPClient(httpClient *http.Client) Option

WithHTTPClient sets the underlying HTTP client used for API requests. By default, http.DefaultClient is used.

func WithSubscriptionKey

func WithSubscriptionKey(subscriptionKey string) Option

WithSubscriptionKey sets the delay in milliseconds before a response is gotten.

func WithTargetEnvironment

func WithTargetEnvironment(targetEnvironment string) Option

WithTargetEnvironment sets the identifier of the EWP system where the transaction shall be processed.

type RequestToPayParams

type RequestToPayParams struct {
	Amount       string         `json:"amount"`
	Currency     string         `json:"currency"`
	ExternalID   string         `json:"externalId"`
	Payer        *AccountHolder `json:"payer"`
	PayerMessage string         `json:"payerMessage"`
	PayeeNote    string         `json:"payeeNote"`
}

RequestToPayParams is the set of parameters used when creating a payment request

type Response

type Response struct {
	HTTPResponse *http.Response
	Body         *[]byte
}

Response captures the http response

func (*Response) Error

func (r *Response) Error() error

Error ensures that the response can be decoded into a string inc ase it's an error response

type TransferParams added in v0.0.4

type TransferParams struct {
	Amount       string         `json:"amount"`
	Currency     string         `json:"currency"`
	ExternalID   string         `json:"externalId"`
	Payee        *AccountHolder `json:"payee"`
	PayerMessage string         `json:"payerMessage"`
	PayeeNote    string         `json:"payeeNote"`
}

TransferParams is the set of parameters for transferring money to a payee account

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL