I'm learning Go by building a real product: ElimuLocal, a free study-resource platform for Kenyan university students. Once it was solid, I wanted a premium tier, and in Kenya that means one thing: M-Pesa. This article walks through how I integrated Safaricom's Daraja STK Push in Go, what broke, and what I'd do differently.
1. The flow at a glance
STK Push means your server asks Safaricom to pop up a PIN prompt on the customer's phone. Four parties are involved:
Customer phone Your Go server Daraja / Safaricom
| | |
| taps "Pay" | |
|-------------------->| 1. OAuth token |
| |------------------------->|
| | 2. STK Push request |
| |------------------------->|
| PIN prompt |<-- 3. "accepted" + ID ---|
|<---------------------------------------------- |
| enters PIN | |
|--------------------------------------------> |
| | 4. Callback (result) |
| |<-------------------------|
| | 5. Activate premium |
The key insight: step 3 only means "request accepted", not "paid." The real answer arrives later, asynchronously, at your callback URL. Everything in this article follows from that.
2. Sandbox setup and credentials
Create an account at the Daraja developer portal, make an app, and enable the Lipa Na M-Pesa Sandbox product. You get a Consumer Key and Secret. The sandbox shortcode is 174379 and Safaricom publishes a public sandbox passkey.
I keep everything in environment variables, never in code:
MPESA_CONSUMER_KEY=...
MPESA_CONSUMER_SECRET=...
MPESA_SHORTCODE=174379
MPESA_PASSKEY=<sandbox passkey from the portal>
MPESA_CALLBACK_URL=https://<your-public-host>/mpesa/callback
MPESA_ENV=sandbox
| Setting | Sandbox | Production |
|---|---|---|
| Base URL | https://sandbox.safaricom.co.ke |
https://api.safaricom.co.ke |
| Shortcode | 174379 |
Your own Paybill/Till |
| Passkey | Public test key | Issued to you after Go-Live |
| Callback URL | Must be public HTTPS (ngrok is fine) | Your real domain |
A small struct holds the config:
type DarajaClient struct {
ConsumerKey string
ConsumerSecret string
ShortCode string
Passkey string
CallbackURL string
BaseURL string
}
3. Getting an access token
Daraja uses OAuth. You send your key and secret as HTTP Basic auth and get a short-lived bearer token:
func (d *DarajaClient) getAccessToken() (string, error) {
req, err := http.NewRequest("GET",
d.BaseURL+"/oauth/v1/generate?grant_type=client_credentials", nil)
if err != nil {
return "", err
}
creds := base64.StdEncoding.EncodeToString(
[]byte(d.ConsumerKey + ":" + d.ConsumerSecret))
req.Header.Set("Authorization", "Basic "+creds)
client := &http.Client{Timeout: 15 * time.Second}
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
var out struct {
AccessToken string `json:"access_token"`
}
if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
return "", err
}
return out.AccessToken, nil
}
Note the explicit http.Client timeout. Go's default client has none, so a slow Safaricom response would hang your handler forever. Tokens last about an hour; I fetch one per payment for simplicity and would cache it in production.
4. Initiating the STK Push
Two things trip people up: the timestamp and the password.
- Timestamp format is
YYYYMMDDHHmmss. In Go that's the reference layout20060102150405. - Password is
base64(shortcode + passkey + timestamp).
func (d *DarajaClient) initiateSTKPush(phone string, amount int, ref string) (*STKResponse, error) {
token, err := d.getAccessToken()
if err != nil {
return nil, err
}
timestamp := time.Now().Format("20060102150405")
password := base64.StdEncoding.EncodeToString(
[]byte(d.ShortCode + d.Passkey + timestamp))
payload := map[string]interface{}{
"BusinessShortCode": d.ShortCode,
"Password": password,
"Timestamp": timestamp,
"TransactionType": "CustomerPayBillOnline",
"Amount": amount,
"PartyA": phone, // who pays
"PartyB": d.ShortCode, // who receives
"PhoneNumber": phone, // who gets the prompt
"CallBackURL": d.CallbackURL,
"AccountReference": ref,
"TransactionDesc": "ElimuLocal Premium",
}
// marshal, POST to /mpesa/stkpush/v1/processrequest with
// "Authorization: Bearer <token>", decode STKResponse
// (MerchantRequestID, CheckoutRequestID, ResponseCode, ...)
}
Phone numbers must be 2547XXXXXXXX — no +, no leading 0. Students type 0712… or +254712…, so I normalise:
func normalisePhone(p string) string {
p = strings.TrimSpace(p)
p = strings.TrimPrefix(p, "+")
if strings.HasPrefix(p, "0") {
p = "254" + p[1:]
}
return p
}
Save before you send. My handler inserts a pending row in payments first, then calls Daraja, then stores the returned CheckoutRequestID. If the callback is faster than your database write, you still have a row to match it to.
CREATE TABLE payments (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
phone_number TEXT,
amount INTEGER,
account_reference TEXT,
checkout_request_id TEXT,
merchant_request_id TEXT,
mpesa_receipt_number TEXT,
status TEXT DEFAULT 'pending',
result_code INTEGER,
result_desc TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
5. The callback endpoint
Safaricom POSTs the outcome to your CallBackURL. The payload is nested JSON:
type STKCallback struct {
Body struct {
StkCallback struct {
MerchantRequestID string `json:"MerchantRequestID"`
CheckoutRequestID string `json:"CheckoutRequestID"`
ResultCode int `json:"ResultCode"`
ResultDesc string `json:"ResultDesc"`
CallbackMetadata struct {
Item []struct {
Name string `json:"Name"`
Value interface{} `json:"Value"`
} `json:"Item"`
} `json:"CallbackMetadata"`
} `json:"stkCallback"`
} `json:"Body"`
}
Value is interface{} because it's a number for amounts and a string for receipts. Only successful payments include CallbackMetadata, which holds MpesaReceiptNumber.
Result codes you'll meet:
| ResultCode | Meaning |
|---|---|
| 0 | Success, money moved |
| 1 | Insufficient balance |
| 1032 | Customer cancelled the prompt |
| 1037 | Prompt timed out (no response) |
| 2001 | Wrong PIN |
Always answer 200 with {"ResultCode":0,"ResultDesc":"Success"}, even for failed payments. That acknowledgement means "I received your message," not "the payment succeeded." Anything else may cause retries.
Testing locally needs a public HTTPS URL, so I used ngrok (./ngrok http 8080) and pasted its URL into MPESA_CALLBACK_URL. In the sandbox I mostly saw 1037: expected, since the simulator doesn't always wait for a PIN. It proved the plumbing worked.
6. Edge cases
Designed but not yet fully implemented in ElimuLocal.
Duplicate callbacks. Networks retry. Make the status transition conditional so a second delivery changes nothing:
res, err := db.Exec(`
UPDATE payments
SET status = ?, result_code = ?, result_desc = ?,
mpesa_receipt_number = ?, updated_at = CURRENT_TIMESTAMP
WHERE checkout_request_id = ? AND status = 'pending'`,
status, code, desc, receipt, checkoutID)
if err != nil { /* log */ }
n, _ := res.RowsAffected()
if n == 0 {
// already processed: acknowledge, do nothing else
}
Only when n == 1 do you activate premium. That's what makes the whole thing idempotent.
Payments that never confirm. Sometimes no callback arrives. Daraja offers an STK Query endpoint (/mpesa/stkpushquery/v1/query) taking the CheckoutRequestID. A small background job can query any row still pending after a few minutes and reconcile it.
Matching a payment to a user. The phone number is not a safe key, since a parent might pay for a student. CheckoutRequestID is the join key: you stored it alongside user_id before the push, so the callback looks up the row and gets the user from there.
Double clicks. A nervous student tapping twice sent me two prompts. Disable the button on submit, and reject a new push if the user already has a recent pending payment.
Don't blindly trust the body. For a stronger setup, verify the amount matches what you expected, and confirm via STK Query before granting access.
7. Activating premium after confirmation
Illustrative;
premium_untilis not yet in the schema.
ALTER TABLE users ADD COLUMN premium_until TEXT;
func activatePremium(userID int, days int) error {
var current sql.NullString
_ = db.QueryRow(`SELECT premium_until FROM users WHERE id = ?`, userID).Scan(¤t)
start := time.Now()
if current.Valid {
if t, err := time.Parse(time.RFC3339, current.String); err == nil && t.After(start) {
start = t // extend from existing expiry, don't lose paid days
}
}
until := start.AddDate(0, 0, days).Format(time.RFC3339)
_, err := db.Exec(`UPDATE users SET premium_until = ? WHERE id = ?`, until, userID)
return err
}
Extending from max(now, current expiry) matters: a student who renews early shouldn't lose days. Gating a feature is then just premium_until > now.
8. Gotchas and lessons learned
- "Request accepted" is not "paid". Only the callback (or STK Query) tells you the truth.
-
1037in the sandbox is normal, not a bug. -
The callback URL must be public HTTPS.
localhostwill never work; use ngrok. -
Phone format is strict:
2547XXXXXXXX. - Save the pending row before calling Daraja.
-
Make state transitions conditional (
AND status = 'pending') so duplicates are harmless. - Set HTTP client timeouts. Go's default has none.
- Secrets live in environment variables, never in Git.
- Always return 200 to the callback, even for failures.
- Sandbox is not production. Real money needs a registered business, your own shortcode, and Go-Live approval. ## Closing
Tutorials give you syntax; a real problem gives you understanding. Asynchronous callbacks, idempotency, and reconciliation are things I'd never have met in a to-do app, and I met all of them because a real student might one day pay for something.
ElimuLocal is live at elimulocal.onrender.com and the code is at github.com/Rkelly-dot/elimulocal.
Top comments (0)