@adsparty/sdk-server
v0.1.6
Published
Server client for requesting AdsParty ads and reporting delivery events.
Readme
@adsparty/sdk-server
Typed Node.js client for publisher bots, channels, delivery services, and other trusted backends that request AdsParty ads and report events.
Publisher setup: An approved publisher source and an approved active placement UUID are required before requests can return ads. Authorized workspace members create placements in Dashboard → Inventory and manage keys in Dashboard → Publisher API keys. See the publisher onboarding guide.
Install
npm install @adsparty/sdk-serverThe package is ESM, includes TypeScript declarations, has no runtime package dependencies, and requires Node.js 20 or newer for global fetch and crypto.randomUUID.
Configure a reusable client
Keep the publisher API key in server-only configuration. Never send it to a browser, Telegram Mini App, client-side bundle, or public repository.
import { createAdsPartyServerClient } from "@adsparty/sdk-server";
const ads = createAdsPartyServerClient({
baseUrl: process.env.ADSPARTY_API_URL!,
apiKey: process.env.ADSPARTY_PUBLISHER_API_KEY!,
});The base URL is an absolute HTTP or HTTPS API URL without /v1. Optional reverse-proxy path prefixes are preserved. The SDK sends the key in the X-Api-Key header.
Keys are scoped to one publisher workspace. Grant ads:request for ad requests and events:write for diagnostic impression reports. Clicks use the signed redirect URL; direct click event posts are rejected. Bot and channel requests must use a key from the same workspace that owns the placement. Conversions are accepted only through an advertiser-owned, authenticated tracker callback.
For an Inline placement, AdRequestInput.inlineSurface may be set to "mini_app_task_list" or "above_chat_list" to ensure the request matches its approved location. When omitted, the placement's configured location is used. The returned DeliveredAd.inlineSurface identifies that location; the publisher's host app decides where to render it. This field is independent of the task experience, which filters inventory and campaign matching. Task requirements and verification remain application-owned.
DeliveredAd.deliveryClass identifies paid inventory or a non-billable AdsParty house promotion. The Telegram helper labels house promotions in the message body; custom publisher renderers should preserve the same disclosure. Older responses default to paid.
Request and confirm delivery
const ad = await ads.requestAd({
placementId: process.env.ADSPARTY_PLACEMENT_ID!,
experience: "standard",
sessionId: createPseudonymousSessionId(telegramUserId),
user: { language: "en" },
});
if (ad === null) {
// No eligible ad; continue the normal bot flow.
return;
}
await sendTelegramMessage(chatId, formatAdMessage(ad));
const receipt = await ads.reportImpression(ad);
console.info("Event accepted", receipt.accepted);This example is for a Bot placement. reportImpressions(ads, options?) sends one to 50 token-bound diagnostic reports in one request and returns one receipt per input ad. An empty input returns [] without a request, and any rejected event prevents the batch from being persisted. A receipt confirms storage only; publisher reports and Telegram publication receipts are not billable and do not affect optimization because they cannot prove a user saw the ad.
The server SDK requires a sessionId of 8–128 characters. Use a stable pseudonymous value when requests should share a frequency cap. Do not use raw personal data as the session identifier. Derive it on your server, for example with HMAC-SHA256 over the Telegram ID and a private secret; keep the secret stable or frequency identity will reset. This SDK runs on your backend, so it cannot inspect an ad viewer's device. Only include user attributes your backend established from a trusted source such as an authenticated Telegram Bot API update; never copy a browser request's claimed user ID, language, country, or device into these fields.
import { createHmac } from "node:crypto";
function createPseudonymousSessionId(telegramUserId: number) {
return createHmac("sha256", process.env.ADSPARTY_SESSION_HMAC_SECRET!)
.update(`telegram-user:${telegramUserId}`)
.digest("base64url");
}For bot placements, report the publication signal only after Telegram confirms the send. For channels, AdsParty records its own successful publication receipt. Neither receipt establishes subscriber visibility, so both remain diagnostic, non-billable signals. If a send times out and you cannot tell whether it was delivered, avoid blindly sending it again.
Weekly posting availability configured for a Bot source is enforced by the ad-request API: requests outside the selected windows return null. AdsParty does not schedule or send publisher Bot messages. Your integration requests and sends them through the SDK with your own Bot API credentials. One-off scheduled publication is a Channel-only feature.
Optional Telegram Bot API sender
For Bot message placements, sendTelegramAd sends text, photo, video, or animation creatives with a tracked action button and returns publication metadata. It validates the creative and URL, uses a fixed HTTPS Telegram Bot API endpoint, applies a bounded timeout, and never retries automatically. It sets Telegram's protect_content flag so forwarded or saved copies are restricted. Keep the bot token in server-side secret storage. A successful send can be reported as a diagnostic publication signal, not a subscriber impression. AdsParty records its own channel publication receipts the same way. A timeout or Telegram 5xx response can leave delivery status unknown; reconcile the destination before retrying to avoid duplicates.
When a paid Bot ad has rewardUrl, sendTelegramAd adds a second Claim reward button below the advertiser action. The publisher bot sends the message using its own bot token. In the authenticated Telegram /start handler, validate the payload with ads.claimReward({ token, telegramId }). Grant the reward only for the first accepted claim (duplicate: false); repeated claims return duplicate: true. See the rewarded bot claims guide.
import { sendTelegramAd } from "@adsparty/sdk-server";
const delivery = await sendTelegramAd({
botToken: process.env.TELEGRAM_BOT_TOKEN!,
chatId: process.env.TELEGRAM_CHAT_ID!,
ad, // A standard bot_message DeliveredAd.
});
await ads.reportImpression(ad);
console.info("Telegram message sent", delivery.messageId);Use a format-specific host surface for Media and Inline creatives. The Telegram sender rejects those formats rather than silently changing their presentation.
Formats and experiences
The response has typed fields for format, mediaType, and experience:
| Format | Integration guidance |
| --- | --- |
| media | Render or send the assetUrl as an image, video, or GIF in a publisher surface. |
| inline | Render or send assetUrl as the icon beside the title and one-line body (up to 180 characters), with the optional actionLabel. |
| channel_post | Publish text, image, video, or GIF creatives with rich copy and a tracked action link. |
| bot_message | Send text, image, video, or GIF creatives with rich copy and a tracked action link. |
| website_banner | Return a fixed-size image or GIF banner from a trusted website backend request; render it in the browser and report viewability through the website-origin event route. |
The API keeps body as plain text for compatibility and may include bodyHtml for formatted copy. sendTelegramAd safely converts supported bold, italic, underline, strike, code, link, heading, paragraph, and list formatting into Telegram HTML. It validates links and escapes text; do not forward bodyHtml to Telegram as raw markup from an untrusted source.
Reward, interstitial, and task values are inventory matching labels. They do not implement presentation, verify viewing, or grant a reward. reportRewardCompleted(ad) persists a completion and returns an AdsParty-signed receipt. reportTaskCompleted(ad) is a publisher-server submission and must be called only after trusted application logic verifies the task. Both calls are bound to the publisher API key's workspace. Forward a browser receipt to your backend and call verifyCompletion(receipt) before granting a reward. The verification response includes trustSource: client_reported means the browser asserted that playback completed; it does not prove playback in an untrusted client. Apply application-specific fraud checks before granting valuable rewards. Place interstitials at natural pauses.
Clicks and conversions
Use the returned clickUrl in a Telegram button or tracked link. Its redirect records a request and forwards to the advertiser destination. AdsParty excludes obvious crawler, link-preview, and prefetch requests from CPC billing and click optimization; other redirects may count as measured clicks, not proof of human intent. Direct click event posts receive 403 tracked_click_required; the deprecated reportClick method rejects locally.
Do not use reportConversion for billing or optimization. It is retained as a deprecated method and throws. Configure a tracker integration in the advertiser workspace and send conversion outcomes through its authenticated callback. This prevents publisher controlled servers from creating CPA charges or changing conversion optimization signals.
For completion receipts, use reportRewardCompleted(ad) or reportTaskCompleted(ad), then call verifyCompletion(receipt) on the publisher backend before granting rewards. Task completion requires the matching Task experience and an authenticated publisher API key. Completion writes deduplicate per served ad request; publisher-server submissions can upgrade an earlier client-reported Reward claim.
Impression events require the eventToken from the matching ad response in X-AdsParty-Event-Token. It is bound to the request, campaign, banner, placement, source, and publisher workspace and expires after 15 minutes. Clicks use the returned signed clickUrl. Configure a workspace tracker integration from Dashboard → Tracking for conversions.
The API deduplicates impression reports and redirect requests by request and event type. Repeated reports can return duplicate: true. The caller-provided eventId is validated for impressions but does not define the durable dedupe key. Bot and Channel publication receipts remain diagnostic-only. Website and Mini App SDK viewability reports can qualify for CPM charges, tracked redirects can qualify for CPC charges, and authenticated advertiser tracker conversions can qualify for CPA charges. Viewability and redirect signals are publisher-controlled measurements, not independent proof of a human view or click.
No-fill, errors, and retries
- null is a normal no-fill result for HTTP 204. Keep the publisher's normal experience available and avoid immediate polling.
- Non-2xx responses reject with AdsPartyApiError. It exposes statusCode, API code, validation details, retryAfter, and isRetryable.
- AdsPartyProtocolError means a successful response did not match the documented JSON contract.
- Network errors reject and the SDK does not retry automatically.
- Correct request, credential, and workspace ownership issues before retrying 400, 401, or 403 responses.
- Honor retryAfter for rate limits. Use bounded exponential backoff with jitter for transient 429 or 5xx errors.
- Event writes can be retried safely within the token lifetime because the API deduplicates logical events.
See the bot and channel guide, HTTP API reference, event guide, and error guide.
Runnable Telegram Bot and Channel projects are included in the repository.
Public API
The package exports AdsPartyServerClient, createAdsPartyServerClient, sendTelegramAd, createTelegramAdPayload, AdsPartyTelegramError, AdExperience, AdRequestInput, DeliveredAd, EventReceipt, CompletionReceipt, CompletionVerification, RewardClaimReceipt, AdsPartyApiError, and AdsPartyProtocolError from its package root. AdsPartyServerClient.claimReward({ token, telegramId }) validates a Telegram /start claim through the publisher API.
Development and publication
From this directory:
npm run check-types
npm run build
npm pack --dry-runThe package is configured for public scoped npm access under the MIT license. Its version is released independently from the browser SDK.
Release
To publish a patch, increase this package's version in package.json and push the change to the repository's default branch. The CI workflow compares the version with npm's latest tag, runs the monorepo and clean-consumer checks, then publishes the package to latest through GitHub Actions OIDC. workflow_dispatch runs verification only; publication requires a default-branch push. Prerelease versions publish to npm's next tag.
Configure npm Trusted Publishing for this package with GitHub account mhbdev, repository adsparty, workflow filename ci.yml, and no environment. Allow direct npm publish for this publisher. Repeat the setup for @adsparty/sdk-browser. The repository is private, so npm does not generate provenance attestations for these publishes; OIDC authentication still avoids long-lived publish tokens. See npm trusted publishing.
