mpesa

package module
v1.0.8 Latest Latest
Warning

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

Go to latest
Published: Feb 1, 2024 License: MIT Imports: 21 Imported by: 4

README

[WIP]: About Mpesa Golang SDK

Mpesa Golang SDK facilitates in integrating M-pesa APIS into your go project. The following APIs are currently supported:

API Description
Authorization Generates an access token for authenticating APIs
Lipa Na M-Pesa Online API Initiates online payment on behalf of a customer.
Business To Customer (B2C) Transact between an M-Pesa short code to a phone number registered on M-Pesa.
M-Pesa Express Query Check the status of a Lipa Na M-Pesa Online Payment.
Dynamic QR Generates a dynamic M-PESA QR Code which enables Safaricom M-PESA customers who have My Safaricom App or M-PESA app, to scan a QR (Quick Response) code, to capture till number and amount then authorize to pay for goods and services at select LIPA NA M-PESA (LNM) merchant outlets.
Transaction Status Check the status of a transaction.
Account Balance Enquire the balance on an M-Pesa BuyGoods (Till Number).
Business Pay Bill This API enables you to pay bills directly from your business account to a pay bill number, or a paybill store.

Getting Started

To use the APIs, follow these steps:

  1. Register or login to your account on Daraja
  2. Create a new or view existing apps here
  3. Copy the app credentials. To prevent exposing you API keys, you can store them on configuration file such as .env or config.yml.

Installation

  go get github.com/jwambugu/mpesa-golang-sdk

Usage/Examples

Environments

The SDK supports the following environments:

  1. mpesa.Sandbox for test environment.
  2. mpesa.Production for production environment once you go live.
Examples

More examples can be found here

package main

import (
    "context"
    "github.com/jwambugu/mpesa-golang-sdk"
    "log"
    "net/http"
    "time"
)

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	mpesaApp := mpesa.NewApp(http.DefaultClient, "CONSUMER_KEY", "CONSUMER_SECRET", mpesa.EnvironmentSandbox)

	stkResp, err := mpesaApp.STKPush(ctx, "YOUR_PASSKEY", mpesa.STKPushRequest{
		BusinessShortCode: 174379,
		TransactionType:   mpesa.CustomerPayBillOnlineTransactionType,
		Amount:            10,
		PartyA:            254708374149,
		PartyB:            174379,
		PhoneNumber:       254708374149,
		CallBackURL:       "https://webhook.site/62daf156-31dc-4b07-ac41-698dbfadaa4b",
		AccountReference:  "Test reference",
		TransactionDesc:   "Test description",
	})

	if err != nil {
		log.Fatalf("stk: %v\n", err)
	}

	log.Printf("stk: %+v\n", stkResp)

	stkQueryRes, err := mpesaApp.STKQuery(ctx, "YOUR_PASSKEY", mpesa.STKQueryRequest{
		BusinessShortCode: 174379,
		CheckoutRequestID: "ws_CO_260520211133524545",
	})

	if err != nil {
		log.Fatalf("stk query: %v\n", err)
	}

	log.Printf("stk query %+v\n", stkQueryRes)

}
Processing Callbacks

The SDK adds a helper functions to decode callbacks. These are:

  1. mpesa.UnmarshalSTKPushCallback(v)
  2. mpesa.UnmarshalCallback(v) for all other callbacks received
mux.HandleFunc("/callback", func(w http.ResponseWriter, r *http.Request) {
callback, err := mpesa.UnmarshalB2CCallback(r.Body)
    if err != nil {
        log.Fatalln(err)
    }
    
    log.Printf("%+v", callback)
})


data := strings.NewReader(`
	{
	   "Body": {
		  "stkCallback": {
			 "MerchantRequestID": "29115-34620561-1",
			 "CheckoutRequestID": "ws_CO_191220191020363925",
			 "ResultCode": 1032,
			 "ResultDesc": "Request cancelled by user."
		  }
	   }
	}`)

callback, err := mpesa.UnmarshalSTKPushCallback(data)ack()

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

log.Printf("%+v", callback)

Documentation

Index

Constants

View Source
const (
	// CustomerBuyGoodsOnlineTransactionType us used to STK push requests for till numbers.
	CustomerBuyGoodsOnlineTransactionType = "CustomerBuyGoodsOnline"

	// CustomerPayBillOnlineTransactionType us used to STK push requests for paybill numbers.
	CustomerPayBillOnlineTransactionType = "CustomerPayBillOnline"
)

Variables

View Source
var (
	// ErrInvalidPasskey indicates that no passkey was provided.
	ErrInvalidPasskey = errors.New("mpesa: passkey cannot be empty")

	// ErrInvalidInitiatorPassword indicates that no initiator password was provided.
	ErrInvalidInitiatorPassword = errors.New("mpesa: initiator password cannot be empty")
)

Functions

This section is empty.

Types

type AccountBalanceRequest added in v1.0.8

type AccountBalanceRequest struct {
	// The CommandID for the request - AccountBalanceCommandID
	CommandID CommandID `json:"CommandID"`

	// IdentifierType is the type of organization fetching the balance - Shortcode (Till Number Organization shortcode)
	IdentifierType IdentifierType `json:"IdentifierType"`

	// Initiator is the credential/username used to authenticate the request.
	Initiator string `json:"Initiator"`

	// PartyA is the shortcode of the organization querying for the account balance.
	PartyA int `json:"PartyA"`

	// QueueTimeOutURL is the endpoint that will be used by API Proxy to send notification incase the request is timed
	// out while awaiting processing in the queue. Must be served via https.
	QueueTimeOutURL string `json:"QueueTimeOutURL"`

	// Remarks are comments that are sent along with the transaction. They are a sequence of characters up to 100
	Remarks string `json:"Remarks"`

	// ResultURL is the endpoint that will be used by M-PESA to send notification upon processing of the request.
	// Must be served via https.
	ResultURL string `json:"ResultURL"`

	// SecurityCredential is an encrypted password for the initiator to authenticate the request
	SecurityCredential string `json:"SecurityCredential"`
}

type AuthorizationResponse added in v1.0.5

type AuthorizationResponse struct {
	AccessToken string `json:"access_token"`
	ExpiresIn   string `json:"expires_in"`
	// contains filtered or unexported fields
}

AuthorizationResponse is returned when trying to authenticate the app using provided credentials

type B2CRequest added in v1.0.5

type B2CRequest struct {
	// InitiatorName is the username of the M-Pesa B2C account API operator. The access channel for this operator
	// must be API and the account must be in active status.
	InitiatorName string `json:"InitiatorName"`

	// SecurityCredential is the value obtained after encrypting the API initiator password.
	SecurityCredential string `json:"SecurityCredential"`

	/*
		CommandID is a unique command that specifies B2C transaction type.
			- SalaryPaymentCommandID: This supports sending money to both registered and unregistered M-Pesa customers.
			- BusinessPaymentCommandID: This is a normal business to customer payment,supports only M-Pesa registered customers.
			- PromotionPaymentCommandID: This is a promotional payment to customers. The M-Pesa notification message is a
			congratulatory message and supports only M-Pesa registered customers.
	*/
	CommandID CommandID `json:"CommandID"`

	// Amount to be sent to the customer.
	Amount uint `json:"Amount"`

	// PartyA is the B2C organization shortcode from which the money is to be from.
	PartyA uint `json:"PartyA"`

	// PartyB is the customer mobile number to receive the amount which should have the country code (254).
	PartyB uint64 `json:"PartyB"`

	// Remarks represents any additional information to be associated with the transaction.
	Remarks string `json:"Remarks"`

	// QueueTimeOutURL is the URL to be specified in your request that will be used by API Proxy to send
	// notification in-case the payment request is timed out while awaiting processing in the queue.
	QueueTimeOutURL string `json:"QueueTimeOutURL"`

	// ResultURL 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.
	ResultURL string `json:"ResultURL"`

	// Occasion is any additional information to be associated with the transaction.
	Occasion string `json:"Occasion"`
}

type BusinessPayBillRequest added in v1.0.8

type BusinessPayBillRequest struct {
	// AccountReference is account number to be associated with the payment. Up to 13 characters.
	AccountReference string `json:"AccountReference"`

	// Amount is the transaction amount.
	Amount uint `json:"Amount"`

	// The CommandID for the request - BusinessPayBillCommandID
	CommandID CommandID `json:"CommandID"`

	// Initiator is the credential/username used to authenticate the request.
	Initiator string `json:"Initiator"`

	// Occasion is an optional paramater that is a sequence of characters up to 100
	Occasion string `json:"Occasion"`

	// PartyA is your shortcode. The shortcode from which money will be deducted.
	PartyA uint `json:"PartyA"`

	// PartyB is the shortcode to which money will be moved to.
	PartyB uint `json:"PartyB"`

	// QueueTimeOutURL is the endpoint that will be used by API Proxy to send notification incase the request is
	//timed out while awaiting processing in the queue. Must be served via https.
	QueueTimeOutURL string `json:"QueueTimeOutURL"`

	// RecieverIdentifierType is the type of shortcode to which money is credited. This API supports type
	// ShortcodeIdentifierType only
	RecieverIdentifierType IdentifierType `json:"RecieverIdentifierType"`

	// Remarks are comments that are sent along with the transaction. They are a sequence of characters up to 100
	Remarks string `json:"Remarks"`

	// Optional. Requester is the consumer’s mobile number on behalf of whom you are paying.
	Requester int64 `json:"Requester"`

	// ResultURL is the endpoint that will be used by M-PESA to send notification upon processing of the request.
	// Must be served via https.
	ResultURL string `json:"ResultURL"`

	// SecurityCredential is an encrypted password for the initiator to authenticate the request
	SecurityCredential string `json:"SecurityCredential"`

	// SenderIdentifierType is the type of shortcode from which money is deducted.
	// For this API, only ShortcodeIdentifierType is allowed
	SenderIdentifierType IdentifierType `json:"SenderIdentifierType"`
}

type Callback added in v1.0.8

type Callback struct {
	// Result is the root parameter that encloses the entire result message.
	Result CallbackResult `json:"Result"`
}

func UnmarshalCallback added in v1.0.8

func UnmarshalCallback(r io.Reader) (*Callback, error)

UnmarshalCallback decodes the provided value to Callback

type CallbackResult added in v1.0.8

type CallbackResult struct {
	// ConversationID is a global unique identifier for the transaction request returned by the M-Pesa
	// upon successful request submission.
	ConversationID string `json:"ConversationID"`

	// OriginatorConversationID is a global unique identifier for the transaction request returned by the API
	// proxy upon successful request submission.
	OriginatorConversationID string `json:"OriginatorConversationID"`

	ReferenceData ReferenceData `json:"ReferenceData"`

	// ResultCode is a numeric status code that indicates the status of the transaction processing.
	// 0 means success and any other code means an error occurred or the transaction failed.
	ResultCode int `json:"ResultCode"`

	// ResultDesc is a message from the API that gives the status of the request processing and usually maps to
	// a specific ResultCode value.
	ResultDesc string `json:"ResultDesc"`

	// ResultParameters is a JSON object that holds more details for the transaction.
	ResultParameters ResultParameters `json:"ResultParameters"`

	// ResultType is a status code that indicates whether the transaction was already sent to your listener.
	// Usual value is 0.
	ResultType int `json:"ResultType"`

	// TransactionID is a unique M-PESA transaction ID for every payment request. Same value is sent to customer
	// over SMS upon successful processing.
	TransactionID string `json:"TransactionID"`
}

type CommandID added in v1.0.8

type CommandID string

CommandID is a unique command that specifies B2C transaction type.

const (
	// AccountBalanceCommandID is applied when getting the account balance of a shortcode
	AccountBalanceCommandID CommandID = "AccountBalance"

	// BusinessPayBillCommandID is applied for BusinessPayBillRequest
	BusinessPayBillCommandID CommandID = "BusinessPayBill"

	// BusinessPaymentCommandID is a normal business to customer payment, supports only M-PESA registered customers.
	BusinessPaymentCommandID CommandID = "BusinessPayment"

	// PromotionPaymentCommandID is a promotional payment to customers. The M-PESA notification message is a congratulatory
	// message. Supports only M-PESA registered customers.
	PromotionPaymentCommandID CommandID = "PromotionPayment"

	// SalaryPaymentCommandID is used for sending money to both registered and unregistered M-Pesa customers.
	SalaryPaymentCommandID CommandID = "SalaryPayment"

	// TransactionStatusQueryCommandID is applied when getting the status of a transaction.
	TransactionStatusQueryCommandID CommandID = "TransactionStatusQuery"
)

type DynamicQRRequest added in v1.0.8

type DynamicQRRequest struct {
	// Total Amount for the sale or transaction
	Amount uint `json:"Amount"`

	// CreditPartyIdentifier can be a Mobile Number, Business Number, Agent Till, Paybill or Business number, or Merchant Buy Goods.
	CreditPartyIdentifier string `json:"CPI"`

	// MerchantName is the name of the Company/M-Pesa merchant
	MerchantName string `json:"MerchantName"`

	// ReferenceNo is the transaction reference number.
	ReferenceNo string `json:"RefNo"`

	// Size of the QR code image in pixels. QR code image will always be a square image.
	Size string `json:"Size"`

	/*
		TransactionType represents the type of transaction being made.
			- PayMerchantBuyGoods: Pay Merchant (Buy Goods).
			- WithdrawCashAtAgentTill: Withdraw Cash at Agent Till.
			- PaybillOrBusinessNumber: Paybill or Business number.
			- SendMoneyViaMobileNumber: Send Money(Mobile number)
			- SentToBusiness: Sent to Business. Business number CPI in MSISDN format.
	*/
	TransactionType DynamicQRTransactionType `json:"TrxCode"`
}

type DynamicQRResponse added in v1.0.8

type DynamicQRResponse struct {
	// ImagePath is the absolute path to the decoded base64 image
	ImagePath string `json:"qr_path,omitempty"`

	// ErrorCode is a predefined code that indicates the reason for request failure that is defined in the
	// ErrorMessage. The error codes maps to specific error message.
	ErrorCode string `json:"errorCode,omitempty"`

	// ErrorMessage is a short descriptive message of the failure reason.
	ErrorMessage string `json:"errorMessage,omitempty"`

	// QRCode Image/Data/String.
	QRCode string `json:"QRCode,omitempty"`

	// RequestID represents the ID for the request
	RequestID string `json:"requestId,omitempty"`

	// ResponseCode is a numeric status code that indicates the status of the transaction submission.
	ResponseCode string `json:"ResponseCode,omitempty"`

	// ResponseDescription is a response describing the status of the transaction.
	ResponseDescription string `json:"ResponseDescription,omitempty"`
}

type DynamicQRTransactionType added in v1.0.8

type DynamicQRTransactionType string

DynamicQRTransactionType represents the supported transaction types for the Dynamic QR API

const (
	PayMerchantBuyGoods      DynamicQRTransactionType = "BG"
	PaybillOrBusinessNumber  DynamicQRTransactionType = "PB"
	SendMoneyViaMobileNumber DynamicQRTransactionType = "SM"
	SentToBusiness           DynamicQRTransactionType = "SB"
	WithdrawCashAtAgentTill  DynamicQRTransactionType = "WA"
)

type Environment added in v1.0.5

type Environment uint8

Environment indicates the current mode the application is running on. Either EnvironmentSandbox or EnvironmentProduction.

const (
	EnvironmentSandbox Environment = iota
	EnvironmentProduction
)

func (Environment) BaseURL added in v1.0.8

func (e Environment) BaseURL() string

BaseURL returns the base url for the current Environment

func (Environment) IsProduction added in v1.0.5

func (e Environment) IsProduction() bool

IsProduction returns true if the current env is set to production.

type HttpClient added in v1.0.5

type HttpClient interface {
	Do(req *http.Request) (*http.Response, error)
}

type IdentifierType added in v1.0.8

type IdentifierType uint8

IdentifierType is the type of organization receiving the transaction

const ShortcodeIdentifierType IdentifierType = 4

type Mpesa

type Mpesa struct {
	// contains filtered or unexported fields
}

Mpesa is an app to make a transaction

func NewApp added in v1.0.5

func NewApp(c HttpClient, consumerKey, consumerSecret string, env Environment) *Mpesa

NewApp initializes a new Mpesa app that will be used to perform C2B or B2C transactions.

func (*Mpesa) B2C added in v1.0.5

func (m *Mpesa) B2C(ctx context.Context, initiatorPwd string, req B2CRequest) (*Response, error)

B2C transacts between an M-Pesa short code to a phone number registered on M-Pesa

func (*Mpesa) BusinessPayBill added in v1.0.8

func (m *Mpesa) BusinessPayBill(ctx context.Context, initiatorPwd string, req BusinessPayBillRequest) (*Response, error)

BusinessPayBill API enables you to pay bills directly from your business account to a pay bill number, or a paybill store. You can use this API to pay on behalf of a consumer/requester.

The transaction moves money from your MMF/Working account to the recipient’s utility account.

func (*Mpesa) DynamicQR added in v1.0.8

func (m *Mpesa) DynamicQR(
	ctx context.Context, req DynamicQRRequest, transactionType DynamicQRTransactionType, decodeImage bool,
) (*DynamicQRResponse, error)

DynamicQR API is used to generate a Dynamic QR which enables Safaricom M-PESA customers who have My Safaricom App or M-PESA app, to scan a QR (Quick Response) code, to capture till number and amount then authorize to pay for goods and services at select LIPA NA M-PESA (LNM) merchant outlets. If the decodeImage parameter is set to true, the QR code will be decoded and a base url is set on the ImagePath field

func (*Mpesa) Environment

func (m *Mpesa) Environment() Environment

Environment returns the current environment the app is running on.

func (*Mpesa) GenerateAccessToken added in v1.0.5

func (m *Mpesa) GenerateAccessToken(ctx context.Context) (string, error)

GenerateAccessToken returns a time bound access token to call allowed APIs. This token should be used in all other subsequent responses to the APIs GenerateAccessToken will also cache the access token for the specified refresh after period

func (*Mpesa) GetAccountBalance added in v1.0.8

func (m *Mpesa) GetAccountBalance(
	ctx context.Context, initiatorPwd string, req AccountBalanceRequest,
) (*Response, error)

GetAccountBalance fetches the account balance of a short code. This can be used for both B2C, buy goods and pay bill accounts.

func (*Mpesa) GetTransactionStatus added in v1.0.8

func (m *Mpesa) GetTransactionStatus(
	ctx context.Context, initiatorPwd string, req TransactionStatusRequest,
) (*Response, error)

GetTransactionStatus checks the status of a transaction

func (*Mpesa) RegisterC2BURL added in v1.0.8

func (m *Mpesa) RegisterC2BURL(ctx context.Context, req RegisterC2BURLRequest) (*Response, error)

RegisterC2BURL API works hand in hand with Customer to Business (C2B) APIs and allows receiving payment notifications to your paybill. This API enables you to register the callback URLs via which you shall receive notifications for payments to your pay bill/till number. There are two URLs required for Register URL API: Validation URL and Confirmation URL. Validation URL: This is the URL that is only used when a Merchant (Partner) requires to validate the details of the payment before accepting. For example, a bank would want to verify if an account number exists in their platform before accepting a payment from the customer. Confirmation URL: This is the URL that receives payment notification once payment has been completed successfully on M-PESA.

func (*Mpesa) STKPush added in v1.0.5

func (m *Mpesa) STKPush(ctx context.Context, passkey string, req STKPushRequest) (*Response, error)

STKPush initiates online payment on behalf of a customer using STKPush.

func (*Mpesa) STKQuery added in v1.0.7

func (m *Mpesa) STKQuery(ctx context.Context, passkey string, req STKQueryRequest) (*Response, error)

STKQuery checks the status of an STKPush payment.

type ReferenceData added in v1.0.8

type ReferenceData struct {
	ReferenceItem ReferenceItem `json:"ReferenceItem"`
}

type ReferenceItem added in v1.0.8

type ReferenceItem struct {
	Key   string `json:"Key"`
	Value string `json:"Value"`
}

type RegisterC2BURLRequest added in v1.0.8

type RegisterC2BURLRequest struct {
	// ShortCode is usually, a unique number is tagged to an M-PESA pay bill/till number of the organization.
	ShortCode uint `json:"ShortCode"`

	// ResponseType This parameter specifies what is to happen if for any reason the validation URL is not reachable.
	// Note that, this is the default action value that determines what M-PESA will do in the scenario that
	//your endpoint is unreachable or is unable to respond on time. Only two values are allowed: Completed or Cancelled.
	// Completed means M-PESA will automatically complete your transaction, whereas Cancelled means M-PESA will
	// automatically cancel the transaction, in the event M-PESA is unable to reach your Validation URL.
	ResponseType ResponseType `json:"ResponseType"`

	// ConfirmationURL is the URL that receives the confirmation request from API upon payment completion.
	ConfirmationURL string `json:"ConfirmationURL"`

	// ValidationURL is the URL that receives the validation request from the API upon payment submission.
	// The validation URL is only called if the external validation on the registered shortcode is enabled.
	// (By default External Validation is disabled).
	ValidationURL string `json:"ValidationURL"`
}

type Response added in v1.0.8

type Response struct {
	// CheckoutRequestID is a global unique identifier of the processed checkout transaction request.
	// Example: ws_CO_DMZ_12321_23423476
	CheckoutRequestID string `json:"CheckoutRequestID,omitempty"`

	// ConversationID is a global unique identifier for the transaction request returned by the M-Pesa upon successful
	// request submission.
	ConversationID string `json:"ConversationID,omitempty"`

	// CustomerMessage is a message that your system can display to the Customer as an acknowledgement of the
	// payment request submission. Example: Success. Request accepted for processing.
	CustomerMessage string `json:"CustomerMessage,omitempty"`

	// ErrorCode is a predefined code that indicates the reason for request failure that is defined in the
	// ErrorMessage. The error codes maps to specific error message.
	ErrorCode string `json:"errorCode,omitempty"`

	// ErrorMessage is a short descriptive message of the failure reason.
	ErrorMessage string `json:"errorMessage,omitempty"`

	// MerchantRequestID is a global unique Identifier for any submitted payment request. Example: 16813-1590513-1
	MerchantRequestID string `json:"MerchantRequestID,omitempty"`

	// OriginatorConversationID is a global unique identifier for the transaction request returned by the API proxy
	// upon successful request submission.
	OriginatorConversationID string `json:"OriginatorConversationID,omitempty"`

	// ResponseCode 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.
	ResponseCode string `json:"ResponseCode,omitempty"`

	// ResponseDescription is an acknowledgment message from the API that gives the status of the request submission.
	// It usually maps to a specific ResponseCode value which can be a success message or an error description.
	ResponseDescription string `json:"ResponseDescription,omitempty"`

	// ResultCode is a numeric status code that indicates the status of the transaction processing.
	// 0 means successful processing and any other code means an error occured or the transaction failed.
	ResultCode string `json:"ResultCode,omitempty"`

	// ResultDesc description is a message from the API that gives the status of the request processing, usualy maps
	// to a specific ResultCode value. It can be a success or an error description message.
	ResultDesc string `json:"ResultDesc,omitempty"`

	// RequestID is a unique request ID for the payment request
	RequestID string `json:"requestId,omitempty"`
}

Response is the response sent back by mpesa after initiating a request.

type ResponseType added in v1.0.8

type ResponseType string
const (
	ResponseTypeCanceled ResponseType = "Canceled"
	ResponseTypeComplete ResponseType = "Completed"
)

type ResultParameter added in v1.0.5

type ResultParameter struct {
	Key   string      `json:"Key"`
	Value interface{} `json:"Value"`
}

