API reference
BHD Ads API reference
Every route, field and rule in this reference comes from the running code. Code samples are in English.
Overview
BHD Ads is an HTTP API with JSON in and JSON out. One base URL serves every call:
https://ads.bhd.om- All calls use HTTPS. Bodies are UTF-8 JSON with
Content-Type: application/json. - Money is an integer in baisa: OMR 1.000 is
1000. A field that ends inMbis in milli-baisa (1/1000 of a baisa), so a price for each view stays a whole number. - Times are ISO 8601 in UTC, for example
2026-10-09T08:00:00.000Z. Days in reports are UTC dates. - Every response has an
x-request-idheader. Errors repeat it asreference. Give it to BHD when you ask for help. - Words in this reference: a property is one website or app, an ad unit is one place for an ad on a property, a campaign holds one or more ads, a view and a tap are counted events.
Public data
These three calls need no key. The public site uses them.
| Call | Returns |
|---|---|
GET /v1/public/pricing | { ready: false } until BHD publishes prices. Then ready, version, packages (id, name, blurb, days, views, price, formats), daily (available, minBaisa, maxDays) and tax (vatBp, label). |
GET /v1/public/formats | The ad formats on sale, each with id, name, kind and requirements (picture size, text limits). |
GET /v1/public/inventory | properties: the approved live properties of BHD Group by name; partnerProperties: how many approved partner properties exist (not named); screens: how many active screens exist. |
Authentication and keys
Send a key in the Authorization header as a bearer token. The ad request also accepts the key in the key query parameter, because a page cannot always set a header.
Authorization: Bearer sk_live_...| Key | Starts with | Use |
|---|---|---|
| Publishable | pk_test_ / pk_live_ | Ad requests (GET /v1/ad). Safe in a page or an app. Never use a secret key for ad requests: the server accepts it there too, and anyone who reads your page could then call your account API. |
| Secret | sk_test_ / sk_live_ | The account API. Keep it on your server. It acts as a member of its organization. |
- An organization admin creates and revokes keys in the console. The full key is shown one time; BHD Ads keeps only a hash of it.
- A publishable key sent to the account API gets
403 secret_key_required. An unknown or revoked key gets401 bad_key. - A secret key acts as an admin of its own organization: it can manage campaigns, properties, ad units, payouts and webhooks. API keys themselves are made and revoked only in the console.
/v1/adrefuses a secret key with403 publishable_key_required: never put a secret key in a page. - A key of one organization never reaches another. An id of another organization answers
404 not_found, so the API does not confirm that it exists.
Test mode
Every object is in test mode or live mode: properties, keys, campaigns, payments and webhook endpoints. A test key works only with test ad units, and a live key only with live ones (403 key_and_unit_modes_differ).
- A test property is approved at once.
- A test key always gets an ad. If a live test campaign of any advertiser matches, you get it. If not, you get a built-in test ad from BHD Ads. Both carry
"test": true; show a visible TEST tag. - Requests show in your earnings report at once. Views and taps of a test campaign also show there. Views and taps of the built-in test ad are checked (a second beacon is a duplicate) but are not written to any report. Test views are never charged and never earn.
- A test campaign is paid with a test payment that moves no money and gives an invoice numbered
TEST-.... A test campaign never shows on live properties. - Test properties skip the website domain check.
Web SDK
The web SDK is one script with no dependencies. It sets no cookie, uses no browser storage and creates one global, window.BHDAds. It reads the API address from its own script URL.
With HTML only
<script async src="https://ads.bhd.om/v1/sdk.js"></script>
<ins class="bhd-ad" data-key="pk_test_YOUR_KEY" data-unit="unit_YOUR_UNIT"
data-lang="ar" data-consent="non_personalized"></ins>The script fills every ins.bhd-ad element that has data-key and data-unit. data-lang and data-consent are optional. For elements you add later, call BHDAds.scan().
With JavaScript
<script src="https://ads.bhd.om/v1/sdk.js"></script>
<div id="ad-footer"></div>
<script>
BHDAds.load({
key: 'pk_test_YOUR_KEY',
unit: 'unit_YOUR_UNIT',
target: '#ad-footer', // a selector or an element
lang: 'en', // 'en' or 'ar'; default: <html lang>
consent: 'non_personalized', // or 'personalized'
onEmpty: function (reason) { // no ad, or any error
document.getElementById('ad-footer').hidden = true;
}
}).then(function (shown) { /* true when an ad is on the page */ });
</script>| Option | Meaning |
|---|---|
key | Your publishable key. Required. |
unit | The ad unit id. Required. |
target | A CSS selector or an element. The ad goes inside it. |
lang | en or ar. Default: the lang of the page. |
consent | personalized or non_personalized. See Consent. |
onEmpty(reason) | Called when no ad shows: no_ad (no matching ad), property_pending and other property_* values, error (a wrong key or unit, a network error, or any other error), no_target, not_supported. |
What the SDK does
- It requests
GET /v1/adonce for each element, withos=web. It never requests twice for the same element. - It draws the ad in a closed Shadow DOM, so the CSS of your page cannot change the ad and the ad cannot change your page. The ad is labelled "Ad · sponsor" ("إعلان" in Arabic), is right to left when the ad is in Arabic, and shows a TEST tag in test mode.
- It fetches
impressionUrlone time, when at least half of the ad is on the screen for one second without a break. Never on load. - A tap opens
clickUrlin a new tab withrel="noopener sponsored". - It never throws. With no ad or on any error it draws nothing and calls
onEmpty.
The host element gets data-bhd-ad="loading", then "filled" or "empty", so you can style the space. The ad is at most 360 px wide. If your site has a Content Security Policy, allow these:
script-src https://ads.bhd.om;
connect-src https://ads.bhd.om;
img-src https:;Ad request
Asks for one ad for one ad unit. CORS is open, so a page can call it. Use it from a browser or from the app on the device, not from your server: counting uses the address of the device.
| Parameter | Meaning |
|---|---|
unit | Required. The ad unit id, for example unit_ab12cd34. A paused or archived unit answers 404 unknown_unit. |
key | Your publishable key, when you cannot send the Authorization header. |
os | web, ios or android. Default web. |
lang | en or ar (the first 2 letters are used). An ad in this language is chosen first. |
consent | personalized or non_personalized. Any other value is stored as unknown. |
country | Optional, 2 letters, for example OM. Default: the country of the request as seen by Cloudflare. |
city | Optional, up to 60 characters. Used only by campaigns that target cities. |
curl "https://ads.bhd.om/v1/ad?unit=unit_YOUR_UNIT&lang=en&os=web&consent=non_personalized" \
-H "Authorization: Bearer pk_test_YOUR_KEY"Response: an ad
{
"ad": {
"id": "cmp_8Hq2...",
"creativeId": "cr_Wb71...",
"kind": "direct",
"title": "Fresh bread every morning",
"body": "Order before 8 and collect at 9.",
"cta": "Order now",
"sponsor": "Amal Bakery",
"lang": "en",
"imageUrl": "https://ads.bhd.om/m/med_x81....png",
"targetUrl": "https://bakery.example.om/",
"test": false,
"impressionUrl": "https://ads.bhd.om/v1/i/eyJu...",
"clickUrl": "https://ads.bhd.om/v1/c/eyJu..."
},
"test": false
}| Field | Meaning |
|---|---|
title, body, cta | The headline, the text and the button label. body and cta can be empty strings. |
sponsor | The advertiser name. Show it next to the word "Ad". |
lang | en or ar. Draw the ad right to left when it is ar. |
imageUrl | An https picture, or an empty string. The card format uses a 1.91:1 picture. |
impressionUrl | Fetch it once when the ad was seen. See Counting rules. It expires 1 hour after the request. |
clickUrl | Open it on a tap. It counts the tap and redirects to the advertiser. It expires 24 hours after the request. |
targetUrl | The advertiser link, for display only. Never open it directly: the tap would not count. |
kind | direct for a paid or BHD ad, house for a BHD house ad. |
test | true in test mode. Show a TEST tag. |
Response: no ad
{ "ad": null, "test": false }
{ "ad": null, "reason": "property_pending" }ad is null when no campaign matches. A live property that BHD has not approved answers reason with its status: property_pending, property_suspended or property_rejected. Show nothing, or your own content.
Errors
| Status | error | Meaning |
|---|---|---|
| 401 | bad_key | No key, an unknown key or a revoked key. |
| 404 | unknown_unit | The unit does not exist, is not active, or belongs to another organization. |
| 403 | key_and_unit_modes_differ | A test key with a live unit, or the other way round. |
| 403 | domain_not_allowed | A live website unit called from a page that is not on the registered domain or its subdomains. The check reads the Origin or Referer header. |
| 429 | too_many_requests | Over the rate limit. |
Error answers of /v1/ad do not carry CORS headers, so a browser page cannot read their body. Test a key and a unit with curl first.
Counting rules
- A view counts when at least half of the ad is on the screen for one continuous second. Then fetch
impressionUrlone time. Never fetch it when the ad loads. - One ad shown is one view at most. Each beacon is single use: a second fetch of the same
impressionUrlanswers204but counts nothing. Ask for a new ad to show a new ad. - A tap goes through
clickUrl. It answers302to the advertiser link. The first tap on an ad counts; later taps still redirect but do not count. - An expired or changed beacon answers
404 not_found. A view beacon lives 1 hour, a tap beacon 24 hours. - Requests from known bots and crawlers (by user agent) are not counted.
- From one address, more than 6 views of one campaign in an hour are not counted, and BHD staff see a flag. A campaign can also set a daily limit of views for each address.
- A paid view is charged to the campaign at the moment it counts, and never above the budget. When a campaign has used 80% of its budget, its organization gets one email. When the budget is spent, the campaign completes and stops showing.
- When a paid campaign ends with budget left, BHD Ads opens a refund request for the unused part (with its share of VAT) by itself. BHD finance approves it before money moves, and it goes back to the card.
| Beacon | Answer |
|---|---|
GET /v1/i/{token} | 204 (counted, repeated or ignored), 404 (bad or expired). CORS is open. |
GET /v1/c/{token} | 302 with Location = the advertiser link, 404 (bad or expired). |
Consent
Pass consent=personalized or consent=non_personalized when your app or site knows the choice of the person. BHD Ads stores the value with the view. Leave it out when you do not know.
- BHD Ads does not profile people. Ads are chosen from the request only: the property, the ad unit, the language, the country, the city if you send it, and the device system.
- BHD Ads stores no raw address with a view or a tap: only a salted hash that changes every day, to count fairly and to stop abuse.
- Never send personal data: no names, emails, phone numbers, user ids or advertising ids, in any parameter.
Mobile apps
- Call
GET /v1/adfrom the app on the device, with your publishable key,os=iosoros=android, and the language of the app. - Draw the ad with your own native views. Show the word "Ad" (or "إعلان") and
sponsor, the title, the text, the picture and the button. Show a TEST tag whentestis true. - Fetch
impressionUrlonce, when at least half of the ad is on the screen for one second. - On a tap, open
clickUrlin the browser.
Swift (iOS)
import UIKit
struct BHDAd: Decodable {
let title: String, body: String, cta: String, sponsor: String, lang: String
let imageUrl: String, impressionUrl: URL, clickUrl: URL, test: Bool
}
private struct BHDAdResponse: Decodable { let ad: BHDAd? }
/// Asks for one ad. Returns nil when there is no ad or on any error.
func loadBHDAd(unit: String, key: String, lang: String) async -> BHDAd? {
var c = URLComponents(string: "https://ads.bhd.om/v1/ad")!
c.queryItems = [URLQueryItem(name: "unit", value: unit), URLQueryItem(name: "lang", value: lang),
URLQueryItem(name: "os", value: "ios"), URLQueryItem(name: "consent", value: "non_personalized")]
var req = URLRequest(url: c.url!, timeoutInterval: 5)
req.setValue("Bearer \(key)", forHTTPHeaderField: "Authorization")
guard let (data, res) = try? await URLSession.shared.data(for: req),
(res as? HTTPURLResponse)?.statusCode == 200 else { return nil }
return (try? JSONDecoder().decode(BHDAdResponse.self, from: data))?.ad
}
/// Fetches impressionUrl once, after half of the ad view was on screen for one second.
final class BHDViewTracker {
private var timer: Timer?
private var since: Date?
private var fired = false
func start(_ view: UIView, impressionUrl: URL) {
timer = Timer.scheduledTimer(withTimeInterval: 0.2, repeats: true) { [weak self, weak view] t in
guard let self = self, let view = view, !self.fired else { t.invalidate(); return }
var half = false
if let w = view.window, UIApplication.shared.applicationState == .active {
let r = view.convert(view.bounds, to: w).intersection(w.bounds)
half = !r.isNull && r.width * r.height >= 0.5 * view.bounds.width * view.bounds.height
}
if !half { self.since = nil; return }
if self.since == nil { self.since = Date() }
if Date().timeIntervalSince(self.since!) >= 1 {
self.fired = true
t.invalidate()
URLSession.shared.dataTask(with: impressionUrl).resume()
}
}
}
func stop() { timer?.invalidate() }
}
// On a tap: open clickUrl, never targetUrl.
// UIApplication.shared.open(ad.clickUrl)Kotlin (Android)
import android.content.Intent
import android.graphics.Rect
import android.net.Uri
import android.os.Handler
import android.os.Looper
import android.view.View
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.json.JSONObject
import java.net.HttpURLConnection
import java.net.URL
import java.net.URLEncoder
data class BhdAd(val title: String, val body: String, val cta: String, val sponsor: String, val lang: String,
val imageUrl: String, val impressionUrl: String, val clickUrl: String, val test: Boolean)
/** Asks for one ad. Returns null when there is no ad or on any error. */
suspend fun loadBhdAd(unit: String, key: String, lang: String): BhdAd? = withContext(Dispatchers.IO) {
try {
val url = URL("https://ads.bhd.om/v1/ad?unit=" + URLEncoder.encode(unit, "UTF-8") +
"&lang=" + lang + "&os=android&consent=non_personalized")
val c = url.openConnection() as HttpURLConnection
c.setRequestProperty("Authorization", "Bearer $key")
c.connectTimeout = 5000; c.readTimeout = 5000
if (c.responseCode != 200) return@withContext null
val ad = JSONObject(c.inputStream.bufferedReader().readText()).optJSONObject("ad") ?: return@withContext null
BhdAd(ad.optString("title"), ad.optString("body"), ad.optString("cta"), ad.optString("sponsor"),
ad.optString("lang"), ad.optString("imageUrl"), ad.getString("impressionUrl"),
ad.getString("clickUrl"), ad.optBoolean("test"))
} catch (e: Exception) { null }
}
/** Fetches impressionUrl once, after half of the view was on screen for one second. */
class BhdViewTracker(private val view: View, private val impressionUrl: String) {
private val main = Handler(Looper.getMainLooper())
private var since = 0L
private var fired = false
private val tick = object : Runnable {
override fun run() {
if (fired) return
val r = Rect()
val shown = view.isShown && view.getGlobalVisibleRect(r)
val half = shown && r.width().toLong() * r.height() >= view.width.toLong() * view.height / 2
val now = System.currentTimeMillis()
if (!half) since = 0L else if (since == 0L) since = now
if (half && now - since >= 1000) {
fired = true
Thread { try { (URL(impressionUrl).openConnection() as HttpURLConnection).apply { connectTimeout = 5000; responseCode; disconnect() } } catch (_: Exception) {} }.start()
return
}
main.postDelayed(this, 200)
}
}
fun start() = main.post(tick)
fun stop() = main.removeCallbacks(tick)
}
// On a tap: open clickUrl, never targetUrl.
// context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(ad.clickUrl)))Server to server for BHD apps
BHD Group apps (Jamiya, Splitty) use the first API of BHD Ads. It returns the Google units of the app, the gaps between full-screen ads, and a BHD ad. It is kept as it is for those apps. New integrations use GET /v1/ad.
| Parameter | Meaning |
|---|---|
app | Required. The property id of the app, for example jamiya. |
os | Required. ios, android or web. |
slot | card (default), fullscreen or rewarded. rewarded returns no BHD ad, only the Google unit. |
lang, country, consent | As in the ad request. |
The key is the app key of that property, or a secret key of the organization that owns it, in the same mode. Errors: 401 unknown_app, 401 bad_key, 400 invalid_query.
curl "https://ads.bhd.om/v1/decide?app=jamiya&os=ios&slot=card&lang=ar" \
-H "Authorization: Bearer APP_KEY"{
"units": { "banner": "ca-app-pub-.../...", "interstitial": "ca-app-pub-.../...", "rewarded": "ca-app-pub-.../..." },
"gaps": { "firstAfterSeconds": 60, "minGapSeconds": 180 },
"personalized": true,
"direct": null,
"fallback": { "id": "cmp_house1", "kind": "house", "title": "...", "impressionUrl": "...", "clickUrl": "...", ... }
}direct is a paid or BHD ad and is shown first. fallback is a house ad: show it when Google has no ad, or first when the app has no Google units. Both use the same impressionUrl and clickUrl rules.
Reports Google ad events, so the BHD report shows all ads in the app. Up to 50 events in one call. type: impression, click, reward or nofill; slot: card, fullscreen or rewarded; os: ios, android or web; network: admob or adsense. Events with other values are skipped. Only the app key works here. Answer: 204.
curl -X POST "https://ads.bhd.om/v1/events" \
-H "Authorization: Bearer APP_KEY" -H "Content-Type: application/json" \
-d '{"events":[{"type":"impression","slot":"card","os":"ios","network":"admob"}]}'Account API
The account API is what the console uses. With a secret key you call it from your server. Each route below names who can call it. Lists take limit (1 to 100, default 50) and offset.
Organizations
With a secret key: { signedIn: true, key: { kind, env }, organizations: [ ... ] }. Use it to find your organization id.
The organization: id, kind, name, legalName, crNumber, vatNumber, country, city, address, phone, website, billingEmail, isAdvertiser, isPublisher, verification, status, bank (the IBAN is masked), and agencies.
curl "https://ads.bhd.om/v1/orgs/org_YOUR_ORG" -H "Authorization: Bearer sk_live_YOUR_KEY"Changing the organization (PATCH /v1/orgs/{orgId}), members, agencies and keys is for an organization admin in the console.
What a campaign can target: properties (BHD properties by id and name) and partnerCount. Put a property id in targeting.properties. env=test lists test properties.
Pictures
Uploads one picture as base64 in JSON: data (required, PNG, JPEG or WebP, at most 5 MB) and formatId (optional). With formatId, problems lists in words why the picture does not fit that format; an empty list means it fits. Use the returned id as mediaId in an ad.
curl -X POST "https://ads.bhd.om/v1/orgs/org_YOUR_ORG/media" \
-H "Authorization: Bearer sk_test_YOUR_KEY" -H "Content-Type: application/json" \
-d "{\"formatId\":\"card\",\"data\":\"$(base64 < picture.png | tr -d '\n')\"}"{ "id": "med_Xw...", "mime": "image/png", "bytes": 182311, "width": 1200, "height": 628,
"url": "https://ads.bhd.om/m/med_Xw....png", "problems": [] }Campaigns
Lists campaigns, newest first. Filters: status, q (part of the name), limit, offset.
curl "https://ads.bhd.om/v1/orgs/org_YOUR_ORG/campaigns?status=live&limit=20" \
-H "Authorization: Bearer sk_test_YOUR_KEY"Creates a draft campaign. The organization must be an advertiser (409 not_an_advertiser).
| Field | Meaning |
|---|---|
name | Required, up to 80 characters. |
env | test or live (default live). |
objective | visits (default), awareness, leads, sales, app_installs, engagement. |
startAt, endAt | Optional ISO times. |
frequencyCap | Optional, 1 to 100: the most views a day for one address. |
creatives[] | Up to 10 ads: lang (en/ar), formatId (default card), sponsor (default: the organization name), headline (up to 60), body (up to 140), cta (up to 20), destinationUrl (https, required), mediaId. |
targeting | All optional lists: langs, os, countries (2 letters), cities, properties, slots (card, fullscreen), dayparts ([{ days: [0..6], from: 0..23, to: 1..24 }], Muscat time). An empty list means all. |
curl -X POST "https://ads.bhd.om/v1/orgs/org_YOUR_ORG/campaigns" \
-H "Authorization: Bearer sk_test_YOUR_KEY" -H "Content-Type: application/json" \
-d '{
"name": "Morning bread",
"env": "test",
"objective": "visits",
"creatives": [{
"lang": "en", "formatId": "card", "sponsor": "Amal Bakery",
"headline": "Fresh bread every morning", "body": "Order before 8 and collect at 9.",
"cta": "Order now", "destinationUrl": "https://bakery.example.om/", "mediaId": "med_Xw..."
}],
"targeting": { "langs": ["en"], "os": ["ios", "android"], "countries": ["OM"] }
}'The campaign with status, budget (totalMb, dailyMb, viewsTarget, viewPriceMb, spentMb, remainingMb), stats (views, clicks, spendMb, ctr), targeting, creatives (with review and reviewReasons), quote and days (one row a day).
Changes a draft: the same fields as create. creatives, when sent, replaces all ads. After the draft stage it answers 409 only_drafts_can_change.
A price preview. Nothing is saved or charged. Body: { "pricing": "package", "packageId": "..." } or { "pricing": "daily", "dailyBaisa": 3000, "days": 5 }, and an optional promoCode. Until BHD publishes prices it answers 409 pricing_not_set.
curl -X POST "https://ads.bhd.om/v1/campaigns/cmp_YOUR_CAMPAIGN/quote" \
-H "Authorization: Bearer sk_test_YOUR_KEY" -H "Content-Type: application/json" \
-d '{"pricing":"daily","dailyBaisa":3000,"days":5}'{
"lines": [ { "kind": "daily", "ruleId": "base", "cpm": 1500, "dailyBaisa": 3000, "days": 5, "views": 10000, "amount": 15000 },
{ "kind": "tax", "label": "VAT 5%", "bp": 500, "amount": 750 } ],
"subtotal": 15000, "discount": 0, "tax": 750, "total": 15750,
"views": 10000, "dailyViews": 2000, "priceVersion": 3,
"network": { "adRequestsPerDay": 4200, "estimatedDays": 3, "unspentIsReturned": true }
}network is the real traffic: adRequestsPerDay is the average number of ad requests a day over the last 7 days on the properties the campaign targets (all approved properties in its mode when it targets none). estimatedDays is about how many days the views need at that rate, or null when there was no traffic. unspentIsReturned is true: budget that is not spent goes back when the campaign ends.
Freezes the quote and starts the payment. The same body as quote, plus a required idempotencyKey: the same key returns the same payment, never a second one. Send the person to checkoutUrl. Only the payment provider marks a payment paid; then the check runs and the campaign goes live. Live campaigns answer 409 live_payments_not_enabled until BHD switches card payments on.
curl -X POST "https://ads.bhd.om/v1/campaigns/cmp_YOUR_CAMPAIGN/checkout" \
-H "Authorization: Bearer sk_test_YOUR_KEY" -H "Content-Type: application/json" \
-d '{"pricing":"package","packageId":"starter","idempotencyKey":"order-2026-10-09-001"}'{ "id": "ADS-k2P...", "campaignId": "cmp_...", "provider": "test", "env": "test", "amount": 5250,
"currency": "OMR", "status": "pending", "card": null, "createdAt": "2026-10-09T08:00:00.000Z",
"succeededAt": null, "checkoutUrl": "https://ads.bhd.om/app#/test-pay/ADS-k2P..." }Takes a campaign that waits for payment back to draft.
curl -X POST "https://ads.bhd.om/v1/campaigns/cmp_YOUR_CAMPAIGN/pause" -H "Authorization: Bearer sk_live_YOUR_KEY"A move that the status does not allow answers 409 invalid_status_change with details.from.
The check
- The link is opened and read. A link that does not open sends the ad to a person.
- A fixed word screen reads the ad and the landing page. A word on the restricted list sends the ad to a person, whatever any model says.
- An AI reader (Claude) reads the ad, the picture and the landing page. If it does not answer, a second line of readers runs, and all of them must pass the ad.
- Pass: the campaign is approved and goes live, or waits for its start time. Anything unclear: the status is
reviewand a person at BHD decides. A machine never rejects an ad.
Status order: draft, payment_pending, paid, checking, approved, scheduled, live, paused, completed, ended. Also review, rejected, refund_pending, refunded.
Reports
curl "https://ads.bhd.om/v1/campaigns/cmp_YOUR_CAMPAIGN/report.csv" -H "Authorization: Bearer sk_live_YOUR_KEY" -o report.csv
# date,campaign,views,taps,tap_rate,spend_omrViews by placement and device system. BHD properties are named; partner properties are grouped as "Partner sites and apps".
Billing
payments (id, campaignId, provider, env, amount, currency, status, card, createdAt, succeededAt) and refunds (id, paymentId, amount, status, reason, createdAt).
An invoice: number (ADS-2026-00001, or TEST-... in test mode), kind, billTo, lines, subtotal, discount, tax, total, issuedAt, and the seller details.
The tax invoice as an A4 PDF. A live invoice answers 409 seller_details_missing until BHD enters its seller details.
curl "https://ads.bhd.om/v1/invoices/inv_YOUR_INVOICE/pdf" -H "Authorization: Bearer sk_live_YOUR_KEY" -o invoice.pdfPublishers
Each property with id, type (website, app, screen_network), name, domain, status (pending, approved, suspended, rejected), env and units.
Body: type, name, domain (required for a website), env. A live property starts as pending: this is the request for approval. A test property is approved at once.
Body: name, formatId (default card). Answer: id, propertyId, name, formatId, slot, status.
Body: { "status": "active" | "paused" | "archived" }.
days is 1 to 365. Add format=csv for a CSV file. balance is in baisa: pending (today, not yet rolled up), available, inPayout, paid, minPayout (set by BHD; null until set). Earnings fields that end in Mb are in milli-baisa.
curl "https://ads.bhd.om/v1/orgs/org_YOUR_ORG/earnings?days=30" -H "Authorization: Bearer sk_live_YOUR_KEY"
curl "https://ads.bhd.om/v1/orgs/org_YOUR_ORG/earnings?days=30&format=csv" -H "Authorization: Bearer sk_live_YOUR_KEY" -o earnings.csv{
"days": 30,
"totals": { "requests": 5120, "fills": 4980, "views": 3710, "clicks": 41, "earnedMb": 111300, "fillRate": 0.97, "rpmMb": 30000 },
"byDay": [ { "day": "2026-10-08", "requests": 170, "fills": 166, "views": 124, "clicks": 1, "earnedMb": 3720 } ],
"byUnit": [ { "propertyId": "prop_...", "unitId": "unit_...", "requests": 5120, "fills": 4980, "views": 3710, "clicks": 41, "earnedMb": 111300 } ],
"balance": { "pending": 3, "available": 108, "inPayout": 0, "paid": 0, "minPayout": 10000 }
}Requests a payout of the whole available balance. Errors: 409 bank_details_missing, 409 payouts_not_set_up, 409 below_minimum_payout (with details.minBaisa and details.availableBaisa), 409 payout_already_open. BHD finance approves it, sends the bank transfer and records its reference.
Webhook endpoints
endpoints, the last 50 deliveries (status, attempts, lastCode) and the list of events.
Body: url (a public https address), events (default: all), env (live default, or test). The answer has the signing secret, shown one time.
{ "url": "https://example.om/bhd-ads/webhook", "events": ["campaign.live", "payment.succeeded"], "env": "live" }Webhooks
BHD Ads sends a POST with a JSON event to your endpoint when something happens. A test endpoint gets test events only; a live endpoint gets live events only.
| Event | When |
|---|---|
campaign.created | A campaign was created. |
campaign.approved | The check or a person approved the campaign. |
campaign.rejected | A person did not approve the campaign. |
campaign.live | The campaign started showing. |
campaign.paused | The campaign was paused. |
campaign.completed | The budget or the time ran out. |
payment.succeeded | A payment was confirmed by the provider. |
payment.failed | A payment did not go through. |
refund.created | A refund request was opened. |
refund.succeeded | The money was sent back. |
payout.requested | A publisher asked for a payout. |
payout.paid | BHD recorded the bank transfer. |
property.approved | BHD approved a property. |
The 80% budget notice (campaign.budget_low) is an email to the organization, not a webhook event.
Payload and headers
POST /bhd-ads/webhook HTTP/1.1
content-type: application/json
user-agent: BHD-Ads-Webhooks/1.0
bhd-ads-signature: t=1791532800,v1=5f0c6a...e91
bhd-ads-event-id: evt_Qm3w...
{"id":"evt_Qm3w...","type":"campaign.live","created":"2026-10-09T08:00:00.000Z",
"data":{"campaignId":"cmp_...","orgId":"org_...","env":"live","from":"approved"}}The payload is { id, type, created, data }. data holds the ids of the objects, for example campaignId, paymentId, amount (baisa) and env. Read the full object from the API when you need it.
Signature
bhd-ads-signature: t=<unix seconds>,v1=<hex>. v1 is HMAC-SHA256 of the text ${t}.${rawBody}, with the endpoint secret (the whole whsec_... string) as the key. Compute it on the raw body bytes, compare in constant time, and reject a t that is more than 5 minutes from your clock. bhd-ads-event-id is the event id; it stays the same on every retry.
Node.js
const crypto = require('node:crypto');
/** true when the request came from BHD Ads. rawBody: the exact bytes received, as a string. */
function verifyBhdAds(rawBody, header, secret) {
const parts = Object.fromEntries(String(header || '').split(',').map((p) => p.split('=')));
const t = Number(parts.t);
if (!t || Math.abs(Date.now() / 1000 - t) > 300) return false; // older than 5 minutes
const want = crypto.createHmac('sha256', secret).update(`${t}.${rawBody}`).digest('hex');
const got = String(parts.v1 || '');
return got.length === want.length && crypto.timingSafeEqual(Buffer.from(got), Buffer.from(want));
}
// Express: read the raw body, not parsed JSON
app.post('/bhd-ads/webhook', express.raw({ type: 'application/json' }), (req, res) => {
const raw = req.body.toString('utf8');
if (!verifyBhdAds(raw, req.get('bhd-ads-signature'), process.env.BHD_ADS_WEBHOOK_SECRET)) return res.sendStatus(400);
const event = JSON.parse(raw);
// retries send the same event id: skip an id you already handled
res.sendStatus(200);
});PHP
<?php
function bhd_ads_verify(string $raw, string $header, string $secret): bool {
$p = [];
foreach (explode(',', $header) as $kv) {
[$k, $v] = array_pad(explode('=', $kv, 2), 2, '');
$p[$k] = $v;
}
$t = (int)($p['t'] ?? 0);
if ($t === 0 || abs(time() - $t) > 300) return false; // older than 5 minutes
$want = hash_hmac('sha256', $t . '.' . $raw, $secret);
return hash_equals($want, $p['v1'] ?? '');
}
$raw = file_get_contents('php://input');
if (!bhd_ads_verify($raw, $_SERVER['HTTP_BHD_ADS_SIGNATURE'] ?? '', getenv('BHD_ADS_WEBHOOK_SECRET'))) {
http_response_code(400);
exit;
}
$event = json_decode($raw, true);
// retries send the same event id: skip an id you already handled
http_response_code(200);Retries
- Answer with any
2xxwithin 10 seconds. A redirect, an error or a timeout is a failure. - BHD Ads sends due events every 20 seconds. After a failure it tries again after 1 minute, 5 minutes, 30 minutes, 2 hours and 6 hours: 6 attempts in all, over about 9 hours. Then the delivery is marked
failed. - An event can arrive more than once. Store the event id and skip one you already handled.
- The endpoint must be a public https address. It is checked again before each send.
Errors
An error has an HTTP status and a JSON body: error (a fixed code), details (sometimes) and reference (the request id). A stack trace is never returned.
HTTP/1.1 404 Not Found
x-request-id: 3f9c2a7b1d0e4c55
{ "error": "unknown_unit", "reference": "3f9c2a7b1d0e4c55" }
HTTP/1.1 400 Bad Request
{ "error": "campaign_incomplete", "details": { "missing": ["add at least one ad"] }, "reference": "..." }| Status | Codes | Meaning |
|---|---|---|
| 400 | invalid_json, invalid_text, invalid_url, invalid_list, invalid_email, invalid_query, invalid_pricing, invalid_package, invalid_format, invalid_media, campaign_incomplete, creative_does_not_fit, picture_required, not_an_image, file_too_large, daily_budget_too_low, invalid_promo_code, webhook_url_must_be_public_https | The request is not valid. details says what to fix when it can. |
| 401 | bad_key, sign_in_required, unknown_app | No valid key or session. |
| 403 | secret_key_required, not_allowed, key_and_unit_modes_differ, domain_not_allowed, organization_suspended, keys_are_made_in_the_console | The caller may not do this. |
| 404 | not_found, unknown_unit | It does not exist, or it belongs to another organization. |
| 405 | method_not_allowed | Wrong HTTP method. |
| 409 | pricing_not_set, live_payments_not_enabled, only_drafts_can_change, invalid_status_change, campaign_not_a_draft, idempotency_key_reused, not_an_advertiser, not_a_publisher, payout_already_open, below_minimum_payout, bank_details_missing, payouts_not_set_up, seller_details_missing | The request is valid but the current state does not allow it. |
| 413 | too_large | The body is too large (64 KB, or about 7.5 MB for a picture upload). |
| 429 | too_many_requests | Over the rate limit. Wait and try again. |
| 500, 502, 503, 504 | server_error, payment_start_failed, payments_not_set_up, pdf_failed, pdf_timeout | A problem on the BHD side or at a provider. Nothing was charged twice. Try again, and send the reference if it repeats. |
Rate limits
Limits are per network address, per minute. Over the limit, the API answers 429 too_many_requests until the next minute starts.
| Calls | Limit a minute |
|---|---|
/v1/ad, /v1/decide, /v1/events | 1200 |
/v1/i/*, /v1/c/* | 1200 |
/v1/auth/* | 12 |
| Other /v1/ calls (account API) | 240 |
| Pages and pictures | 300 |
Ad requests and beacons come from the devices of your visitors, so each device has its own limit. Your server calls to the account API share one limit.
Versioning
/v1is stable. BHD Ads does not remove a field, rename a field or change its meaning in/v1.- New fields and new event types can appear. Your code must ignore what it does not know.
- A breaking change goes to
/v2, and/v1keeps working. - The web SDK at
/v1/sdk.jsfollows the same rule.