Skip to content

Latest commit

 

History

11 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

MTN Mobile Money SDK for Go

A comprehensive Go SDK for integrating MTN Mobile Money (MoMo) payment services into your applications. This SDK provides simple, idiomatic Go interfaces to MTN's collection, disbursement, account, and refund APIs.

Features

  • Collections API: Request payments from customers
  • Disbursements API: Send money to customers
  • Account API: Check balance and validate account holders
  • Refunds API: Handle transaction refunds
  • Type-safe: Fully typed request/response structures
  • Error handling: Comprehensive error handling and validation
  • Idempotent requests: Built-in support for idempotent operations
  • Zero external dependencies: Uses only Go standard library

Installation

go get github.com/Bahatiroben/mtn-momo-sdk-go

Quick Start

1. Initialize the SDK

package main

import (
	"log"
	"time"
	
	"github.com/Bahatiroben/mtn-momo-sdk-go/pgk/momo"
)

func main() {
	config := &momo.Config{
		BaseURL:         "https://sandbox.momodeveloper.mtn.com",
		APIKey:          "your-api-key",
		PrimaryKey:      "your-primary-key",
		SecondaryKey:    "your-secondary-key",
		SubscriptionKey: "your-subscription-key",
		Timeout:         30 * time.Second,
	}

	sdk, err := momo.NewSDK(config)
	if err != nil {
		log.Fatalf("Failed to initialize SDK: %v", err)
	}
	defer sdk.Close()
}

2. Request Payment (Collection)

req := &momo.CollectionRequest{
	Amount: momo.Money{
		Amount:   "1000",
		Currency: "RWF",
	},
	Currency:   "RWF",
	ExternalId: "txn-unique-id-123",
	Payer: momo.Party{
		PartyIdType: momo.PartyIdTypeMSISDN,
		PartyId:     "250780000000",
		PartyName:   "John Doe",
	},
	PayerMessage: "Payment for goods",
	PayeeNote:    "Invoice #2024001",
}

resp, err := sdk.Collections.RequestToPay(req)
if err != nil {
	log.Printf("Error: %v", err)
	return
}

log.Printf("Transaction ID: %s", resp.TransactionId)

3. Check Transaction Status

status, err := sdk.Collections.GetTransactionStatus("txn-unique-id-123")
if err != nil {
	log.Printf("Error: %v", err)
	return
}

log.Printf("Status: %s", status.Status)

4. Send Money (Disbursement)

req := &momo.DisbursementRequest{
	Amount: momo.Money{
		Amount:   "2000",
		Currency: "RWF",
	},
	Currency:   "RWF",
	ExternalId: "transfer-unique-id",
	Payee: momo.Party{
		PartyIdType: momo.PartyIdTypeMSISDN,
		PartyId:     "250780000000",
		PartyName:   "Jane Smith",
	},
	PayerMessage: "Salary payment",
	PayeeNote:    "Monthly salary",
}

resp, err := sdk.Disbursements.Transfer(req)
if err != nil {
	log.Printf("Error: %v", err)
	return
}

log.Printf("Transfer initiated with ID: %s", resp.TransactionId)

5. Get Account Balance

balance, err := sdk.Account.GetBalance("RWF")
if err != nil {
	log.Printf("Error: %v", err)
	return
}

log.Printf("Balance: %s %s", balance.Balance, balance.Currency)

6. Validate Account Holder

info, err := sdk.Account.ValidateAccountHolder("250780000000", momo.PartyIdTypeMSISDN)
if err != nil {
	log.Printf("Error: %v", err)
	return
}

log.Printf("Account validation result: %s", info.Result)

7. Create Refund

req := &momo.RefundRequest{
	Amount: momo.Money{
		Amount:   "1000",
		Currency: "RWF",
	},
	Currency:              "RWF",
	ExternalId:            "refund-001",
	OriginalTransactionId: "txn-unique-id-123",
	Reason:                "Customer requested refund",
}

resp, err := sdk.Refunds.CreateRefund(req)
if err != nil {
	log.Printf("Error: %v", err)
	return
}

log.Printf("Refund created with ID: %s", resp.TransactionId)

API Reference

Collections API

RequestToPay

Initiates a request for payment from a customer.

func (c *Collections) RequestToPay(req *CollectionRequest) (*CollectionResponse, error)

RequestToPayWithOptions

Convenience method with flexible options.

func (c *Collections) RequestToPayWithOptions(
	amount, currency, externalId, payerId string,
	additionalOptions map[string]interface{},
) (*CollectionResponse, error)

GetTransactionStatus

Checks the status of a collection request.

func (c *Collections) GetTransactionStatus(transactionId string) (*TransactionStatusResponse, error)

