mpesa

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Oct 2, 2023 License: Apache-2.0 Imports: 16 Imported by: 1

Documentation

Overview

Package mpesa provides a wrapper around the Mpesa API.

The Mpesa API is a RESTful API that exposes Mpesa functionality to applications such as MpesaOverlay.

The Mpesa API is documented at https://developer.safaricom.co.ke/docs.

Copyright (c) MpesaOverlay. All rights reserved. Use of this source code is governed by a Apache-2.0 license that can be found in the LICENSE file.

SPDX-License-Identifier: Apache-2.0

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AccountBalanceReq

type AccountBalanceReq struct {
	CommandID          string `json:"CommandID,omitempty"`
	PartyA             uint64 `json:"PartyA,omitempty"`             // Type of organization receiving the transaction
	IdentifierType     uint8  `json:"IdentifierType,omitempty"`     // Type of organization querying for the account balance.
	Remarks            string `json:"Remarks,omitempty"`            // Comments that are sent along with the transaction.
	InitiatorName      string `json:"Initiator,omitempty"`          // The name of Initiator to initiating  the request
	InitiatorPassword  string `json:"InitiatorPassword,omitempty"`  // The password of the API user. This is the same password used while creating the API user.
	SecurityCredential string `json:"SecurityCredential,omitempty"` // Encrypted Credential of user getting transaction amoun
	QueueTimeOutURL    string `json:"QueueTimeOutURL,omitempty"`    // The path that stores information of time out transaction
	ResultURL          string `json:"ResultURL,omitempty"`          // The path that stores information of transaction
}

AccountBalanceReq is used to query the balance of an account.

func (AccountBalanceReq) Validate

func (r AccountBalanceReq) Validate() error

Validate validate the struct.

type AccountBalanceResp

type AccountBalanceResp struct {
	ValidResp
}

AccountBalanceResp is the response from the AccountBalance endpoint.

type B2CPaymentReq

type B2CPaymentReq struct {
	OriginatorConversationID string `json:"OriginatorConversationID,omitempty"` // This is a unique string you specify for every API request you simulate.
	CommandID                string `json:"CommandID,omitempty"`                // This is a unique command that specifies B2C transaction type.
	PartyA                   uint64 `json:"PartyA,omitempty"`                   // This is the B2C organization shortcode from which the money is sent from.
	PartyB                   uint64 `json:"PartyB,omitempty"`                   // This is the customer mobile number to receive the amount. - The number should have the country code (254) without the plus sign.
	Remarks                  string `json:"Remarks,omitempty"`                  // Any additional information to be associated with the transaction.
	InitiatorName            string `json:"InitiatorName,omitempty"`            // This is an API user created by the Business Administrator of the M-PESA Bulk disbursement account that is active and authorized to initiate B2C transactions via API.
	InitiatorPassword        string `json:"InitiatorPassword,omitempty"`        // The password of the API user. This is the same password used while creating the API user.
	SecurityCredential       string `json:"SecurityCredential,omitempty"`       // This is the value obtained after encrypting the API initiator password. The password on Sandbox has been provisioned on the simulator. However, on production the password is created when the user is being created on the M-PESA organization portal.
	QueueTimeOutURL          string `json:"QueueTimeOutURL,omitempty"`          // This is the URL to be specified in your request that will be used by API Proxy to send notification incase the payment request is timed out while awaiting processing in the queue
	ResultURL                string `json:"ResultURL,omitempty"`                // This is the URL to be specified in your request that will be used by M-PESA to send notification upon processing of the payment request.
	TransactionID            string `json:"TransactionID,omitempty"`
	Occasion                 string `json:"Occasion,omitempty"` // Any additional information to be associated with the transaction.
	Amount                   uint64 `json:"Amount,omitempty"`   // The amount of money being sent to the customer.
}

B2CPaymentReq is used to make a B2C payment.

func (B2CPaymentReq) Validate

func (r B2CPaymentReq) Validate() error

Validate validate the struct.

type B2CPaymentResp

type B2CPaymentResp struct {
	ValidResp
}

B2CPaymentResp is the response from the B2CPayment endpoint.

type C2BRegisterURLReq

type C2BRegisterURLReq struct {
	ValidationURL   string `json:"ValidationURL,omitempty"`   // This is the URL that receives the validation request from API upon payment submission. The validation URL is only called if external validation on the registered shortcode is enabled. (By default external validation is disabled)
	ConfirmationURL string `json:"ConfirmationURL,omitempty"` // Thie is the URL that receives the confirmation request from API upon payment completion
	ShortCode       uint64 `json:"ShortCode,omitempty"`       // The shortcode of the organization
	ResponseType    string `json:"ResponseType,omitempty"`    // This parameter specifies what is to happen if for any reason the validation URL is not reachable. It can be cancelled or completed.
}

C2BRegisterURLReq is used to register a URL.

func (C2BRegisterURLReq) Validate

func (c2b C2BRegisterURLReq) Validate() error

Validate validate the C2BRegisterURLReq Request.

type C2BRegisterURLResp

type C2BRegisterURLResp struct {
	ValidResp
}

C2BRegisterURLResp is the response from the C2BRegisterURL endpoint.

type C2BSimulateReq

type C2BSimulateReq struct {
	CommandID     string `json:"CommandID,omitempty"`     // This is a unique identifier of the transaction type: There are two types of these Identifiers:
	Msisdn        string `json:"Msisdn,omitempty"`        // This is the phone number initiating the C2B transaction.
	BillRefNumber string `json:"BillRefNumber,omitempty"` // This is used on CustomerPayBillOnline option only. This is where a customer is expected to enter a unique bill identifier, e.g. an Account Number.
	Amount        uint64 `json:"Amount,omitempty"`        // This is the amount being transacted.
	ShortCode     uint64 `json:"ShortCode,omitempty"`     // This is the Short Code receiving the amount being transacted.
}

C2BSimulateReq is used to simulate a C2B transaction.

func (C2BSimulateReq) Validate

func (c2b C2BSimulateReq) Validate() error

Validate validate the C2BSimulateReq Request.

type C2BSimulateResp

type C2BSimulateResp struct {
	ValidResp
}

C2BSimulateResp is the response from the C2BSimulate endpoint.

type Config

type Config struct {
	BaseURL           string
	AppKey            string
	AppSecret         string
	CertFile          string
	HTTPClient        *http.Client
	InitiatorName     string
	InitiatorPassword string
}

Config contains sdk configuration parameters.

type ExpressQueryReq

type ExpressQueryReq struct {
	PassKey           string `json:"PassKey,omitempty"`           // This is a passkey which is generated by Safaricom for use when making Lipa Na M-Pesa Online Payment API requests.
	BusinessShortCode uint64 `json:"BusinessShortCode,omitempty"` // This is organizations shortcode (Paybill or Buygoods - A 5 to 7 digit account number) used to identify an organization and receive the transaction.
	Password          string `json:"Password,omitempty"`          // This is the password used for encrypting the request sent: A base64 encoded string.
	Timestamp         string `json:"Timestamp,omitempty"`         // This is the Timestamp of the transaction, normally in the formart of YEAR+MONTH+DATE+HOUR+MINUTE+SECOND (YYYYMMDDHHMMSS)
	CheckoutRequestID string `json:"CheckoutRequestID,omitempty"` // This is a global unique identifier of the processed checkout transaction request.
}

ExpressQueryReq is used to query a transaction.

func (ExpressQueryReq) Validate

func (eqr ExpressQueryReq) Validate() error

Validate validate the ExpressQueryReq Request.

type ExpressQueryResp

type ExpressQueryResp struct {
	ResponseDescription string `json:"ResponseDescription,omitempty"` // Response Description message. It can be a Success submission message or an error description.
	ResponseCode        string `json:"ResponseCode,omitempty"`        // This is a numeric status code that indicates the status of the transaction submission. 0 means successful submission and any other code means an error occurred.
	MerchantRequestID   string `json:"MerchantRequestID,omitempty"`   // This is a global unique Identifier for any submitted payment request.
	CheckoutRequestID   string `json:"CheckoutRequestID,omitempty"`   // This is a global unique identifier of the processed checkout transaction request.
	CustomerMessage     string `json:"CustomerMessage,omitempty"`     // This is a message that your system can display to the Customer as an acknowledgement of the payment request submission.
	ResultCode          string `json:"ResultCode,omitempty"`          // This is a numeric status code that indicates the status of the transaction processing. 0 means successful processing and any other code means an error occurred or the transaction failed.
	ResultDesc          string `json:"ResultDesc,omitempty"`          // Response description is an acknowledgment message from the API that gives the status of the request submission usually maps to a specific ResponseCode value. It can be a "Success" submission message or an error description.
}

ExpressQueryResp is the response from the ExpressQuery endpoint.

type ExpressSimulateReq

type ExpressSimulateReq struct {
	PassKey           string `json:"PassKey,omitempty"`           // This is a passkey which is generated by Safaricom for use when making Lipa Na M-Pesa Online Payment API requests.
	BusinessShortCode uint64 `json:"BusinessShortCode,omitempty"` // This is the organization's shortcode (Paybill or Buygoods - A 5 to 6-digit account number) used to identify an organization and receive the transaction.
	Password          string `json:"Password,omitempty"`          // This is the password used for encrypting the request sent.
	Timestamp         string `json:"Timestamp,omitempty"`         // This is the Timestamp of the transaction.
	TransactionType   string `json:"TransactionType,omitempty"`   // This is the transaction type that is used to identify the transaction when sending the request to M-PESA.
	PhoneNumber       uint64 `json:"PhoneNumber,omitempty"`       // The Mobile Number to receive the STK Pin Prompt.
	Amount            uint64 `json:"Amount,omitempty"`            // This is the Amount transacted normally a numeric value.
	PartyA            uint64 `json:"PartyA,omitempty"`            // The phone number sending money.
	PartyB            uint64 `json:"PartyB,omitempty"`            // The organization that receives the funds.
	CallBackURL       string `json:"CallBackURL,omitempty"`       // A CallBack URL is a valid secure URL that is used to receive notifications from M-Pesa API.
	AccountReference  string `json:"AccountReference,omitempty"`  // This is an Alpha-Numeric parameter that is defined by your system as an Identifier of the transaction for the CustomerPayBillOnline transaction type.
	TransactionDesc   string `json:"TransactionDesc,omitempty"`   // This is any additional information/comment that can be sent along with the request
}

ExpressSimulateReq is used to simulate a transaction.

func (ExpressSimulateReq) Validate

func (esr ExpressSimulateReq) Validate() error

Validate validate the ExpressSimulateReq Request.

type ExpressSimulateResp

type ExpressSimulateResp struct {
	ResponseDescription string `json:"ResponseDescription,omitempty"` // Response description is an acknowledgment message from the API that gives the status of the request submission.
	ResponseCode        string `json:"ResponseCode,omitempty"`        // This is a Numeric status code that indicates the status of the transaction submission. 0 means successful submission and any other code means an error occurred.
	MerchantRequestID   string `json:"MerchantRequestID,omitempty"`   // This is a global unique Identifier for any submitted payment request.
	CheckoutRequestID   string `json:"CheckoutRequestID,omitempty"`   // This is a global unique identifier of the processed checkout transaction request.
	CustomerMessage     string `json:"CustomerMessage,omitempty"`     // This is a message that your system can display to the customer as an acknowledgment of the payment request submission.
}

ExpressSimulateResp is the response from the ExpressSimulate endpoint.

type GenerateQRReq

type GenerateQRReq struct {
	MerchantName string `json:"MerchantName,omitempty"` // Name of the Company/M-Pesa Merchant Name
	RefNo        string `json:"RefNo,omitempty"`        // Transaction Reference
	Amount       uint64 `json:"Amount,omitempty"`       // The total amount for the sale/transaction
	TrxCode      string `json:"TrxCode,omitempty"`      // Transaction Type. Can be SB, WA, PB, SM, BG
	CPI          string `json:"CPI,omitempty"`          // Credit Party Identifier. Can be a Mobile Number, Business Number, Agent Till, Paybill or Business number, Merchant Buy Goods.
	Size         string `json:"Size,omitempty"`         // Size of the QR code image in pixels.
}

GenerateQRReq is used to generate a QR code.

func (GenerateQRReq) Validate

func (qr GenerateQRReq) Validate() error

Validate validate the GenerateQRReq Request.

type GenerateQRResp

type GenerateQRResp struct {
	ResponseDescription string `json:"ResponseDescription,omitempty"` // This is a response describing the status of the transaction.
	ResponseCode        string `json:"ResponseCode,omitempty"`        // Used to return the Transaction Type.
	RequestID           string `json:"RequestID,omitempty"`
	QRCode              string `json:"QRCode,omitempty"` // QR Code Image Data/String/Image.
}