ResultParameter holds additional transaction details. Details available: 1:

type ResultParameters added in v1.0.8

type ResultParameters struct {
	// ResultParameter is a JSON array within the ResultParameters.
	ResultParameter []ResultParameter `json:"ResultParameter"`
}

type STKCallback added in v1.0.5

type STKCallback struct {
	// MerchantRequestID is a global unique Identifier for any submitted payment request. It is the same
	// value returned to the acknowledgement message on the Response.
	MerchantRequestID string `json:"MerchantRequestID"`

	// CheckoutRequestID is a global unique identifier of the processed checkout transaction request.
	// It is the same value returned to the acknowledgement message on the Response.
	CheckoutRequestID string `json:"CheckoutRequestID"`

	// ResultCode 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.
	ResultCode int `json:"ResultCode"`

	// ResultDesc is a message from the API that gives the status of the request processing. It usually maps
	// to a specific ResultCode value. It can be a success or an error description message.
	ResultDesc string `json:"ResultDesc"`

	// CallbackMetadata is the JSON object that holds more details for the transaction.
	// It is only returned for successful transaction.
	//
	// Successful transaction contains this sample payload:
	//
	// {
	//   "CallbackMetadata":{
	//      "Item":[
	//         {
	//            "Name":"Amount",
	//            "Value":1.00
	//         },
	//         {
	//            "Name":"MpesaReceiptNumber",
	//            "Value":"NLJ7RT61SV"
	//         },
	//         {
	//            "Name":"TransactionDate",
	//            "Value":20191219102115
	//         },
	//         {
	//            "Name":"PhoneNumber",
	//            "Value":254708374149
	//         }
	//      ]
	//   }
	// }
	//
	CallbackMetadata STKCallbackMetadata `json:"CallbackMetadata"`
}

type STKCallbackItem added in v1.0.5

type STKCallbackItem struct {
	Name  string      `json:"Name"`
	Value interface{} `json:"Value,omitempty"`
}

type STKCallbackMetadata added in v1.0.5

type STKCallbackMetadata struct {
	// Item is a JSON Array, within the CallbackMetadata, that holds additional transaction details in
	// JSON objects. It is only returned for Successful transaction as part of CallbackMetadata
	Item []STKCallbackItem `json:"Item"`
}

type STKPushCallback added in v1.0.5

type STKPushCallback struct {
	// Body is the root key for the entire callback message.
	Body STKPushCallbackBody `json:"Body"`
}

STKPushCallback is the response sent back sent to the callback URL after making the STKPushRequest

func UnmarshalSTKPushCallback added in v1.0.5

func UnmarshalSTKPushCallback(r io.Reader) (*STKPushCallback, error)

UnmarshalSTKPushCallback decodes the provided value to STKPushCallback.

type STKPushCallbackBody added in v1.0.5

type STKPushCallbackBody struct {
	// STKCallback stores the data related to the request.
	STKCallback STKCallback `json:"stkCallback"`
}

type STKPushRequest