Disbursements API

Transfer

Initiates a disbursement/transfer to a customer.

func (d *Disbursements) Transfer(req *DisbursementRequest) (*DisbursementResponse, error)

TransferWithOptions

Convenience method with flexible options.

func (d *Disbursements) TransferWithOptions(
	amount, currency, externalId, payeeId string,
	additionalOptions map[string]interface{},
) (*DisbursementResponse, error)

GetTransactionStatus

Checks the status of a disbursement.

func (d *Disbursements) GetTransactionStatus(transactionId string) (*TransactionStatusResponse, error)

Account API

GetBalance

Retrieves the current account balance.

func (a *Account) GetBalance(currency string) (*BalanceResponse, error)

ValidateAccountHolder

Checks if an account holder exists.

func (a *Account) ValidateAccountHolder(
	accountHolderId, accountHolderIdType string,
) (*AccountHolderResponse, error)

GetAccountInfo

Retrieves account information.

func (a *Account) GetAccountInfo(accountId string) (*AccountHolderResponse, error)

Refunds API

CreateRefund

Initiates a refund for a previous transaction.

func (r *Refunds) CreateRefund(req *RefundRequest) (*RefundResponse, error)

CreateRefundWithOptions

Convenience method with flexible options.

func (r *Refunds) CreateRefundWithOptions(
	amount, currency, externalId, originalTransactionId string,
	additionalOptions map[string]interface{},
) (*RefundResponse, error)

GetRefundStatus

Checks the status of a refund request.

func (r *Refunds) GetRefundStatus(transactionId string) (*TransactionStatusResponse, error)

Types

Config

Configuration for the SDK client.

type Config struct {
	BaseURL         string        // API base URL
	APIKey          string        // API key
	PrimaryKey      string        // Primary key
	SecondaryKey    string        // Secondary key
	SubscriptionKey string        // Subscription key
	Timeout         time.Duration // Request timeout
}

Party

Represents a party in a transaction (payer or payee).

type Party struct {
	PartyIdType string // MSISDN, EMAIL, or PARTY_CODE
	PartyId     string // Phone number or email
	PartyName   string // Optional name
}

Money

Represents a monetary amount.

type Money struct {
	Amount   string // Amount in smallest currency unit
	Currency string // ISO 4217 currency code
}

Error Handling

The SDK returns detailed error messages for failed requests:

resp, err := sdk.Collections.RequestToPay(req)
if err != nil {
	// Handle error
	log.Printf("Failed to request payment: %v", err)
}

Common errors include:

  • Invalid configuration parameters
  • Missing required fields in requests
  • API authentication failures
  • Network timeouts
  • Invalid currency codes

Best Practices

  1. Use ExternalId for Idempotency: Always provide a unique ExternalId for each request to ensure idempotent operations. This prevents duplicate transactions if a request is retried.

  2. Check Transaction Status: Always check transaction status after receiving a response, as the immediate response doesn't guarantee completion.

  3. Handle Timeouts: Configure appropriate timeout values based on your use case. Default is 30 seconds.

  4. Validate Parties: Use ValidateAccountHolder before initiating transactions to ensure the recipient exists.

  5. Log Transactions: Keep logs of all transaction IDs for reconciliation and audit purposes.

  6. Use Sandbox for Testing: Develop and test against the sandbox environment before moving to production.

Constants

Party ID Types

  • PartyIdTypeMSISDN: Mobile number
  • PartyIdTypeEmail: Email address
  • PartyIdTypePartyCode: Party code

Transaction Status

  • TransactionStatusSuccessful: Transaction completed successfully
  • TransactionStatusFailed: Transaction failed
  • TransactionStatusPending: Transaction is pending

Transaction Types

  • TransactionTypeCashin: Cash-in transaction
  • TransactionTypeCashout: Cash-out transaction
  • TransactionTypeTransfer: Transfer transaction
  • TransactionTypeBillPayment: Bill payment
  • TransactionTypeRefund: Refund transaction

Running Tests

go test ./...

Contributing

Contributions are welcome! Please ensure:

  1. Code follows Go conventions
  2. Tests are included for new features
  3. Documentation is updated
  4. No external dependencies are added without good reason

License

This SDK is provided as-is for integration with MTN Mobile Money services.

Support

For issues, questions, or suggestions:

  1. Check the examples directory for usage patterns
  2. Review the API documentation from MTN Developer Portal
  3. Ensure your credentials are correct and have appropriate permissions

Changelog

v1.0.0

  • Initial release
  • Collections API
  • Disbursements API
  • Account API
  • Refunds API
  • Comprehensive test coverage
  • Full documentation

About

MTN mobile money SDK for Golang

Topics

Resources

Contributing

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages