Files
sdk-go/qbirr.go
T
admin 86885c670e Docs + scrub: neutral example account number, CBE reference formats, webhooks, quota
- The example account number in the README and in the source docblock was a
  REAL account number. Replaced with an obviously fake one (1000123456789).
  The same scrub had already been applied to sdks/ in qbirr-saas; this repo
  had drifted from it.
- Document that CBE accepts the full receipt link, the "v2-" token and the bare
  token as the SAME payment. qbirr reduces them to one identity, so a receipt
  cannot be verified twice by presenting it differently. Case is ignored for
  that check.
- Document the webhook contract: `verification.created` fires for BOTH outcomes
  so always read data.verified; data.client_ref echoes the tag your own upload
  sent (null if you did not send one); a 4xx response is final and is NOT
  retried, while 5xx / timeouts are retried with exponential backoff.
- Document that only verified lookups count against the monthly quota.
- sdk-node: the committed dist/ comment blocks were updated to match src. The
  change is inside comments only — no executable code differs.
2026-10-06 01:04:59 +03:00

198 lines
6.0 KiB
Go

// Package qbirr is a thin Go client for the qbirr payment verification API.
//
// qb := qbirr.New("your_api_key")
// r, err := qb.Verify(context.Background(), qbirr.VerifyRequest{
// Provider: "cbe",
// Ref: "FT23001234ABC",
// Amount: 500,
// ReceiverName: "YOUR NAME",
// ReceiverAccount: "1000123456789",
// })
// if err != nil { return err }
// if r.Verified { fmt.Println("Paid by", r.Payer) }
package qbirr
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"time"
)
const (
Version = "1.0.0"
DefaultBaseURL = "https://verify.qbirr.com"
DefaultTimeout = 30 * time.Second
)
// Provider identifies which bank or wallet the reference belongs to.
type Provider = string
const (
ProviderCBE Provider = "cbe"
ProviderTelebirr Provider = "telebirr"
ProviderAbyssinia Provider = "abyssinia"
ProviderDashen Provider = "dashen"
ProviderMpesa Provider = "mpesa"
ProviderAwash Provider = "awash"
ProviderEbirr Provider = "ebirr"
ProviderZamZam Provider = "zamzam"
)
// VerifyRequest is the payload for /api/v1/verify.
type VerifyRequest struct {
Provider Provider `json:"provider"`
Ref string `json:"ref"`
Amount float64 `json:"amount"`
ReceiverName string `json:"receiver_name"`
ReceiverAccount string `json:"receiver_account,omitempty"` // required for CBE & Abyssinia
}
// VerifyResult is the API response. Verification failures arrive here (Verified=false + Error set),
// NOT as Go errors. Errors are reserved for network/HTTP problems.
type VerifyResult struct {
Verified bool `json:"verified"`
Payer string `json:"payer"`
Amount float64 `json:"amount"`
Error string `json:"error"`
// PaidAmount is the amount the receipt ACTUALLY shows, in ETB. 0 when
// unreadable. On a short payment compare it to Amount to see what arrived.
PaidAmount float64 `json:"paid_amount"`
// Retryable TRUE means "we could not reach the bank", so Verified=false is NOT
// a verdict on the payment — it is "not checked yet". Retry, or fall back to
// manual review. NEVER reject an order on this. Check it BEFORE acting on
// Verified=false.
Retryable bool `json:"retryable"`
// Code is a stable machine-readable reason; branch on this instead of parsing
// Error. Empty on success. Values: RECEIPT_NOT_FOUND, AMOUNT_MISMATCH,
// RECEIVER_MISMATCH, RECEIPT_EXPIRED, RECEIPT_UNREADABLE, REFERENCE_INVALID,
// RECEIVER_ACCOUNT_REQUIRED, UNSUPPORTED_INPUT, VERIFICATION_FAILED,
// DUPLICATE_REFERENCE, UPSTREAM_UNAVAILABLE (the only retryable one).
Code string `json:"code"`
// ReceiverSource is which receiver identity was actually checked: "settings"
// (your saved account — strongest), "request" (the receiver_name/account you
// sent), or "none" (NOTHING was checked: Verified=true with "none" means the
// reference exists and the amount matches, but says nothing about who
// received the money).
ReceiverSource string `json:"receiver_source"`
// Sandbox is true only on TEST-... responses.
Sandbox bool `json:"sandbox"`
}
// IsOutage reports whether this result is "we could not check" rather than a
// verdict on the payment. When true, retry or review manually — do not treat the
// payment as invalid.
func (r VerifyResult) IsOutage() bool {
return !r.Verified && r.Retryable
}
// UsageStatus is the response from /api/v1/usage.
type UsageStatus struct {
Used int `json:"used"`
Limit int `json:"limit"`
Remaining int `json:"remaining"`
Plan string `json:"plan"`
PeriodStart string `json:"period_start"`
PeriodEnd string `json:"period_end"`
}
// APIError wraps a non-2xx HTTP response.
type APIError struct {
Status int
Message string
}
func (e *APIError) Error() string { return fmt.Sprintf("qbirr: HTTP %d: %s", e.Status, e.Message) }
// Client talks to the qbirr API.
type Client struct {
APIKey string
BaseURL string
HTTPClient *http.Client
}
// New returns a client with sensible defaults.
func New(apiKey string) *Client {
return &Client{
APIKey: apiKey,
BaseURL: DefaultBaseURL,
HTTPClient: &http.Client{Timeout: DefaultTimeout},
}
}
// Verify performs a verification. Returns (result, nil) for both verified=true and verified=false
// (real verification failures). Returns (nil, error) only for transport/HTTP issues.
func (c *Client) Verify(ctx context.Context, req VerifyRequest) (*VerifyResult, error) {
if c.APIKey == "" {
return nil, errors.New("qbirr: APIKey is empty")
}
var out VerifyResult
if err := c.do(ctx, "POST", "/api/v1/verify", req, &out); err != nil {
return nil, err
}
return &out, nil
}
// Usage returns the current calendar-month quota status.
func (c *Client) Usage(ctx context.Context) (*UsageStatus, error) {
var out UsageStatus
if err := c.do(ctx, "GET", "/api/v1/usage", nil, &out); err != nil {
return nil, err
}
return &out, nil
}
func (c *Client) do(ctx context.Context, method, path string, body any, out any) error {
var rdr io.Reader
if body != nil {
buf, err := json.Marshal(body)
if err != nil {
return fmt.Errorf("qbirr: marshal: %w", err)
}
rdr = bytes.NewReader(buf)
}
req, err := http.NewRequestWithContext(ctx, method, c.BaseURL+path, rdr)
if err != nil {
return err
}
req.Header.Set("X-API-Key", c.APIKey)
req.Header.Set("Accept", "application/json")
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
req.Header.Set("User-Agent", "qbirr-go/"+Version)
resp, err := c.HTTPClient.Do(req)
if err != nil {
return fmt.Errorf("qbirr: network: %w", err)
}
defer resp.Body.Close()
raw, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("qbirr: read body: %w", err)
}
if resp.StatusCode >= 400 {
// Try to extract { error: "..." }
var apiErr struct{ Error string `json:"error"` }
_ = json.Unmarshal(raw, &apiErr)
msg := apiErr.Error
if msg == "" {
msg = string(raw)
}
return &APIError{Status: resp.StatusCode, Message: msg}
}
if err := json.Unmarshal(raw, out); err != nil {
return fmt.Errorf("qbirr: decode (HTTP %d): %w", resp.StatusCode, err)
}
return nil
}