@birrlink/sdk
v1.0.0
Published
Official TypeScript SDK for BirrLink payments
Readme
@birrlink/sdk
Official TypeScript SDK for BirrLink Payments.
This SDK simplifies BirrLink payment integration by:
- Handling authentication
- Normalizing Ethiopian phone numbers
- Enforcing minimum payment rules
- Auto-generating unique order IDs
- Providing webhook helpers for status updates
Installation
npm install @birrlink/sdkConfiguration
This SDK is configured using environment variables. Create a .env file in your project's root directory.
BIRRLINK_API_KEY=your-secret-api-key
BIRRLINK_CALLBACK_URL=https://yourdomain.com/webhook
BIRRLINK_RETURN_URL=https://yourdomain.com/thankyouWhy environment variables? Using
.envfiles is an industry-standard practice that keeps your secret API keys out of source code, making your application more secure.
Usage
Creating a Payment
First, import and instantiate the SDK. It will automatically load the configuration from your .env file.
import { BirrLinkSDK } from "@birrlink/sdk";
const birr = new BirrLinkSDK(); // Loads configuration from .env. You can also manually pass the API key here.
const paymentResponse = await birr.pay(10, "0912345678", {
title: "Food Order",
});
console.log(paymentResponse);
/*
{
success: true,
message: "Payment created successfully",
payment_url: "https://checkout.birrlink.et/...",
order_id: "..."
}
*/What happens internally?
- The phone number is normalized to the
251XXXXXXXXXformat and validated. - The payment amount is validated against the minimum.
- A unique
order_idis auto-generated. - The
callback_urlandreturn_urlare included from your.envconfiguration.
Overriding Configuration Per-Request
You can override callback_url and return_url for a specific payment by passing them in the options object.
await birr.pay(25, "0912345678", {
title: "VIP Order",
callback_url: "https://custom-domain.com/webhook",
return_url: "https://custom-domain.com/thankyou",
});Handling Webhooks
BirrLink sends payment status updates to your callback_url. The SDK provides helpers to parse and validate these incoming webhooks.
Example with Express.js
import { parseWebhook, isPaymentCompleted } from "@birrlink/sdk";
import express from "express";
const app = express();
app.use(express.json()); // Make sure to use a JSON body parser
app.post("/webhook", (req, res) => { // Your BIRRLINK_CALLBACK_URL endpoint
try {
// 1. Parse and validate the incoming payload
const payload = parseWebhook(req.body);
// 2. Check if the payment was successful
if (isPaymentCompleted(payload)) {
// 3. Update your database with the payment status
console.log("Payment successful:", payload.order_id);
// e.g., await db.orders.update({ where: { id: payload.order_id }, data: { status: 'PAID' } });
}
// 4. Respond to BirrLink to acknowledge receipt
res.sendStatus(200);
} catch (err: any) {
console.error("Webhook error:", err.message);
// Respond with an error if the payload is invalid
res.sendStatus(400);
}
});The parseWebhook function validates required fields, normalizes data, and ensures a consistent object shape for safe use in your application.
Manual Webhook Usage
You can import the webhook helpers directly to process data anywhere in your application logic.
import { parseWebhook, isPaymentCompleted } from "@birrlink/sdk";
const webhookPayload = {
status: "COMPLETED",
amount: 10,
payment_method: "Telebirr",
payment_id: "TX123",
order_id: "ORD-EXAMPLE-123",
phone_number: "0912345678",
};
const parsed = parseWebhook(webhookPayload);
console.log("Parsed webhook:", parsed);
console.log("Payment completed?", isPaymentCompleted(parsed));API Reference
new BirrLinkSDK(apiKey?: string)
Creates a new SDK instance.
apiKey(optionalstring): Overrides theBIRRLINK_API_KEYfrom your.envfile.
pay(amount, phone, options?)
Creates a new payment request and returns a Promise<PaymentResponse>.
amount(number): The payment amount in ETB (minimum is 3).phone(string): The customer's Ethiopian phone number.options(optionalobject): Additional payment metadata.
| Option | Type | Description |
| :------------- | :------- | :-------------------------------------------------------- |
| title | string | A title for the payment. Defaults to "Payment". |
| description | string | A description for the payment. |
| order_id | string | A unique ID for the order. Auto-generated if not provided.|
| callback_url | string | Overrides the BIRRLINK_CALLBACK_URL from .env. |
| return_url | string | Overrides the BIRRLINK_RETURN_URL from .env. |
parseWebhook(body: unknown)
Parses and validates an incoming webhook payload. Throws an error if validation fails.
body(unknown): The raw request body from the webhook POST request.- Returns: A validated
WebhookPayloadobject.
isPaymentCompleted(payload: WebhookPayload)
A utility function to check if the payment status is COMPLETED.
payload(WebhookPayload): The object returned fromparseWebhook.- Returns:
boolean.
Security Best Practices
- Never commit your
.envfile to version control. Add it to your.gitignorefile. - Always validate webhook payloads using
parseWebhookto prevent processing malicious or malformed requests. - Store payment results in your database only after a successful webhook confirmation to maintain a reliable source of truth.
Support
For support or inquiries, please contact us at: [email protected]
License
© BirrLink
