BHD Ads

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:

text
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 in Mb is 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-id header. Errors repeat it as reference. 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.

CallReturns
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/formatsThe ad formats on sale, each with id, name, kind and requirements (picture size, text limits).
GET /v1/public/inventoryproperties: 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.

http
Authorization: Bearer sk_live_...
KeyStarts withUse
Publishablepk_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.
Secretsk_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 gets 401 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/ad refuses a secret key with 403 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

html
<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

html
<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>
OptionMeaning
keyYour publishable key. Required.
unitThe ad unit id. Required.
targetA CSS selector or an element. The ad goes inside it.
langen or ar. Default: the lang of the page.
consentpersonalized 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

  1. It requests GET /v1/ad once for each element, with os=web. It never requests twice for the same element.
  2. 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.
  3. It fetches impressionUrl one time, when at least half of the ad is on the screen for one second without a break. Never on load.
  4. A tap opens clickUrl in a new tab with rel="noopener sponsored".
  5. 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:

text
script-src  https://ads.bhd.om;
connect-src https://ads.bhd.om;
img-src     https:;

Ad request

GET/v1/adpublishable key

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.

ParameterMeaning
unitRequired. The ad unit id, for example unit_ab12cd34. A paused or archived unit answers 404 unknown_unit.
keyYour publishable key, when you cannot send the Authorization header.
osweb, ios or android. Default web.
langen or ar (the first 2 letters are used). An ad in this language is chosen first.
consentpersonalized or non_personalized. Any other value is stored as unknown.
countryOptional, 2 letters, for example OM. Default: the country of the request as seen by Cloudflare.
cityOptional, up to 60 characters. Used only by campaigns that target cities.
bash
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

json
{
  "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
}
FieldMeaning
title, body, ctaThe headline, the text and the button label. body and cta can be empty strings.
sponsorThe advertiser name. Show it next to the word "Ad".
langen or ar. Draw the ad right to left when it is ar.
imageUrlAn https picture, or an empty string. The card format uses a 1.91:1 picture.
impressionUrlFetch it once when the ad was seen. See Counting rules. It expires 1 hour after the request.
clickUrlOpen it on a tap. It counts the tap and redirects to the advertiser. It expires 24 hours after the request.
targetUrlThe advertiser link, for display only. Never open it directly: the tap would not count.
kinddirect for a paid or BHD ad, house for a BHD house ad.
testtrue in test mode. Show a TEST tag.

Response: no ad

json
{ "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

StatuserrorMeaning
401bad_keyNo key, an unknown key or a revoked key.
404unknown_unitThe unit does not exist, is not active, or belongs to another organization.
403key_and_unit_modes_differA test key with a live unit, or the other way round.
403domain_not_allowedA 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.
429too_many_requestsOver 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 impressionUrl one 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 impressionUrl answers 204 but counts nothing. Ask for a new ad to show a new ad.
  • A tap goes through clickUrl. It answers 302 to 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.
BeaconAnswer
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).

Mobile apps

  1. Call GET /v1/ad from the app on the device, with your publishable key, os=ios or os=android, and the language of the app.
  2. 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 when test is true.
  3. Fetch impressionUrl once, when at least half of the ad is on the screen for one second.
  4. On a tap, open clickUrl in the browser.

Swift (iOS)

swift
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)

kotlin
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.

GET/v1/decideBHD app key
ParameterMeaning
appRequired. The property id of the app, for example jamiya.
osRequired. ios, android or web.
slotcard (default), fullscreen or rewarded. rewarded returns no BHD ad, only the Google unit.
lang, country, consentAs 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.

bash
curl "https://ads.bhd.om/v1/decide?app=jamiya&os=ios&slot=card&lang=ar" \
  -H "Authorization: Bearer APP_KEY"
json
{
  "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.

POST/v1/eventsBHD app key

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.

bash
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

GET/v1/mesecret key

With a secret key: { signedIn: true, key: { kind, env }, organizations: [ ... ] }. Use it to find your organization id.

GET/v1/orgs/{orgId}secret key

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.

bash
curl "https://ads.bhd.om/v1/orgs/org_YOUR_ORG" -H "Authorization: Bearer sk_live_YOUR_KEY"
GET/v1/orgs/{orgId}/memberssecret key

Changing the organization (PATCH /v1/orgs/{orgId}), members, agencies and keys is for an organization admin in the console.

GET/v1/targets?env=livesecret key

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

POST/v1/orgs/{orgId}/mediasecret key

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.

bash
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')\"}"
json
{ "id": "med_Xw...", "mime": "image/png", "bytes": 182311, "width": 1200, "height": 628,
  "url": "https://ads.bhd.om/m/med_Xw....png", "problems": [] }

Campaigns

GET/v1/orgs/{orgId}/campaignssecret key

Lists campaigns, newest first. Filters: status, q (part of the name), limit, offset.

bash
curl "https://ads.bhd.om/v1/orgs/org_YOUR_ORG/campaigns?status=live&limit=20" \
  -H "Authorization: Bearer sk_test_YOUR_KEY"
POST/v1/orgs/{orgId}/campaignssecret key

Creates a draft campaign. The organization must be an advertiser (409 not_an_advertiser).

FieldMeaning
nameRequired, up to 80 characters.
envtest or live (default live).
objectivevisits (default), awareness, leads, sales, app_installs, engagement.
startAt, endAtOptional ISO times.
frequencyCapOptional, 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.
targetingAll 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.
bash
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"] }
  }'
GET/v1/campaigns/{campaignId}secret key

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).

PATCH/v1/campaigns/{campaignId}secret key

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.

POST/v1/campaigns/{campaignId}/quotesecret key

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.

bash
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}'
json
{
  "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.

POST/v1/campaigns/{campaignId}/checkoutsecret key

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.

bash
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"}'
json
{ "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..." }
POST/v1/campaigns/{campaignId}/cancelsecret key

Takes a campaign that waits for payment back to draft.

POST/v1/campaigns/{campaignId}/pausesecret key
POST/v1/campaigns/{campaignId}/resumesecret key
bash
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

  1. The link is opened and read. A link that does not open sends the ad to a person.
  2. 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.
  3. 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.
  4. Pass: the campaign is approved and goes live, or waits for its start time. Anything unclear: the status is review and 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

GET/v1/campaigns/{campaignId}/report.csvsecret key
bash
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_omr
GET/v1/campaigns/{campaignId}/placementssecret key

Views by placement and device system. BHD properties are named; partner properties are grouped as "Partner sites and apps".

Billing

GET/v1/orgs/{orgId}/paymentssecret key

payments (id, campaignId, provider, env, amount, currency, status, card, createdAt, succeededAt) and refunds (id, paymentId, amount, status, reason, createdAt).

GET/v1/orgs/{orgId}/invoicessecret key
GET/v1/invoices/{invoiceId}secret key

An invoice: number (ADS-2026-00001, or TEST-... in test mode), kind, billTo, lines, subtotal, discount, tax, total, issuedAt, and the seller details.

GET/v1/invoices/{invoiceId}/pdfsecret key

The tax invoice as an A4 PDF. A live invoice answers 409 seller_details_missing until BHD enters its seller details.

bash
curl "https://ads.bhd.om/v1/invoices/inv_YOUR_INVOICE/pdf" -H "Authorization: Bearer sk_live_YOUR_KEY" -o invoice.pdf

Publishers

GET/v1/orgs/{orgId}/propertiessecret key

Each property with id, type (website, app, screen_network), name, domain, status (pending, approved, suspended, rejected), env and units.

POST/v1/orgs/{orgId}/propertiesconsole only: organization admin

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.

POST/v1/properties/{propertyId}/unitsconsole only: organization admin

Body: name, formatId (default card). Answer: id, propertyId, name, formatId, slot, status.

PATCH/v1/units/{unitId}console only: organization admin

Body: { "status": "active" | "paused" | "archived" }.

GET/v1/orgs/{orgId}/earnings?days=30secret key

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.

bash
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
json
{
  "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 }
}
GET/v1/orgs/{orgId}/payoutssecret key
POST/v1/orgs/{orgId}/payoutsconsole only: organization admin

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

GET/v1/orgs/{orgId}/webhooksconsole only: organization admin

endpoints, the last 50 deliveries (status, attempts, lastCode) and the list of events.

POST/v1/orgs/{orgId}/webhooksconsole only: organization admin

Body: url (a public https address), events (default: all), env (live default, or test). The answer has the signing secret, shown one time.

json
{ "url": "https://example.om/bhd-ads/webhook", "events": ["campaign.live", "payment.succeeded"], "env": "live" }
DELETE/v1/orgs/{orgId}/webhooks/{endpointId}console only: organization admin

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.

EventWhen
campaign.createdA campaign was created.
campaign.approvedThe check or a person approved the campaign.
campaign.rejectedA person did not approve the campaign.
campaign.liveThe campaign started showing.
campaign.pausedThe campaign was paused.
campaign.completedThe budget or the time ran out.
payment.succeededA payment was confirmed by the provider.
payment.failedA payment did not go through.
refund.createdA refund request was opened.
refund.succeededThe money was sent back.
payout.requestedA publisher asked for a payout.
payout.paidBHD recorded the bank transfer.
property.approvedBHD approved a property.

The 80% budget notice (campaign.budget_low) is an email to the organization, not a webhook event.

Payload and headers

http
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

javascript
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
<?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 2xx within 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
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": "..." }
StatusCodesMeaning
400invalid_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_httpsThe request is not valid. details says what to fix when it can.
401bad_key, sign_in_required, unknown_appNo valid key or session.
403secret_key_required, not_allowed, key_and_unit_modes_differ, domain_not_allowed, organization_suspended, keys_are_made_in_the_consoleThe caller may not do this.
404not_found, unknown_unitIt does not exist, or it belongs to another organization.
405method_not_allowedWrong HTTP method.
409pricing_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_missingThe request is valid but the current state does not allow it.
413too_largeThe body is too large (64 KB, or about 7.5 MB for a picture upload).
429too_many_requestsOver the rate limit. Wait and try again.
500, 502, 503, 504server_error, payment_start_failed, payments_not_set_up, pdf_failed, pdf_timeoutA 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.

CallsLimit a minute
/v1/ad, /v1/decide, /v1/events1200
/v1/i/*, /v1/c/*1200
/v1/auth/*12
Other /v1/ calls (account API)240
Pages and pictures300

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

  • /v1 is 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 /v1 keeps working.
  • The web SDK at /v1/sdk.js follows the same rule.