@vesvank/ramblay-js
v0.1.0
Published
Ramblay javascript SDK for embedding payment forms
Downloads
18
Maintainers
Readme
Ramblay SDK
Official JavaScript SDK for Ramblay payment integration. Easily embed secure payment forms in your web application.
Features
- Secure - Isolated iframe with origin validation and secure postMessage communication
- Lightweight - Only ~2KB gzipped
- TypeScript - Full type definitions included
- Simple API - Stripe-inspired, minimal developer experience
- Zero Dependencies - No external dependencies
- Universal - Works with any JavaScript framework or vanilla JS
- Auto Redirect - Automatic redirect to success URL when configured
Installation
Via npm
npm install @vesvank/ramblay-jsVia CDN
<script src="https://unpkg.com/@vesvank/ramblay-js@latest/dist/ramblay.min.js"></script>Quick Start
// 1. Initialize the SDK with your publishable key
const ramblay = new Ramblay('pk_live_your_key_here');
// 2. Create a payframes instance with the client secret
const payframes = ramblay.payframes({
clientSecret: 'pf_xxxx_secret_xxxx', // Get this from your backend
});
// 3. Create and mount the embedded payframe
const embedded = payframes.createEmbedded();
// 4. Handle events
embedded.on('ready', () => {
console.log('Payment form is ready');
});
embedded.on('success', () => {
console.log('Payment successful!');
// If success_url was configured, the page will auto-redirect
// Otherwise, fetch payment details from your backend
});
embedded.mount('#payframe-container');API Reference
Ramblay
Initialize the SDK with your publishable API key.
const ramblay = new Ramblay(publishableKey: string, options?: RamblayOptions);Parameters:
publishableKey(required): Your Ramblay publishable API key (starts withpk_)options(optional): Configuration optionsbaseUrl(optional): Custom base URL for the Ramblay API (default:'https://ramblay.com')
Example:
const ramblay = new Ramblay('pk_live_abc123');ramblay.payframes()
Create a Payframes instance for managing payment forms.
const payframes = ramblay.payframes(options: PayframesOptions);Parameters:
options(required):clientSecret(required): The client secret obtained from your backend (format:pf_..._secret_...)
Example:
const payframes = ramblay.payframes({
clientSecret: 'pf_xxxx_secret_xxxx',
});payframes.createEmbedded()
Create an embedded payframe element.
const embedded = payframes.createEmbedded(options?: EmbeddedPayframeOptions);Parameters:
options(optional): Configuration options (reserved for future use)
Returns: EmbeddedPayframe instance
Example:
const embedded = payframes.createEmbedded();embedded.mount()
Mount the payframe to a DOM element.
embedded.mount(selector: string | HTMLElement): voidParameters:
selector: CSS selector string or HTMLElement reference
Example:
// Mount using CSS selector
embedded.mount('#payframe-container');
// Mount using element reference
const container = document.getElementById('payframe-container');
embedded.mount(container);embedded.unmount()
Unmount the payframe from the DOM.
embedded.unmount(): voidExample:
embedded.unmount();embedded.destroy()
Destroy the payframe and clean up all resources.
embedded.destroy(): voidExample:
embedded.destroy();embedded.on()
Subscribe to payframe events.
embedded.on(event: EventType, handler: EventHandler): voidEvents:
ready
Emitted when the payframe iframe has loaded and is ready to accept input. Use this to hide loading indicators.
embedded.on('ready', () => {
document.getElementById('loading').style.display = 'none';
});success
Emitted when a payment is successfully completed.
embedded.on('success', () => {
console.log('Payment completed!');
// Fetch payment details from your backend if needed
});Note: The success event does not include payment details. For security, always fetch payment information from your backend using webhooks or API calls.
Auto-redirect: If you configured a success_url when creating the payframe on your backend, the SDK will automatically redirect the user to that URL upon successful payment. In this case, the success event handler may not execute as the page navigates away.
embedded.off()
Unsubscribe from payframe events.
embedded.off(event: EventType, handler: EventHandler): voidExample:
const successHandler = () => console.log('Success!');
embedded.on('success', successHandler);
// Later, remove the listener
embedded.off('success', successHandler);TypeScript Support
The SDK is written in TypeScript and includes full type definitions.
import Ramblay, { ReadyEvent, SuccessEvent, EmbeddedPayframe } from '@vesvank/ramblay-js';
const ramblay = new Ramblay('pk_live_abc123');
const payframes = ramblay.payframes({ clientSecret: 'pf_xxxx_secret_xxxx' });
const embedded: EmbeddedPayframe = payframes.createEmbedded();
embedded.on('ready', (event: ReadyEvent) => {
console.log('Payframe is ready');
});
embedded.on('success', (event: SuccessEvent) => {
console.log('Payment completed');
});
embedded.mount('#payframe-container');Security
Secure iframe Communication
The SDK loads payment forms in an isolated iframe with credentials passed via query parameters:
- Isolated iframe context - Payment form runs in separate origin for security
- Origin validation - All postMessage events are validated against expected origin
- Minimal event exposure - Only
readyandsuccessevents are exposed to your code - No sensitive data in events - Payment details should be fetched from your backend
- Auto-redirect support - Success URL redirects happen automatically within the SDK
How it works:
- SDK creates iframe with URL:
/pay/embed?publishable_key=pk_xxx&client_secret=pf_xxx_secret_xxx - Iframe loads the Ramblay-hosted payment form
- User completes payment in isolated iframe
- Iframe sends result via postMessage to parent
- SDK validates message origin and:
- If
success_urlwas configured: automatically redirects the user - Otherwise: emits
successevent to your handler
- If
Best Practices
- Never expose secret keys - Only use publishable keys (starting with
pk_) in your frontend code - Create payframes on your backend - Call the Ramblay API from your server to create payframes and obtain the
client_secret - Validate on the backend - Always verify payments on your backend using webhooks
- Use HTTPS - Always serve your application over HTTPS in production
- Configure success_url - For the best UX, configure a
success_urlwhen creating the payframe to enable automatic redirects
Error Handling
Errors during payment (card declined, network issues, etc.) are handled internally by the embedded iframe. The iframe displays appropriate error messages to the user and allows them to retry.
For initialization errors, use try-catch:
try {
const ramblay = new Ramblay('pk_live_abc123');
const payframes = ramblay.payframes({ clientSecret: 'pf_xxxx_secret_xxxx' });
const embedded = payframes.createEmbedded();
embedded.mount('#payframe-container');
} catch (error) {
if (error.code === 'invalid_key') {
console.error('Invalid publishable key');
} else if (error.code === 'container_not_found') {
console.error('Container element not found');
} else {
console.error('Initialization error:', error.message);
}
}Browser Support
The SDK supports modern browsers with ES2017+ features:
- Chrome 60+
- Firefox 55+
- Safari 11+
- Edge 79+
Not supported: Internet Explorer 11
Backend Integration
Creating a Payframe
Example backend endpoint to create a payframe:
// Node.js/Express example
app.post('/api/create-payframe', async (req, res) => {
try {
const response = await fetch('https://ramblay.com/api/payframes', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${process.env.RAMBLAY_SECRET_KEY}`,
},
body: JSON.stringify({
success_url: 'https://yourapp.com/success', // Auto-redirect on success
cancel_url: 'https://yourapp.com/cancel',
expires_in: 3600,
display_mode: 'embedded',
payment_method_types: ['c2p', 'card'],
line_items: [
{
inline_price: {
unit_amount: req.body.amount,
product: {
name: req.body.product_name,
description: req.body.product_description,
},
},
quantity: 1,
},
],
}),
});
const data = await response.json();
// Return only the client_secret to the frontend
res.json({ client_secret: data.client_secret });
} catch (error) {
res.status(500).json({ error: error.message });
}
});Understanding the Payment Flow
When you mount an embedded payframe, the SDK creates an iframe that loads the Ramblay-hosted payment form:
URL Format:
https://ramblay.com/pay/embed?publishable_key=pk_xxx&client_secret=pf_xxx_secret_xxxImportant: The /pay/embed endpoint is hosted by Ramblay, not by you. You don't need to implement this endpoint.
Your backend responsibilities:
- Create a payframe via the Ramblay API (see "Creating a Payframe" section above)
- Return the
client_secretto your frontend - Handle webhook events for payment confirmation
The embedded iframe:
- Is hosted at Ramblay's domain
- Renders the secure payment form
- Handles payment processing and error display
- Sends events back to your page via postMessage
- Automatically redirects if
success_urlwas configured
Examples
Check out the examples directory for complete working examples:
- Vanilla JavaScript - Basic integration example
Running Examples
To see the SDK in action, you can run the included example:
Quick Start
# Install dependencies (if not already done)
npm install
# Run the example (opens browser automatically)
npm run exampleThe example will open at http://localhost:8080/examples/vanilla/index.html
Manual Setup
If you prefer to run without auto-opening the browser:
npm run example:no-openThen manually navigate to: http://localhost:8080/examples/vanilla/index.html
What You'll See
The example demonstrates:
- Initializing the SDK with a test publishable key
- Creating and mounting an embedded payframe
- Handling payment events (
readyandsuccess) - Real-time event logging
- Interactive controls (load/unmount)
Note: This is a demo using test credentials. For a fully functional example with real payment processing, you'll need to use your actual Ramblay credentials.
Development
# Install dependencies
npm install
# Build the SDK
npm run build
# Watch mode (auto-rebuild on changes)
npm run build:watch
# Run the example to test your changes
npm run example
# Run tests
npm test
# Run type checking
npm run typecheck
# Lint code
npm run lintContinuous Integration: The project uses GitHub Actions for CI. On every push and PR, the following checks run:
- Type checking
- Linting
- Tests with coverage
- Build verification
- Matrix testing on Node 18.x and 20.x
Coverage reports are uploaded to Codecov (when configured).
Contributing
Contributions are welcome! Please read our Contributing Guide for details on:
- Development workflow and setup
- Commit message guidelines (we use Conventional Commits for automated releases)
- Versioning policy and release process
Quick start:
- Fork the repository
- Create a feature branch
- Make your changes with tests
- Write commits following Conventional Commits format (enforced by commitlint)
- Ensure all CI checks pass (type checking, linting, tests)
- Submit a Pull Request
All PRs are automatically tested via GitHub Actions. Releases are automated when PRs are merged to main.
License
MIT © Ramblay
Support
- Documentation: https://ramblay.com/docs
- GitHub Issues: https://github.com/vesvank/ramblay-js/issues
- Email: [email protected]
Changelog
See CHANGELOG.md for version history and release notes.
