marketin-js
v1.0.1
Published
MarketIn SDK for affiliate and conversion tracking.
Downloads
23
Maintainers
Readme
MarketIn JavaScript SDK
A lightweight browser SDK for tracking affiliate activity, page views, and conversions with the MarketIn platform.
Installation options
CDN (recommended for quick embeds)
<script src="https://cdn.jsdelivr.net/gh/ayg3/sdk@latest/marketin-sdk.min.js"></script>
<script type="module">
import { initMarketIn, trackConversion, trackPageView } from 'marketin-js'
async function bootstrap() {
await initMarketIn({
brandId: 'YOUR_BRAND_ID',
apiEndpoint: 'https://api.marketin.now/api/v1',
debug: true
})
trackPageView()
}
bootstrap()
</script>Important: The CDN script populates
window.MarketIn. Load it before calling any helper exported by this package. The helpers pollwindow.MarketInand no-op safely while waiting, but they can only work once the global SDK is available.
NPM package (bundler usage)
npm install marketin-jsAdd the CDN <script> tag to your host page (or bundle the script yourself) and then import the helpers in your app:
import { initMarketIn, handleTrackConversion, handleSubscriptionSubmit, trackPageView } from 'marketin-js'
// Ensure the CDN script has run and window.MarketIn exists
await initMarketIn({ brandId: 'YOUR_BRAND_ID' })
trackPageView()Initialization
Call initMarketIn once after the DOM has loaded:
await initMarketIn({
brandId: 'acme-123',
apiEndpoint: 'https://api.marketin.now/api/v1',
debug: false,
campaignId: 'cmp_789',
affiliateId: 'aff_456'
})brandId(required): Provided by MarketIn.apiEndpoint: Override for non-production environments.debug: Enables verbose console logging whentrue.campaignId/affiliateId: Optional defaults if your page doesn’t include query params like?aid=or?cid=.
The underlying SDK automatically:
- Generates a session ID if none exists.
- Reads URL query parameters (
aid,cid,pid, UTM tags, etc.). - Invokes
trackPageViewon init. - Persists click identifiers in cookies for de-duplication.
React / SPA example (Vite, CRA, Next.js)
For single-page apps, call initMarketIn inside a useEffect and preserve the attribution params across client-side navigation:
import { useEffect } from 'react'
import { initMarketIn } from 'marketin-js'
export function App() {
useEffect(() => {
const bootstrap = async () => {
await initMarketIn({
brandId: import.meta.env.VITE_MARKETIN_BRAND_ID ?? 1,
apiEndpoint: 'https://api.marketin.now/api/v1',
debug: true,
})
}
if (typeof window !== 'undefined') {
bootstrap().catch((error) => {
console.error('MarketIn init failed', error)
})
const { search, pathname } = window.location
const params = new URLSearchParams(search)
if (params.get('aid') || params.get('cid') || params.get('pid')) {
sessionStorage.setItem('marketinParams', search)
}
const savedParams = sessionStorage.getItem('marketinParams')
if (!search && savedParams) {
window.history.replaceState({}, '', `${pathname}${savedParams}`)
}
}
return undefined
}, [])
return <YourRoutes />
}- The CDN script must still run (e.g., added to
index.html) so thatwindow.MarketInexists before this effect executes. - Attribution params (
aid,cid,pid) are cached insessionStorageand replayed after client-side route changes, ensuring conversions remain tied to the correct affiliate/campaign.
Tracking helpers
trackPageView(options?)
Logs a page view with optional overrides (url, referrer, campaignId, etc.). Defaults are derived from the browser environment and any query parameters present.
trackConversion(payload)
Posts purchase or subscription conversions to MarketIn using whatever billing data you collect on the client.
Prerequisites:
initMarketIn(orMarketIn.init) must have already hydratedcampaignIdandaffiliateId. If either is missing, the SDK skips the request and logsConversion skipped.
One-off purchases (Paystack/Stripe success handlers)
import { trackConversion } from 'marketin-js'
trackConversion({
eventType: 'purchase', // any string not starting with "subscription"
productId: 'plan-premium', // required for non-subscription events
value: paystackResponse.amount, // numeric order total
currency: paystackResponse.currency,
conversionRef: paystackResponse.reference, // stable per transaction for de-dupe
metadata: { paymentProvider: 'paystack' }
})productIdmust be supplied for purchases or the call aborts.- Supply the billing provider's charge/transaction ID as
conversionRefso retries stay idempotent. The SDK also stores this underlocalStoragekeymi_conv_<sessionId>_<eventType>to suppress duplicates. - The payload automatically includes the current session, campaign, and affiliate IDs captured during initialization or via
trackAffiliateClick.
Subscriptions (renewals, upgrades, cancellations)
import { trackConversion } from 'marketin-js'
trackConversion({
eventType: 'subscription_renewed', // must start with "subscription"
subscriptionId: stripeSubscription.id,
periodNumber: stripeInvoice.current_period,
planId: stripeSubscription.plan?.id,
interval: stripeSubscription.items.data[0]?.plan?.interval,
recurringAmount: stripeInvoice.amount_paid,
currency: stripeInvoice.currency,
subscriptionStatus: stripeSubscription.status,
conversionRef: stripeInvoice.id,
metadata: { paymentProvider: 'stripe' }
})- When
eventTypebegins withsubscription,productIdbecomes optional; subscription context is forwarded inpayload.metadataalong with any extra fields you provide. - You can attach
planId,interval,periodNumber, or custommetadata—everything is forwarded to MarketIn unchanged.
Client-only flow: These helpers rely on the browser environment (
window,localStorage, cookies). Invoke them from the same client session that captured the affiliate click. Server-side webhooks should use a dedicated server integration instead.
handleTrackConversion(payload)
High-level helper for conversions:
handleTrackConversion({
productId: 'prod-123',
value: 199.99,
currency: 'USD',
conversionRef: 'order-456'
})For subscription flows:
handleTrackConversion({
eventType: 'subscription_renewed',
recurringAmount: 49.99,
currency: 'USD',
subscriptionId: 'sub-789',
planId: 'plan-monthly',
interval: 'month',
periodNumber: 2
})handleSubscriptionSubmit(event)
Drop-in form handler for subscription conversions:
<form id="subscription" onsubmit="return false;">
<input name="eventType" value="subscription_started" />
<input name="recurringAmount" value="29.99" />
<button type="submit">Subscribe</button>
</form>
<script type="module">
import { handleSubscriptionSubmit } from 'marketin-js'
document
.getElementById('subscription')
?.addEventListener('submit', (event) => {
const payload = handleSubscriptionSubmit(event)
console.log('Tracked subscription', payload)
})
</script>The helper extracts form fields into a structured payload, calls handleTrackConversion, and returns the sanitized data.
Diagnostic utilities
onMarketInEvent(listener)– subscribe to internal SDK events (init,track_page_view,track_conversion, etc.).isMarketInReady()– check whether the global SDK is available.crawlPageData()– scrape meta/product tags from the page and forward them to MarketIn.
Browser requirements & SSR
- This SDK relies on browser globals (
window,document,fetch,localStorage). Guard any server-side rendering hooks by checkingtypeof window !== 'undefined'. - The helpers no-op gracefully when the SDK is unavailable, but you should still ensure the CDN script runs before invoking tracking functions.
Development scripts
npm install
npm run buildnpm run build uses tsup to bundle ESM + CJS outputs with TypeScript definitions under dist/.
Need help integrating? Contact the MarketIn team or open an issue on the repository.
