@gatevector/browser-sdk
v0.2.1
Published
Browser extension payment SDK for GateVector - Accept payments in Chrome/Firefox extensions
Maintainers
Readme
@gatevector/browser-sdk
Official Browser Extension SDK for GateVector - Accept payments in your Chrome/Firefox extensions.
Installation
npm install @gatevector/browser-sdkQuick Start
1. Initialize the SDK
import { GateVector } from '@gatevector/browser-sdk';
const gateVector = new GateVector({
apiBaseUrl: 'https://api.gatevector.com',
apiKey: 'your-api-key-here'
});2. Create a One-Time Payment
// In your extension's popup or options page
async function handleUpgrade() {
await gateVector.openPaymentPage({
amount: 9.99,
currency: 'usd',
mode: 'payment',
description: 'Premium Upgrade'
});
}3. Create a Subscription
async function handleSubscribe() {
await gateVector.openPaymentPage({
amount: 4.99,
currency: 'usd',
mode: 'subscription',
interval: 'month',
description: 'Premium Monthly Subscription'
});
}4. Check User Payment Status
async function checkUserStatus() {
try {
const status = await gateVector.getUserStatus();
if (status.paid) {
console.log('User has paid!');
enablePremiumFeatures();
} else {
console.log('User has not paid');
showUpgradePrompt();
}
} catch (error) {
console.error('Failed to check status:', error);
}
}5. Handle Payment Success
// In your success page (success.html)
chrome.runtime.sendMessage({ type: 'payment-success' });
// In your background script
chrome.runtime.onMessage.addListener((message) => {
if (message.type === 'payment-success') {
extensionPay.clearCache();
checkUserStatus();
}
});API Reference
Constructor
new ExtensionPay(config: ExtensionPayConfig)Parameters:
config.apiBaseUrl(string): Base URL of your ExtensionPay instanceconfig.apiKey(string): Your organization's API key
Methods
createPaymentSession(options: PaymentSessionOptions): Promise<PaymentSession>
Creates a Stripe Checkout session and returns the session URL.
Options:
amount(number, required): Payment amount (e.g., 9.99)currency(string, optional): Currency code (default: 'usd')mode('payment' | 'subscription', optional): Payment mode (default: 'payment')successUrl(string, optional): Redirect URL after successful paymentcancelUrl(string, optional): Redirect URL after cancelled paymentdescription(string, optional): Payment descriptionlocale(string, optional): Checkout page locale (default: 'auto')priceId(string, optional): Stripe Price ID for subscriptionsinterval('day' | 'week' | 'month' | 'year', optional): Subscription intervalintervalCount(number, optional): Interval count (e.g., 3 for every 3 months)
Returns:
{
url: string; // Stripe Checkout URL
session_id?: string; // Checkout session ID
}openPaymentPage(options: PaymentSessionOptions): Promise<void>
Creates a payment session and opens it in a new tab (Chrome) or window.
getUserStatus(userId?: string): Promise<UserStatus>
Checks if a user has paid. Results are cached for 60 seconds.
Parameters:
userId(string, optional): User identifier (if not provided, uses default)
Returns:
{
paid: boolean;
customer_id?: string;
subscription_id?: string;
subscription_status?: string;
subscription_cancel_at_period_end?: boolean;
}confirmPayment(sessionId: string): Promise<{ status: string }>
Confirms a payment after checkout (hybrid safety net).
clearCache(userId?: string): void
Clears the user status cache. Call this after successful payments.
setApiKey(apiKey: string): void
Updates the API key and clears cache.
setApiBaseUrl(apiBaseUrl: string): void
Updates the base URL and clears cache.
Manifest Configuration
Chrome Extension (Manifest V3)
{
"manifest_version": 3,
"name": "Your Extension",
"permissions": [
"tabs"
],
"host_permissions": [
"https://api.extensionpay.io/*"
]
}Firefox Add-on (Manifest V2)
{
"manifest_version": 2,
"name": "Your Extension",
"permissions": [
"tabs",
"https://api.extensionpay.io/*"
]
}Complete Example
background.js (Service Worker)
import ExtensionPay from '@extensionpay/browser-sdk';
const extensionPay = new ExtensionPay({
apiBaseUrl: 'https://api.extensionpay.io',
apiKey: 'your-api-key'
});
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.type === 'check-status') {
extensionPay.getUserStatus()
.then(status => sendResponse({ paid: status.paid }))
.catch(error => sendResponse({ error: error.message }));
return true;
}
if (message.type === 'upgrade') {
extensionPay.openPaymentPage({
amount: 9.99,
mode: 'payment',
description: 'Premium Upgrade'
}).catch(error => console.error(error));
}
if (message.type === 'payment-success') {
extensionPay.clearCache();
chrome.storage.local.set({ premium: true });
}
});popup.html + popup.js
document.getElementById('upgrade-btn').addEventListener('click', async () => {
chrome.runtime.sendMessage({ type: 'upgrade' });
});
chrome.runtime.sendMessage({ type: 'check-status' }, (response) => {
if (response.paid) {
document.getElementById('status').textContent = 'Premium Active';
}
});success.html
<!DOCTYPE html>
<html>
<head>
<title>Payment Success</title>
</head>
<body>
<h1>Payment Successful!</h1>
<p>Thank you for upgrading to Premium.</p>
<script>
chrome.runtime.sendMessage({ type: 'payment-success' });
setTimeout(() => window.close(), 2000);
</script>
</body>
</html>Best Practices
Cache User Status: The SDK automatically caches user status for 60 seconds. Don't call
getUserStatus()on every page load.Clear Cache After Payment: Always call
clearCache()after successful payments to ensure fresh status.Handle Errors: Wrap API calls in try-catch blocks and handle network errors gracefully.
Store Premium State: After confirming payment, store premium status in
chrome.storagefor offline access.Test in Development: Use test API keys and test mode in Stripe during development.
Support
- Documentation: https://docs.extensionpay.io
- Issues: https://github.com/xgame92/extensionpay-io-v2/issues
License
MIT