GenerateQRResp is the response from the GenerateQR endpoint.

type Option

type Option func(SDK) (SDK, error)

Option is a function that can be passed to New to configure a SDK.

type RemitTaxReq

type RemitTaxReq struct {
	InitiatorName          string `json:"Initiator,omitempty"`              // The name of Initiator to initiating  the request
	InitiatorPassword      string `json:"InitiatorPassword,omitempty"`      // The password of the API user. This is the same password used while creating the API user.
	SecurityCredential     string `json:"SecurityCredential,omitempty"`     // Encrypted Credential of user getting transaction amoun
	CommandID              string `json:"CommandID,omitempty"`              // Takes only the 'TransactionStatusQuery' Command ID.
	SenderIdentifierType   uint8  `json:"SenderIdentifierType,omitempty"`   // The type of shortcode from which money is deducted. For this API, only "4" is allowed.
	RecieverIdentifierType uint8  `json:"RecieverIdentifierType,omitempty"` // The type of shortcode to which money is credited. For this API, only "4" is allowed.
	Amount                 uint64 `json:"Amount,omitempty"`                 // The amount of money being sent to the customer.
	PartyA                 uint64 `json:"PartyA,omitempty"`                 // This is your own shortcode from which the money will be deducted.
	PartyB                 uint64 `json:"PartyB,omitempty"`                 // The account to which money will be credited.
	AccountReference       string `json:"AccountReference,omitempty"`       // The payment registration number (PRN) issued by KRA.
	QueueTimeOutURL        string `json:"QueueTimeOutURL,omitempty"`        // The path that stores information of time out transaction
	ResultURL              string `json:"ResultURL,omitempty"`              // The path that stores information of transaction
	Remarks                string `json:"Remarks,omitempty"`                // Comments that are sent along with the transaction.
}

RemitTaxReq is used to remit tax.

func (RemitTaxReq) Validate

func (r RemitTaxReq) Validate() error

Validate validate the struct.

type RemitTaxResp

type RemitTaxResp struct {
	ValidResp
}

RemitTaxResp is the response from the RemitTax endpoint.

type RespError

type RespError struct {
	RequestID string `json:"requestId,omitempty"`
	Code      string `json:"errorCode,omitempty"`
	Message   string `json:"errorMessage,omitempty"`
}

RespError is a common response for all endpoints.

func (RespError) Error

func (e RespError) Error() string

Error is the error returned by the Mpesa API.

type ReverseReq

type ReverseReq struct {
	CommandID              string `json:"CommandID,omitempty"`              // Takes only the 'TransactionReversal' Command id.
	ReceiverParty          uint64 `json:"ReceiverParty,omitempty"`          // The organization that receives the transaction.
	RecieverIdentifierType uint8  `json:"RecieverIdentifierType,omitempty"` // Type of organization that receives the transaction.
	Remarks                string `json:"Remarks,omitempty"`                // Comments that are sent along with the transaction.
	InitiatorName          string `json:"Initiator,omitempty"`              // The name of the initiator to initiate the request.
	InitiatorPassword      string `json:"InitiatorPassword,omitempty"`      // The password of the API user. This is the same password used while creating the API user.
	SecurityCredential     string `json:"SecurityCredential,omitempty"`     // Encrypted Credential of the user getting transaction amount.
	QueueTimeOutURL        string `json:"QueueTimeOutURL,omitempty"`        // The path that stores information about the time-out transaction.
	ResultURL              string `json:"ResultURL,omitempty"`              // The path that stores information about the transaction.	TransactionID string `json:"TransactionID,omitempty"`
	Occasion               string `json:"Occasion,omitempty"`               // Optional Parameter.
	Amount                 uint64 `json:"Amount,omitempty"`                 // The amount of money being sent to the customer.
	TransactionID          string `json:"TransactionID,omitempty"`          // Organization Receiving the funds.
}

ReverseReq is used to reverse a transaction.

func (ReverseReq) Validate

func (r ReverseReq) Validate() error

Validate validate the struct.

type ReverseResp

type ReverseResp struct {
	ValidResp
}

ReverseResp is the response from the Reverse endpoint.

type SDK

type SDK interface {
	// GetToken gives you a time bound access token to call allowed APIs.
	//
	// Documentation: https://developer.safaricom.co.ke/APIs/Authorization
	//
	// Example:
	// 	token, err := mp.GetToken()
	// 	if err != nil {
	// 		log.Fatal(err)
	// 	}
	// 	log.Printf("Token: %+v\n", token)
	// Output:
	// 	2023/09/06 22:43:21 Token: {AccessToken:unU9joKpPqIsZ1jFiDmQoNJ1cIvK Expiry:3599}
	Token() (TokenResp, error)

	// ExpressQuery check the status of a Lipa Na M-Pesa Online Payment.
	//
	// Documentation: https://developer.safaricom.co.ke/APIs/MpesaExpressQuery
	//
	// Example:
	// 	eqReq := mpesa.ExpressQueryReq{
	// 		PassKey:           "bfb279f9aa9bdbcf158e97dd71a467cd2e0c893059b10f78e6b72ada1ed2c919", // Get this from the developer portal under the test credentials section
	// 		BusinessShortCode: 174379,
	// 		CheckoutRequestID: "ws_CO_07092023195244460712345678",
	// 	}
	//
	// 	resp, err := mp.ExpressQuery(eqReq)
	// 	if err != nil {
	// 		log.Fatal(err)
	// 	}
	//
	// 	log.Printf("Resp: %+v\n", resp)
	// Output:
	//  2023/09/07 20:08:05 Resp: {ResponseDescription:The service request has been accepted successsfully ResponseCode:0 MerchantRequestID:92643-47073138-2 CheckoutRequestID:ws_CO_07092023195244460712345678 CustomerMessage: ResultCode:1032 ResultDesc:Request cancelled by user}
	ExpressQuery(eqReq ExpressQueryReq) (ExpressQueryResp, error)

	// ExpressSimulate initiates online payment on behalf of a customer.
	//
	// Documentation: https://developer.safaricom.co.ke/APIs/MpesaExpressSimulate
	//
	// Example:
	// 	qrReq := mpesa.ExpressSimulateReq{
	// 		PassKey:           "bfb279f9aa9bdbcf158e97dd71a467cd2e0c893059b10f78e6b72ada1ed2c919", // Get this from the developer portal under the test credentials section
	// 		BusinessShortCode: 174379,
	// 		TransactionType:   "CustomerPayBillOnline",
	// 		PhoneNumber:       254712345678, // You can use your own phone number here
	// 		Amount:            10,
	// 		PartyA:            254712345678,
	// 		PartyB:            174379,
	// 		CallBackURL:       "https://69a2-105-163-2-116.ngrok.io",
	// 		AccountReference:  "CompanyXLTD",
	// 		TransactionDesc:   "Payment of X",
	// 	}
	//
	// 	resp, err := mp.ExpressSimulate(qrReq)
	// 	if err != nil {
	// 		log.Fatal(err)
	// 	}
	//
	// 	log.Printf("Resp: %+v\n", resp)
	// Output:
	//  2023/09/07 00:39:08 Resp: {ResponseDescription:Success. Request accepted for processing ResponseCode:0 MerchantRequestID:27260-79456854-2 CheckoutRequestID:ws_CO_07092023004130971712345678 CustomerMessage:Success. Request accepted for processing}
	ExpressSimulate(eReq ExpressSimulateReq) (ExpressSimulateResp, error)

	// B2CPayment Transact between an M-Pesa short code to a phone number registered on M-Pesa
	//
	// Documentation: https://developer.safaricom.co.ke/APIs/BusinessToCustomer
	//
	// Example:
	// 	b2cReq := mpesa.B2CPaymentReq{
	//      OriginatorConversationID: uuid.String(),
	// 		InitiatorName:            "testapi",
	// 		SecurityCredential:       "Safaricom111!",
	// 		CommandID:                "BusinessPayment",
	// 		Amount:                   10,
	// 		PartyA:                   174379,
	// 		PartyB:                   254712345678,
	// 		Remarks:                  "Test",
	// 		QueueTimeOutURL:          "https://69a2-105-163-2-116.ngrok.io",
	// 		ResultURL:                "https://69a2-105-163-2-116.ngrok.io",
	// 		Occasion:                 "Test",
	// 	}
	//
	// 	resp, err := mp.B2CPayment(b2cReq)
	// 	if err != nil {
	// 		log.Fatal(err)
	// 	}
	//
	// 	log.Printf("Resp: %+v\n", resp)
	// Output:
	//  2023/09/07 21:12:26 Resp: {ValidResp:{OriginatorConversationID: ConversationID:AG_20230907_2010325b025970fde878 ResponseDescription:Accept the service request successfully. ResponseCode:0}}
	B2CPayment(b2cReq B2CPaymentReq) (B2CPaymentResp, error)

	// AccountBalance Enquire the balance on an M-Pesa BuyGoods (Till Number)
	//
	// Documentation: https://developer.safaricom.co.ke/APIs/AccountBalance
	//
	// Example:
	// 	balReq := mpesa.AccountBalanceReq{
	// 		InitiatorName:     "testapi",
	// 		InitiatorPassword: "Safaricom999!*!",
	// 		CommandID:         "AccountBalance",
	// 		IdentifierType:    4,
	// 		PartyA:            600772,
	// 		QueueTimeOutURL:   "https://example.com/timeout",
	// 		ResultURL:         "https://example.com/result",
	// 		Remarks:           "test",
	// 	}
	//
	// 	resp, err := mp.AccountBalance(balReq)
	// 	if err != nil {
	// 		log.Fatal(err)
	// 	}
	//
	// 	log.Printf("Resp: %+v\n", resp)
	// Output:
	//  2023/09/07 22:05:44 Resp: {ValidResp:{OriginatorConversationID: ConversationID:AG_20230907_201045e9b4e4f9bcb4d6 ResponseDescription:Accept the service request successfully. ResponseCode:0}}
	AccountBalance(abReq AccountBalanceReq) (AccountBalanceResp, error)

	// C2BRegisterURL register validation and confirmation URLs on M-Pesa
	//
	// Documentation: https://developer.safaricom.co.ke/APIs/CustomerToBusinessRegisterURL
	//
	// Example:
	// 	c2bReq := mpesa.C2BRegisterURLReq{
	// 		ShortCode: 174379,
	// 		ResponseType: "Completed",
	// 		ConfirmationURL: "https://69a2-105-163-2-116.ngrok.io",
	// 		ValidationURL: "https://69a2-105-163-2-116.ngrok.io",
	// 	}
	//
	// 	resp, err := mp.C2BRegisterURL(c2bReq)
	// 	if err != nil {
	// 		log.Fatal(err)
	// 	}
	//
	// 	log.Printf("Resp: %+v\n", resp)
	// Output:
	//  2023/09/07 20:23:39 Resp: {ValidResp:{OriginatorConversationID:29607-261203248-2 ConversationID: ResponseDescription:Success ResponseCode:0}}
	C2BRegisterURL(c2bReq C2BRegisterURLReq) (C2BRegisterURLResp, error)

	// C2BSimulate Make payment requests from Client to Business (C2B)
	//
	// Documentation: https://developer.safaricom.co.ke/APIs/CustomerToBusinessRegisterURL
	//
	// Example:
	// 	c2bReq := mpesa.C2BSimulateReq{
	// 		ShortCode: 174379,
	// 		CommandID: "CustomerPayBillOnline",
	// 		Amount: 10,
	// 		Msisdn: 254712345678,
	// 		BillRefNumber: "",
	// 	}
	//
	// 	resp, err := mp.C2BSimulate(c2bReq)
	// 	if err != nil {
	// 		log.Fatal(err)
	// 	}
	//
	// 	log.Printf("Resp: %+v\n", resp)
	// Output:
	//  2023/09/07 20:33:56 Resp: {ValidResp:{OriginatorConversationID:92647-47234949-2 ConversationID: ResponseDescription:Accept the service request successfully. ResponseCode:0}}
	C2BSimulate(c2bReq C2BSimulateReq) (C2BSimulateResp, error)

	// GenerateQR generates a dynamic M-PESA QR Code.
	//
	// Documentation: https://developer.safaricom.co.ke/APIs/DynamicQRCode
	//
	// Example:
	// 	qrReq := mpesa.GenerateQRReq{
	// 		MerchantName: "Test Supermarket",
	// 		RefNo:        "Invoice No",
	// 		Amount:       "2000",
	// 		TrxCode:      "BG",
	// 		CPI:          "174379",
	// 		Size:         "300",
	// 	}
	// 	qrcode, err := mp.GenerateQR(qrReq)
	// 	if err != nil {
	// 		log.Fatal(err)
	// 	}
	// 	log.Printf("QR Code: %+v\n", qrcode)
	// Output:
	//  2023/09/06 23:22:51 QR Code: {ResponseDescription:The service request is processed successfully. ResponseCode:00 RequestID: QRCode:...}
	GenerateQR(qReq GenerateQRReq) (GenerateQRResp, error)

	// Reverse Reverses an M-Pesa transaction.
	//
	// Documentation: https://developer.safaricom.co.ke/APIs/Reversal
	//
	// Example:
	// 	rReq := mpesa.ReverseReq{
	// 		InitiatorName:          "testapi",
	// 		InitiatorPassword:      "Safaricom999!*!",
	// 		CommandID:              "TransactionReversal",
	// 		TransactionID:          "RI704KI9RW",
	// 		Amount:                 10,
	// 		ReceiverParty:          600992,
	// 		RecieverIdentifierType: 11,
	// 		QueueTimeOutURL:        "https://example.com/timeout",
	// 		ResultURL:              "https://example.com/result",
	// 		Remarks:                "test",
	// 		Occasion:               "test",
	// 	}
	//
	// 	resp, err := mp.Reverse(rReq)
	// 	if err != nil {
	// 		log.Fatal(err)
	// 	}
	//
	// 	log.Printf("Resp: %+v\n", resp)
	// Output:
	//  2023/09/07 22:11:13 Resp: {ValidResp:{OriginatorConversationID: ConversationID:AG_20230907_20106204c62f8f1a3f21 ResponseDescription:Accept the service request successfully. ResponseCode:0}}
	Reverse(rReq ReverseReq) (ReverseResp, error)

	// TransactionStatus check the status of a transaction
	//
	// Documentation: https://developer.safaricom.co.ke/APIs/TransactionStatus
	//
	// Example:
	// 	tReq := mpesa.TransactionStatusReq{
	// 		InitiatorName:     "testapi",
	// 		InitiatorPassword: "Safaricom999!*!",
	// 		CommandID:         "TransactionStatusQuery",
	// 		IdentifierType:    1,
	// 		TransactionID:     "RI704KI9RW",
	// 		PartyA:            254759764065,
	// 		QueueTimeOutURL:   "https://example.com/timeout",
	// 		ResultURL:         "https://example.com/result",
	// 		Remarks:           "test",
	// 		Occasion:          "test",
	// 	}
	//
	// 	resp, err := mp.TransactionStatus(tReq)
	// 	if err != nil {
	// 		log.Fatal(err)
	// 	}
	//
	// 	log.Printf("Resp: %+v\n", resp)
	// Output:
	//  2023/09/07 21:56:50 Resp: {ValidResp:{OriginatorConversationID: ConversationID:AG_20230907_20102e33b7103b4f7b0e ResponseDescription:Accept the service request successfully. ResponseCode:0}}
	TransactionStatus(tReq TransactionStatusReq) (TransactionStatusResp, error)

	// RemitTax enables businesses to remit tax to Kenya Revenue Authority (KRA).
	//
	// Documentation: https://developer.safaricom.co.ke/APIs/TaxRemittance
	//
	// Example:
	// 	taxReq := mpesa.RemitTax{
	// 		InitiatorName:          "testapi",
	// 		InitiatorPassword:      "Safaricom999!*!",
	// 		CommandID:              "PayTaxToKRA",
	// 		SenderIdentifierType:   4,
	// 		RecieverIdentifierType: 4,
	// 		Amount:                 239,
	// 		PartyA:                 600978,
	// 		PartyB:                 572572,
	// 		AccountReference:       "353353",
	// 		QueueTimeOutURL:        "https://example.com/timeout",
	// 		ResultURL:              "https://example.com/result",
	// 		Remarks:                "test",
	// 	}
	//
	// 	resp, err := mp.RemitTax(taxReq)
	// 	if err != nil {
	// 		log.Fatal(err)
	// 	}
	//
	// 	log.Printf("Resp: %+v\n", resp)
	// Output:
	//  2023/09/07 22:30:00 Resp: {ValidResp:{OriginatorConversationID: ConversationID:AG_20230907_201001484b176c67b3fb ResponseDescription:Accept the service request successfully. ResponseCode:0}}
	RemitTax(rReq RemitTaxReq) (RemitTaxResp, error)
}

SDK contains MpesaOverlay interface API.

func NewSDK

func NewSDK(conf Config, opts ...Option) (SDK, error)

NewSDK returns new mpesa SDK instance.

type TokenResp

type TokenResp struct {
	AccessToken string `json:"access_token,omitempty"` // Access token to access other APIs
	Expiry      string `json:"expires_in,omitempty"`   // Token expiry time in seconds
}

TokenResp is the response from the token endpoint.

type TransactionStatusReq

type TransactionStatusReq struct {
	CommandID          string `json:"CommandID,omitempty"`          // Takes only the 'TransactionStatusQuery' Command ID.
	PartyA             uint64 `json:"PartyA,omitempty"`             // Organization/MSISDN receiving the transaction
	IdentifierType     uint8  `json:"IdentifierType,omitempty"`     // Type of organization receiving the transaction
	Remarks            string `json:"Remarks,omitempty"`            // Comments that are sent along with the transaction.
	InitiatorName      string `json:"Initiator,omitempty"`          // The name of Initiator to initiating  the request
	InitiatorPassword  string `json:"InitiatorPassword,omitempty"`  // The password of the API user. This is the same password used while creating the API user.
	SecurityCredential string `json:"SecurityCredential,omitempty"` // Encrypted Credential of user getting transaction amoun
	QueueTimeOutURL    string `json:"QueueTimeOutURL,omitempty"`    // The path that stores information of time out transaction
	ResultURL          string `json:"ResultURL,omitempty"`          // The path that stores information of transaction
	TransactionID      string `json:"TransactionID,omitempty"`      // Unique identifier to identify a transaction on M-Pesa
	Occasion           string `json:"Occasion,omitempty"`
}

TransactionStatusReq is used to query the status of a transaction.

func (TransactionStatusReq) Validate

func (r TransactionStatusReq) Validate() error

Validate validate the struct.

type TransactionStatusResp

type TransactionStatusResp struct {
	ValidResp
}

TransactionStatusResp is the response from the TransactionStatus endpoint.

type ValidResp

type ValidResp struct {
	OriginatorConversationID string `json:"OriginatorCoversationID,omitempty"` // The unique request ID for tracking a transaction
	ConversationID           string `json:"ConversationID,omitempty"`          // The unique request ID returned by mpesa for each request made
	ResponseDescription      string `json:"ResponseDescription,omitempty"`     // Response Description message
	ResponseCode             string `json:"ResponseCode,omitempty"`            // It indicates whether Mobile Money accepts the request or not.
}

ValidResp is a common response for all endpoints.

Directories

Path Synopsis
Package middleware provides a set of middleware for use with MpesaOverlay.
Package middleware provides a set of middleware for use with MpesaOverlay.
database
Package database provides a middleware for database.
Package database provides a middleware for database.
database/postgres
Package postgres implements the postgres database for the logging middleware to be used with MpesaOverlay SDK.
Package postgres implements the postgres database for the logging middleware to be used with MpesaOverlay SDK.
logging
Package logging provides a middleware for logging.
Package logging provides a middleware for logging.
logging/logrus
Package logrus implements the logrus logger for the logging middleware to be used with MpesaOverlay SDK.
Package logrus implements the logrus logger for the logging middleware to be used with MpesaOverlay SDK.
logging/slog
Package slog implements the slog logger for the logging middleware to be used with MpesaOverlay SDK.
Package slog implements the slog logger for the logging middleware to be used with MpesaOverlay SDK.
logging/zap
Package zap implements the zap logger for the logging middleware to be used with MpesaOverlay SDK.
Package zap implements the zap logger for the logging middleware to be used with MpesaOverlay SDK.
metrics
Package metrics provides a middleware for metrics.
Package metrics provides a middleware for metrics.
metrics/prometheus
Package prometheus provides a Prometheus metrics middleware for the MpesaOverlay API.
Package prometheus provides a Prometheus metrics middleware for the MpesaOverlay API.

Jump to

Keyboard shortcuts

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