type STKPushRequest struct {
	// BusinessShortCode is organizations shortcode (Paybill or Buy goods - A 5 to 7-digit account number) used to
	// identify an organization and receive the transaction.
	BusinessShortCode uint `json:"BusinessShortCode"`

	// Password is a base64 encoded string used for encrypting the request sent which is a combination of
	// BusinessShortCode + Passkey + Timestamp
	Password string `json:"Password"`

	// Timestamp of the transaction in the format of YEAR+MONTH+DATE+HOUR+MINUTE+SECOND (YYYYMMDDHHmmss).
	// Each part should be at least two digits apart from the year which takes four digits.
	// Example 20060102150405
	Timestamp string `json:"Timestamp"`

	// TransactionType identifies the transaction when sending the request to M-Pesa. Expects CustomerPayBillOnline
	// or CustomerBuyGoodsOnline
	TransactionType TransactionType `json:"TransactionType"`

	// Amount to be transacted which will be deducted from the customer.
	Amount uint `json:"Amount,omitempty"`

	// PartyA is phone number sending money. The parameter expected is a valid Safaricom Mobile Number that is
	// M-Pesa registered in the format 2547XXXXXXXX
	PartyA uint `json:"PartyA"`

	// PartyB is the organization receiving the funds. The parameter expected is a 5 to 7 digit as defined on
	// the Shortcode description which can also be the same as BusinessShortCode value.
	PartyB uint `json:"PartyB"`

	// PhoneNumber to receive the STK Pin Prompt which can be same as PartyA value.
	PhoneNumber uint64 `json:"PhoneNumber"`

	// CallbackURL is a valid secure URL that is used to receive notifications from M-Pesa API. It is the endpoint
	// to which the results will be sent by M-Pesa API.
	CallBackURL string `json:"CallBackURL"`

	// AccountReference is parameter that is defined by your system as an identifier of the transaction for
	// CustomerPayBillOnline transaction type. Along with the business name, this value is also displayed to the
	// customer in the STK Pin Prompt message and must be maximum of 12 characters.
	AccountReference string `json:"AccountReference"`

	// TransactionDesc is any additional information/comment that can be sent along with the request from your
	// system with a maximum of 13 Characters.
	TransactionDesc string `json:"TransactionDesc"`
}

STKPushRequest represents the data to be provided by the user for LipaNaMpesaOnlineRequestParameters

type STKQueryRequest added in v1.0.7

type STKQueryRequest struct {
	// BusinessShortCode is organizations shortcode (Paybill or Buy goods - A 5 to 7-digit account number) used to
	// identify an organization and receive the transaction.
	BusinessShortCode uint `json:"BusinessShortCode"`

	// CheckoutRequestID is a global unique identifier of the processed checkout transaction request.
	CheckoutRequestID string `json:"CheckoutRequestID"`

	// Password is a base64 encoded string used for encrypting the request sent which is a combination of
	// BusinessShortCode + Passkey + Timestamp
	Password string `json:"Password"`

	// Timestamp of the transaction in the format of YEAR+MONTH+DATE+HOUR+MINUTE+SECOND (YYYYMMDDHHmmss).
	// Each part should be at least two digits apart from the year which takes four digits.
	// Example 20060102150405
	Timestamp string `json:"Timestamp"`
}

type TransactionStatusRequest added in v1.0.8

type TransactionStatusRequest struct {
	// The CommandID for the request - TransactionStatusQueryCommandID
	CommandID CommandID `json:"CommandID"`

	// IdentifierType is the type of organization receiving the transaction
	IdentifierType IdentifierType `json:"IdentifierType"`

	// Initiator is the credential/username used to authenticate the transaction request.
	Initiator string `json:"Initiator"`

	// Occasion is an optional paramater that is a sequence of characters up to 100
	Occasion string `json:"Occasion"`

	// OriginatorConversationID is a global unique identifier for the transaction request returned by the API proxy
	// upon successful request submission. If you don’t have the M-PESA transaction ID you can use this to query.
	OriginatorConversationID string `json:"OriginatorConversationID,omitempty"`

	// PartyA is an Organization/MSISDN receiving the transaction. Shortcode (6-9 digits) MSISDN (12 Digits)
	PartyA uint `json:"PartyA"`

	// QueueTimeOutURL is the endpoint that will be used by API Proxy to send notification incase the request is timed
	// out while awaiting processing in the queue. Must be served via https.
	QueueTimeOutURL string `json:"QueueTimeOutURL"`

	// Remarks are comments that are sent along with the transaction. They are a sequence of characters up to 100
	Remarks string `json:"Remarks"`

	// ResultURL is the endpoint that will be used by M-PESA to send notification upon processing of the request.
	// Must be served via https.
	ResultURL string `json:"ResultURL"`

	// SecurityCredential is an encrypted password for the initiator to authenticate the transaction request
	SecurityCredential string `json:"SecurityCredential"`

	// TransactionID is a unique identifier to identify a transaction on Mpesa
	TransactionID string `json:"TransactionID"`
}

type TransactionType added in v1.0.8

type TransactionType string

TransactionType is used ti identify the type of the transaction being made.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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