For agents: reference card
Dense, source-checked facts for coding agents integrating GoPayLocal — the public endpoints, SDK entry points, banner script URL, template tokens, A/B tests and common mistakes.
Written for coding agents. Every fact on this page was checked against the GoPayLocal source code (github.com/RayLabsHQ/gopaylocal; file paths in square brackets). If another docs page disagrees with this card, trust this card.
Mental model
Section titled “Mental model”- A merchant’s site runs one client in the visitor’s browser: the banner script,
@gopaylocal/react, or@gopaylocal/js. Every client makes the same public call,GET https://api.gopaylocal.com/v1/banner/config/{publicKey}, optionally with?product=and&vid=. The three clients build that request with the same shared code. [apps/api/src/routes/banner-script.ts, packages/js-sdk/src/core.ts] - The API reads the visitor’s country from Cloudflare’s
request.cf.countryonly. It never trusts a header (such asCF-IPCountry) or a query parameter, so the country cannot be overridden from code. - The API answers with one campaign’s discount percentage and coupon code for that country. Which campaign [apps/api/src/services/banner-selection.ts]:
- A campaign can be served when its status is
activeand it has a banner config. Every new campaign gets one with the default design. - With
product, only that product’s campaigns count. An unknown product, or one with nothing servable, givesno_active_campaign; it never falls back to another product. - Without
product, the API uses the product of the newest servable campaign in the account. - Campaigns are
liveortest. For a product, a servablelivecampaign wins over anytestone. Requests answered by atestcampaign don’t count against the plan. - Within a product and environment, a running A/B test comes first. When both of its campaigns are servable, each visitor is assigned to one of them. When only one is, that campaign answers every visitor and the response carries no
experimentId. When neither is, the test is ignored. Without a running test, the newest servable campaign answers.
- A campaign can be served when its status is
- A public key belongs to an account, not to a product. Pass the product id to pin a page to one product.
- GoPayLocal creates the coupon codes in the merchant’s payment provider for campaigns linked to a connected integration. The visitor types the code at the merchant’s normal checkout, so the checkout must accept discount codes. [apps/api/src/routes/campaigns.ts, apps/api/src/services/parity.service.ts]
- Stripe Checkout Session created in the merchant’s code:
allow_promotion_codes: true, or pass the promotion code indiscounts(Stripe integration). - WooCommerce: the customer types the code in the cart or checkout coupon field. On WooCommerce 10.0 or later a checkout link can apply it:
https://<store>/checkout-link/?products=<productId>:1&coupon=<code>(WooCommerce integration). - Use
codeexactly as the API returns it. Codes can contain hyphens (WooCommerce codes look likePPP-IN40-K7QX), so URL-encode it rather than reformatting it.
- Stripe Checkout Session created in the merchant’s code:
- Products, campaigns, discount levels, integrations and A/B tests are set up by the human in GoPayLocal at
https://app.gopaylocal.com, not in site code. That includes each campaign’s banner design: position, message, button text, colors, flag and close button, edited on the campaign page under Setup > Banner. New campaigns start with the default design shown under Config endpoint. It also includes each campaign’s allowed domains, which have no dashboard field. An agent cannot change any of these (see the note under What to get from the human). [apps/dashboard/src/components/banner-editor.tsx]
What to get from the human
Section titled “What to get from the human”| Need | Details |
|---|---|
| Public API key | gpl_pk_ followed by 64 hex characters [apps/api/src/routes/api-keys.ts]. Created in the dashboard under API keys. Public by design: it ends up in page source, so it is safe in client bundles and HTML. |
| Payment provider | One of Stripe, Paddle, Gumroad, Chargebee, Dodo Payments, Polar, Whop, Creem or WooCommerce [packages/shared/src/types/index.ts IntegrationProvider]. Connected in the dashboard, not in code. Creem, WooCommerce, and Stripe’s Managed Payments mode (which the merchant turns on in Stripe; GoPayLocal has no setting for it) are implemented but not yet verified against a live account. WooCommerce has no test mode: its coupons are always real coupons in the store. Live-verification status per provider: apps/api/PROVIDER_VERIFICATION.md. |
| Dashboard setup | A product and an active campaign linked to the provider integration. Without a servable campaign the API answers show: false with no_active_campaign. |
| Product id | Only when the account has several products and a page belongs to one of them: pass it as data-product (banner script) or productId (SDKs). |
| Allowed domains | Only if the campaign has them. Then the request’s Origin (or Referer) hostname must equal a listed domain or be a subdomain of one, otherwise reason: "domain_not_allowed". Local testing needs localhost (or the dev host) in the list. |
| API origin | Only for a self-hosted GoPayLocal deployment: the URL of its API. It replaces https://api.gopaylocal.com everywhere on this card: the script host, the SDKs’ apiBase and the CSP entries. |
Never use a secret key (gpl_sk_…) in an integration. The banner script answers 400, and the config and events endpoints answer 401 with "code": "secret_key_not_allowed" [apps/api/src/lib/public-key.ts]. A secret key is for the human’s own server, calling the management API under /v1/teams/{orgId}/ [apps/api/src/middleware/api-key.ts]; a banner or SDK integration never needs it. Don’t change account settings (campaigns, discounts, banner designs, allowed domains, A/B tests) from integration code; ask the human to make the change in the dashboard.
Choose one client
Section titled “Choose one client”| Client | Install | Renders a banner | Banner design | Analytics events |
|---|---|---|---|---|
| Banner script | <script src="https://api.gopaylocal.com/v1/banner/script.js?key=KEY" async></script> |
Yes, automatically | The campaign’s | copy, sent automatically |
| React SDK | npm install @gopaylocal/react |
Only if you render <PPPBanner /> |
The campaign’s; props override it | <PPPBanner /> sends copy; for your own UI call usePPP().track(event) |
| JS SDK | npm install @gopaylocal/js |
Only if you call gpl.showBanner() |
The campaign’s; options override it | showBanner() sends copy; for your own UI call gpl.track(event) |
- Pick one banner. The banner script plus
<PPPBanner />shows two banners. - All three banners add a “Powered by GoPayLocal” link when the response has
showBranding: true. The server decides this; it is not configurable from code. - Impressions are counted by the API: one for each config request answered with
show: true. No client sends them. - Events are only sent when a discount applies (they need the response’s
campaignId).track()sendsclickandcopy; it also acceptsimpressionanddismissand sends nothing for them. - There is no server-side pricing API. The config endpoint uses the country of whoever makes the request, so calling it from a server, edge function, build step or CI gives the server’s country and usually
vpn_detected. Fetch from the browser.
Banner script
Section titled “Banner script”<script src="https://api.gopaylocal.com/v1/banner/script.js?key=gpl_pk_REPLACE_ME" async></script>Optional attributes on the same tag [packages/banner/src/setup.ts]:
data-product="<productId>": only that product’s campaign.data-visitor-id="<id>": your own visitor id for experiment assignment. It must be 16 to 64 characters ofA-Z a-z 0-9 _ -; anything else is ignored. No personal data.data-no-storage: store nothing in the browser (nosessionStoragecache or dismissal, nolocalStoragevisitor id).
How the script works:
-
Key. The key goes in the
keyquery parameter of the script URL. There is nodata-keyattribute. [packages/banner/src/setup.ts reads?key=] -
How settings are read. The script looks at its own tag first, then every script whose
srccontains/v1/banner/orgopaylocal, in document order. It takes:- the key from the first of those tags with a
keyparameter - the API base from that tag’s
src(everything before/v1/), so a self-hosted API works by changing the script host - each data attribute from the first tag that has it
- the key from the first of those tags with a
-
One static file.
script.jsis the banner itself, the same file for every key, served without running the API.bundle.jsis the same file under an older name. The server does not readkeyon this request, so it never answers 400 for a missing or malformed key. -
Errors. A tag without a
keyparameter does nothing. A secret key (gpl_sk_) sends nothing and logs an error to the browser console. An unknown key gets401from the config request, and no banner. -
Runtime [packages/banner/src/index.ts]:
- 5-second fetch timeout.
- The config response is cached for 5 minutes in
sessionStoragekeygpl_c_<key>_<productId>. The product part is empty withoutdata-product. - Clicking close sets
gpl_d_<key>_<productId>="1", which hides the banner for the rest of the session in that tab. - It renders into a closed Shadow DOM with
position: fixedand the maximumz-index. - The copy button appears only when
codeis not null. - It sends
copywhen the code is copied. The impression was counted by the API when it answered the config request, and a dismissal is only remembered in the browser. Events go toPOST /v1/eventswithnavigator.sendBeacon, falling back to a keepalivefetch.
-
Page event. After each config response, including cached ones and
show: false, the script dispatches agopaylocal:configCustomEventondocument. Itsdetailis{ show, country, discount, code, campaignId, experimentId, variant }, so page code can read the result and the experiment arm. It does not fire when the banner was dismissed earlier in the session or the request failed. -
Positions.
topandbottomrender a full-width bar.bottom-leftandbottom-rightrender a card that also shows the country name. -
Content Security Policy. Allow
https://api.gopaylocal.cominscript-srcandconnect-src. The banner’s styles are a constructed stylesheet, which astyle-srcwithout'unsafe-inline'does not block. Browsers without constructable stylesheets get a<style>element instead. [packages/js-sdk/src/core.tsadoptStyles]
A/B tests
Section titled “A/B tests”[apps/api/src/services/experiment.service.ts, apps/api/src/services/banner-selection.ts; the API calls them experiments]
What exists:
- A test links exactly two campaigns of the same product and the same environment: A, the control, and B, the variant. A product has at most one running test per environment (
live,test). - The human starts, changes and ends tests in the dashboard: A/B Tests, or a campaign’s Settings > A/B Testing. Both campaigns must be active when the test starts.
- The traffic split is the percentage of visitors sent to B, from 1 to 99 (default 50).
- Arms are sticky. The API hashes the test id with the visitor key (the
vid, or IP address plus user agent when there is none) and compares the result with the split. A visitor stays in their arm while the test and its split are unchanged. Changing the split moves only the visitors between the old and the new value. - The assigned arm always answers. If its campaign gives the visitor’s country no discount, or the domain is not allowed, the answer is
show: falsewithexperimentIdandvariant. The visitor is not moved to the other arm. - Results, in the dashboard, are raw counts and rates per arm: impressions, clicks, copies, redemptions, revenue saved per currency, click, copy and conversion rates, and redemptions per copy. They come from daily rollups (whole UTC days) and only reach back as far as the account’s analytics history.
- End test: the human picks the winner. The winner stays active and the other campaign is paused. After that the product is served the normal way, by its newest servable campaign.
- While a test runs, its campaigns cannot be paused, set back to draft, moved to another product or environment, or deleted (
409).
What does not exist: per-country tests or per-country results (a test splits every visitor of the product, even though the two campaigns can set different per-country discounts), a significance or lift figure, and a no-discount control arm (a campaign with 0% for a country serves nothing there, so it collects no data).
What an integration needs for a test:
- Usually nothing extra. All three clients send
vidand report events with the assigned arm’scampaignId, which is how each arm gets its own numbers. - On a site with several products, pass the product id (
data-productorproductId). Otherwise the request can be answered for another product and the test never applies. - Don’t set
data-no-storageorpersistVisitorId: falseunless the human asks for it. Assignment then falls back to IP address plus user agent, and a visitor whose IP changes can switch arms. - To keep a signed-in user in one arm across devices, pass a stable id that is not personal data as
data-visitor-idorvisitorId(16 to 64 characters ofA-Z a-z 0-9 _ -, so an email address is rejected). - A custom banner must report clicks and copies with
track()(orPOST /v1/events) using the response’scampaignId, or its arm records none. Impressions need nothing: the API counts them for the arm it served. - To record the arm in the site’s own analytics, read
experimentIdandvariantfrom thegopaylocal:configevent,gpl.getExperiment()orusePPP(). They are set even when the arm shows no banner.
Visitor id (A/B test assignment)
Section titled “Visitor id (A/B test assignment)”[packages/js-sdk/src/core.ts]
- All three clients share one
localStoragekey,gpl_vid. It holds a random 32-hex-character id from Web Crypto and is sent only to the GoPayLocal API, asvid. It keeps a visitor in the same arm across page loads and across clients on the same origin. The API uses it only for the assignment and does not store it. - A valid id from
data-visitor-idor the SDKs’visitorIdis used as is and never stored. - With
data-no-storageorpersistVisitorId: false, no id is sent. The API then assigns the arm from a hash of IP address and user agent.
Config endpoint
Section titled “Config endpoint”GET /v1/banner/config/{publicKey}?product={productId}&vid={visitorId} — public, no auth header, both query parameters optional. Call it from the visitor’s browser. [apps/api/src/routes/banner-script.ts]
productmust match[A-Za-z0-9_-]{1,64}. Any other value means nothing is served (no_active_campaign).vidmust be 16 to 64 characters ofA-Z a-z 0-9 _ -. Anything else is ignored.
Discount available (HTTP 200). Shape, with placeholder values:
{ "show": true, "country": "IN", "countryName": "India", "discount": 30, "code": "<coupon code, or null>", "baseCurrencyCode": "USD", "baseCurrencySymbol": "$", "currencyCode": "INR", "currencySymbol": "₹", "fxRate": 93.32614706, "fxAsOf": "2026-11-18", "localPrice": 1249, "localOriginalPrice": 1769, "charmPricingStrategy": "round_x9", "campaignId": "<campaign id>", "experimentId": "<only when an experiment applied>", "variant": "a", "showBranding": false, "banner": { "position": "bottom", "messageTemplate": "It looks like you're visiting from {{country}}! Use code {{code}} for {{discount}}% off.", "ctaText": "Copy Code", "backgroundColor": "#1a1a2e", "textColor": "#ffffff", "ctaColor": "#e94560", "ctaTextColor": "#ffffff", "showFlag": true, "showCloseBtn": true }}The banner values above are the defaults every new campaign gets.
| Field | Meaning |
|---|---|
show |
true only when a discount applies. |
country |
ISO 3166-1 alpha-2 code from Cloudflare. |
countryName |
English country name. |
discount |
Percentage as a number, e.g. 40 means 40% off. No % sign. |
code |
Coupon code for this country, or null if no coupon exists for it in the provider. |
baseCurrencyCode, baseCurrencySymbol |
The product’s currency (ISO 4217) and its symbol. |
currencyCode, currencySymbol |
The currency of localPrice and localOriginalPrice: the visitor’s when the prices were converted, otherwise the product’s. |
fxRate |
Units of currencyCode per 1 unit of baseCurrencyCode (10 significant digits); 1 when not converted. |
fxAsOf |
Date of the exchange rates, YYYY-MM-DD. Present only when the prices were converted. |
localPrice |
Number. The product’s price after the discount, in currencyCode. Converted: rounded up by the charm strategy. |
localOriginalPrice |
Number. The product’s price before the discount, in currencyCode. Converted: rounded down. |
charmPricingStrategy |
The campaign’s rounding: none, dot99, round_x9, nearest_5 or region_aware. |
campaignId |
The campaign that answered (the assigned one during an experiment). Sent with analytics events. |
experimentId, variant |
Present only when a running experiment applied; variant is "a" or "b". Also present on no_discount and domain_not_allowed answers. |
showBranding |
Server-decided; see Choose one client. |
banner |
The campaign’s banner design. For a holiday deal, messageTemplate is the deal’s message and showFlag is false. |
deal |
Present only when the offer is a holiday deal: { "id", "name", "endsAt" }. discount and code are then the deal’s (code is null for a deal without one), and the price fields use the deal’s percentage. |
Local prices [packages/shared/src/currency/local-price.ts]:
- Converted (
fxAsOfpresent): the visitor’s country uses another currency and the exchange rates are less than 96 hours old.localPrice=basePrice × (1 − discount/100) × fxRate, charm-rounded up (never below that amount, at most 8% above it).localOriginalPrice=basePrice × fxRate, charm-rounded down. The example above is a $19 product at 30% off withround_x9, for a visitor in India on the rates of 2026-11-18: ₹1,249, was ₹1,769. The two are chosen together so that the discount they imply is never above the real one and, except for prices of a few cents, neither more than 2 points below it nor under four fifths of it [packages/shared/src/currency/pair.ts]. - Exact (no
fxAsOf): the visitor pays in the product’s currency, the rates are stale or missing, the visitor’s currency has no rate, or no converted pair is possible (the paid price would not be below the original, or the converted price rounds to zero).currencyCodeequalsbaseCurrencyCode,fxRateis1, and the prices are exact, with no charm rounding. A US visitor at 60% off a $19 product getslocalPrice7.6 andlocalOriginalPrice19.
Local prices are estimates. They convert your price at the day’s mid-market rate and round up to a charm price, at most 8% above the converted amount and never below it (an amount under 13 of the currency’s smallest unit can round up by more than 8%, to the next one). Your payment provider charges the exact discounted price in your currency; the amount on the customer’s statement depends on their bank’s exchange rate.
No discount (still HTTP 200): { "show": false, "reason": "<reason>" }, plus experimentId and variant where noted above. The checks run in this order:
reason |
Meaning |
|---|---|
unknown_country |
Cloudflare reported no country, XX, or T1 (Tor). |
vpn_detected |
The request comes from a known VPN, a Tor exit, or a datacenter or cloud network. Servers, CI machines and some corporate networks get this. [apps/api/src/services/vpn-detect.service.ts] |
quota_exceeded |
The account’s monthly API quota is used up. Only hosted accounts whose plan has a quota; never on self-hosted deployments. |
no_active_campaign |
Nothing servable: no active campaign with a banner config for the requested (or default) product, or an invalid product value. |
domain_not_allowed |
The campaign has allowed domains and the request’s Origin/Referer host is missing or not listed. |
no_discount |
The campaign gives this country no discount (or 0%) and no holiday deal is running. |
The key is checked between unknown_country and vpn_detected.
Holiday deals [packages/shared/src/deals/index.ts, apps/api/src/routes/banner-script.ts]: a campaign can have deals (a percentage, a start, an end, one code for every visitor). After domain_not_allowed, a deal running at request time is offered when its percentage is at least the visitor’s country discount (0 for a country without one); otherwise the country’s discount is. A client needs no change: discount, code, the prices and banner.messageTemplate are already the deal’s.
Errors:
401 {"error":"Invalid API key"}: an unknown or revoked key.401with"code": "secret_key_not_allowed": a secret key (gpl_sk_). It is refused before any lookup and never echoed.429 {"error":"rate_limited"}, with aRetry-Afterheader.500 {"show":false,"reason":"internal_error"}.
What counts as an API call. The server counts one call for each config request with a valid key that reaches campaign selection, whatever the answer: a banner, no_active_campaign, domain_not_allowed or no_discount. [apps/api/src/routes/banner-script.ts meterApiCall]
- Not counted:
unknown_country,vpn_detected,quota_exceeded,401,429,script.js,bundle.jsand/v1/events. - Calls answered by a
testcampaign are recorded separately and don’t count against the plan. - Client caching saves calls. The banner script caches every config response for 5 minutes in the tab, unless
data-no-storageis set. The SDKs cache only responses with a discount.
React SDK: @gopaylocal/react
Section titled “React SDK: @gopaylocal/react”[packages/react-sdk/src]
Install
npm install @gopaylocal/react. Peer dependency:react^18 || ^19. ESM and CommonJS builds.
Next.js App Router
- The bundle starts with
'use client', soapp/layout.tsx(a Server Component) can render<GoPayLocalProvider apiKey={...}>directly. - Function props (
onLoad,onError,<PPPPricingTable onPlanSelect>) cannot be passed from a Server Component. When you need them, put the provider or table in your own file that starts with'use client'. - Components that call the hooks must be client components.
Provider
<GoPayLocalProvider apiKey>wraps everything that uses the hooks or components. Props:apiBase(defaulthttps://api.gopaylocal.com)productIdvisitorIdpersistVisitorId(defaulttrue)baseCurrencyCode: the currency of the prices you pass in. Defaults to the product’s currency from the API (USDbefore the API answers or when no discount applies).baseCurrencySymbol: defaults to the product’s symbol from the API, or the symbol ofbaseCurrencyCodein the visitor’s locale.onLoad(data): called only when a discount appliesonError(error): also called for the 8-second timeout
- There is no
environmentprop and no sandbox host. - Leave
baseCurrencyCodeunset when your prices are in the product’s currency. Prices are converted to the visitor’s currency only when the response was converted (fxAsOfset) andbaseCurrencyCodeequals the product’s currency. Set to another currency, prices stay unconverted and the provider logs one console warning. [packages/react-sdk/src/provider.tsxpriceContext]
Hooks
usePPP()returns{ data, isLoading, error, country, discount, code, baseCurrencyCode, baseCurrencySymbol, currencyCode, currencySymbol, fxRate, fxAsOf, charmPricingStrategy, localPrice(basePrice), localOriginalPrice(basePrice), formatPrice(price, intlOptions?), flag, campaignId, experimentId, variant, track(event) }.currencyCodeandcurrencySymbolare the currency prices are shown in: the visitor’s when converted, otherwisebaseCurrencyCode.fxAsOfisnullunless prices are converted.localPrice(basePrice)is the discounted price incurrencyCode, charm-rounded up when converted, otherwise exact.localOriginalPrice(basePrice)is the price before the discount, charm-rounded down when converted. Same rule as the API [packages/js-sdk/src/price.tslocalPrices].- It throws outside the provider.
discountis0when no discount applies.experimentIdandvariantare also set when the visitor’s arm has no discount (dataisnull).isLoadingistrueon the server and on the first client render.
usePrice({ price, localize?, showDecimal?, minimumDecimalDigits?, maximumDecimalDigits? })returns{ originalPrice, discountedPrice, localPrice, localOriginalPrice, converted, formatted, formattedOriginal, discount, integer, decimal, currencySymbol, currencyCode, hasDiscount }.discountedPriceis in the base currency, unrounded.localPrice,formattedandformattedOriginalare incurrencyCode;formattedOriginalis the visitor’s currency too whenconverted.- By default whole amounts format without decimals (
₹719,$19) and other amounts keep the currency’s digits ($7.60).showDecimal: truealways shows decimals;showDecimal: falsenever does.
Components
<PPPBanner />- Props:
position,backgroundColor,fontColor,borderRadius,fontSize,className,onClose,showCloseIcon,noStyles. - Uses the campaign’s design (position, colors, message, CTA text, flag, close button), and props override it.
showCloseIconfalls back to the design’sshowCloseBtn. - Renders nothing when
discountis 0. - Sends
copy. - The message is plain text (
**is not interpreted). - Dismissal is component state only and is not remembered across page loads.
- Props:
<PPPPrice price={29} />: alsoclassName,localize,showDecimal,currencyDisplay('symbol' | 'code' | 'name'). Renders the base price when there is no discount.<PPPPriceFormatted price isOriginalDisplay? />(isOriginalDisplayshows the price before the discount),<PPPPriceInteger price />,<PPPPriceDecimal price />,<PPPCurrencySymbol />,<PPPCurrencyCode />. The last two follow the shown currency.<PPPPricingTable plans={[{ name, price, features, highlighted?, description?, ctaText?, planId? }]} />: alsobillingPeriod,annualDiscount,ctaText,onPlanSelect,showBillingToggle,className,noStyles,header,showCountryBanner.onPlanSelect(plan)receives the plan plusfinalPrice(the monthly price after the annual and PPP discounts, exact, in the base currency, never converted),localPrice(the price the table shows),currencyCode(the currency oflocalPrice) andbillingPeriod; the type is exported asPPPSelectedPlan. Charge or look up the plan withfinalPriceorplanId, never withlocalPrice. [packages/react-sdk/src/components/pricing-table.tsxPPPSelectedPlan]
Utilities: countryToFlag(code), formatCurrency(amount, currencyCode, intlOptions?), splitPrice(formatted), DEFAULT_API_BASE, VISITOR_ID_STORAGE_KEY.
Caching: sessionStorage key gpl_react_<key>_<productId> for 5 minutes, written only when show is true.
Server rendering: the provider has no PPP data on the server, so server HTML shows base prices. Discounted prices appear after the client fetch, or immediately from the session cache.
JS SDK: @gopaylocal/js
Section titled “JS SDK: @gopaylocal/js”[packages/js-sdk/src]
Install: npm install @gopaylocal/js. ESM and CommonJS builds.
Create the client: const gpl = new GoPayLocal({ apiKey }). Optional settings:
baseCurrencyCode: the currency of the prices you pass togetPrice(). Defaults to the product’s currency from the API (USDbefore the API answers or when no discount applies). Set to another currency, prices are not converted and the client logs one console warning.baseCurrencySymbol: defaults to the product’s symbol from the API, or the symbol ofbaseCurrencyCodein the visitor’s locale.apiBase(defaulthttps://api.gopaylocal.com)productIdvisitorIdpersistVisitorId(defaulttrue)cacheTtlin ms (default 300000;0always asks the API)onLoad(data): only when a discount appliesonError(error): also called for the timeout, with the message “GoPayLocal API did not respond within 8 seconds”
There is no environment option; passing it is a TypeScript error.
await gpl.init() returns PPPData or null: null when no discount applies, on error, or after the 8-second timeout. PPPData is { show, country, countryName, discount, code, baseCurrencyCode, baseCurrencySymbol, currencyCode, currencySymbol, fxRate, fxAsOf, localPrice, localOriginalPrice, charmPricingStrategy, flag, campaignId, experimentId, variant, banner, showBranding }. The price fields are the product’s own prices as the API computed them (fxAsOf is null and currencyCode is baseCurrencyCode when they are not converted).
Methods:
getData(),isLoading(),getError(),getCode()getExperiment():{ experimentId, variant }or null; set even wheninit()resolvednullgetCountry():{ code, name, flag }or nullgetPrice(basePrice, { localize?, showDecimal? })returns{ originalPrice, discountedPrice, localPrice, localOriginalPrice, converted, formatted, formattedOriginal, integer, decimal, currencySymbol, currencyCode, hasDiscount, discount }, with the same conversion, rounding and formatting rules as React’susePrice()formatPrice(amount, currencyCode?): formatsamountwithout converting it, by default in the currencygetPrice()shows prices insubscribe(listener): returns an unsubscribe functionbindPriceElements()showBanner(options?): returns{ remove }track(event)
Data attributes are filled only when you call gpl.bindPriceElements() after init() returned data. With no discount, elements keep their original text, so put the base price there.
data-gopaylocal-price="29": discounted price, formatted (getPrice().formatted)data-gopaylocal-price-original="29": original price, formatted, in the visitor’s currency when converteddata-gopaylocal-currency-symbol,data-gopaylocal-currency-code: the currency the prices are shown indata-gopaylocal-country(country name),data-gopaylocal-country-flagdata-gopaylocal-discount: rendered with a percent sign, e.g.40%data-gopaylocal-coupon
showBanner(options)
- Layers settings as SDK defaults, then the campaign’s design from the API, then
options. Options:position, colors,ctaText,messageTemplate,showFlag,showCloseBtn,onClose. - Sends
copy. - Does not remember dismissal.
Exports: GoPayLocal, formatCurrency, countryToFlag, splitPrice, DEFAULT_API_BASE, VISITOR_ID_STORAGE_KEY, and the types GoPayLocalConfig, PPPData, PricingResult, BannerOptions, BannerDesign, TrackableEvent and CharmStrategy.
Caching: sessionStorage key gpl_js2_<key>_<productId> for cacheTtl, only for responses with a discount.
Template tokens
Section titled “Template tokens”Tokens in the banner design’s messageTemplate, or in the JS SDK’s showBanner({ messageTemplate }). New campaigns use the default template below. Unknown tokens become an empty string everywhere.
The banner script, React <PPPBanner> and the JS SDK’s showBanner() fill the same tokens with the same values [packages/js-sdk/src/core.ts templateValues]:
| Token | Value |
|---|---|
{{discount}} |
Number only, e.g. 40. Write {{discount}}%. |
{{code}} |
Coupon code; empty if none |
{{country}} |
ISO code, e.g. IN (not the name) |
{{countryName}} |
e.g. India |
{{flag}} |
Flag emoji |
{{localPrice}} |
The product’s price after the discount, formatted in the visitor’s locale, e.g. ₹1,249 (converted) or $7.60 (not converted). Whole amounts show no decimals |
{{localOriginalPrice}} |
The product’s price before the discount, formatted the same way, e.g. ₹1,769 |
{{currencySymbol}} |
Symbol of the currency those prices are in: the visitor’s when converted, otherwise the product’s |
{{currencyCode}} |
Code of that currency, e.g. INR |
These are the product’s own prices from the response, whatever baseCurrencyCode is set to. Local prices are estimates; don’t present them as the amount charged.
- Banner script: HTML in the template is escaped and shown as text, and
**bold**is not interpreted (the asterisks show). Thediscountandcodevalues are bolded. - JS SDK:
**text**renders bold. React: plain text. - Default template for new campaigns [packages/shared/src/constants/index.ts
DEFAULT_BANNER_MESSAGE]:It looks like you're visiting from {{country}}! Use code {{code}} for {{discount}}% off.It shows the ISO code, not the country name.
Events endpoint
Section titled “Events endpoint”Only needed for a banner you build yourself, and the SDKs’ track(event) already does it. POST /v1/events, with a JSON body that may be sent as text/plain. [apps/api/src/routes/analytics-ingest.ts]
- Single event:
{ "key", "event", "campaignId", "countryCode", "url"?, "code"? }, whereeventisclickorcopy. - Batch:
{ "key", "events": [{ "eventType", "campaignId", "countryCode", "couponId"?, "pageUrl"?, "discountPercent"? }] }, 1 to 50 events. - Take
campaignIdandcountryfrom the config response. - Responses:
204for any payload that matches one of the two shapes.400when the body matches neither shape.401for an unknown key.429when rate limited.
- What gets dropped silently, still with
204:- events without
campaignIdandcountryCode - events whose campaign belongs to another account
impression, which is accepted but not counted, because the API counts impressions itself when it serves an offerdismiss, which is accepted but not countedredemption, which is accepted but never stored, because redemptions are recorded only from payment-provider webhooks. Don’t send it.
- events without
Common mistakes
Section titled “Common mistakes”- Putting the key in a
data-keyattribute. It must be the?key=query parameter of the script URL. - Writing
{{discount}} offand expecting a percent sign.{{discount}}is the number only; write{{discount}}% off. - Using
**bold**in a template shown by the banner script; the asterisks appear literally. - Using
{{country}}and expecting the country name; use{{countryName}}. - Calling the config endpoint from server code to render prices. There is no server-side pricing API.
- Concluding the integration is broken because no banner shows on a developer machine. High-income countries, VPNs, corporate proxies and cloud machines get no discount. Check that the config request returns HTTP 200 JSON:
show: falsewith areasonmeans the wiring works. To see the banner, the human can temporarily give their own country a discount in the dashboard campaign. - Allowed domains set on the campaign without the development host, which gives
domain_not_allowedlocally. - Adding both the banner script and
<PPPBanner />, which shows two banners. - Passing
onLoad,onErrororonPlanSelectfrom a Next.js Server Component. Rendering the provider there is fine; callbacks need your own'use client'file. - Presenting
localPriceas the amount charged. It is an estimate; the payment provider charges the exact discounted price in the product’s currency. - Setting
baseCurrencyCodeto a currency other than the product’s. Leave it unset when your prices are in the product’s currency; another value turns conversion off and logs a console warning. - Forgetting
bindPriceElements()afterinit()in the JS SDK. - Retesting right after a dashboard change in the same tab. The API usually serves a change everywhere within about a minute (in the worst case, about 16 minutes), clients cache the config in
sessionStoragefor 5 minutes, and a dismissed script banner stays hidden for the session. Clear thegpl_c_*,gpl_d_*,gpl_react_*andgpl_js2_*keys, or use a new private window. - Using a secret key (
gpl_sk_…) or inventing a key. The banner endpoints refuse a secret key (secret_key_not_allowed). Ask the human for the public key. - Trying to fake the country with a query parameter or header. Not supported; the country comes from Cloudflare only.
- Several products and no product id: the API answers for the product of the newest servable campaign. Pass
data-productorproductIdon pages that belong to a specific product. - Trying to change the campaign’s banner text or colors yourself, through GoPayLocal’s API or by editing the response. The campaign’s design is the human’s to change, on the campaign page under Setup > Banner. To change the look from site code, use
<PPPBanner />props orshowBanner()options, or build a custom banner and report events withtrack(). - Passing
environmentto an SDK, or using a sandbox API host. Neither exists. - Building an A/B split in page code, for example random discounts, two keys or alternating campaigns. The human starts the test in the dashboard and the API assigns the arm.
- Promising per-country A/B tests or results, a significance or lift figure, or a no-discount control arm. None exists; results are raw counts and rates per arm.
Source map
Section titled “Source map”- Config endpoint,
script.js,bundle.js:apps/api/src/routes/banner-script.ts - Campaign and experiment selection, arm assignment:
apps/api/src/services/banner-selection.ts - A/B test rules and results:
apps/api/src/services/experiment.service.ts - Events endpoint:
apps/api/src/routes/analytics-ingest.ts - Banner bundle:
packages/banner/src/index.ts,packages/banner/src/setup.ts - Request, visitor id and event helpers shared by all three clients:
packages/js-sdk/src/core.ts - JS SDK:
packages/js-sdk/src(client.ts,banner.ts,types.ts) - React SDK:
packages/react-sdk/src(provider.tsx,types.ts,hooks/,components/) - Shared types and defaults:
packages/shared/src/types/index.ts,packages/shared/src/constants/index.ts