Skip to main content

@martianpay/js Usage Guide

A comprehensive guide for integrating the MartianPay JavaScript SDK into your web applications for seamless payment processing.

Table of Contents

Installation

Install the package using your preferred package manager:

npm install @martianpay/js
# or
yarn add @martianpay/js
# or
pnpm add @martianpay/js

Basic Setup

1. Import the Library

import { loadMartian } from "@martianpay/js";

2. Initialize with Public API Key

const martian = await loadMartian(import.meta.env.VITE_PUBLIC_API_KEY);

Important Notes:

  • Use your public API key (not secret key) for frontend integrations
  • The public key is safe to use in client-side code and browsers
  • Store the public key in environment variables for better organization
  • Never use your secret API key in frontend JavaScript - it should only be used for backend API calls

Core Concepts

MartianPay Instance

The main entry point that provides access to payment functionality.

Payment Elements

UI components that handle payment form rendering and user interaction.

Payment Intent

A server-side object that tracks the payment state and amount.

API Reference

loadMartian(publicKey: string)

Initializes the MartianPay SDK instance.

Parameters:

  • publicKey (string): Your MartianPay public API key (not secret key)

Returns: Promise<MartianPayInstance | null>

Example:

const martian = await loadMartian("your_public_api_key_here");
if (!martian) {
throw new Error("Failed to initialize MartianPay");
}

Security Note: Always use your public API key for frontend integrations. Secret keys should only be used on the backend.

martian.retrievePaymentIntent(clientSecret: string)

Retrieves a payment intent using the client secret.

Parameters:

  • clientSecret (string): The client secret from your payment intent

Returns: Promise<void>

Example:

await martian.retrievePaymentIntent(intent.client_secret);

martian.elements()

Creates an elements factory for building payment UI components.

Returns: ElementsFactory

Example:

const elements = martian.elements();

elements.create()

Creates a payment element.

Returns: PaymentElement

Example:

const paymentElement = elements.create();

paymentElement.mount(selector: string)

Mounts the payment element to a DOM container.

Parameters:

  • selector (string): CSS selector for the container element

Example:

paymentElement.mount("#martian-container");

paymentElement.on(event: string, callback: Function)

Attaches event listeners to the payment element.

Parameters:

  • event (string): Event name (e.g., 'ready')
  • callback (Function): Event handler function

Example:

paymentElement.on("ready", () => {
console.log("Payment element is ready");
setLoading(false);
});

martian.confirmPayment(options: ConfirmPaymentOptions)

Initiates the payment confirmation process.

Parameters:

  • options (ConfirmPaymentOptions): Configuration object containing the payment element

Returns: Promise<PaymentResult>

Example:

const result = await martian.confirmPayment({ element: paymentElement });

Integration Examples

Complete Payment Flow

import { loadMartian } from "@martianpay/js";

const processPayment = async (clientSecret) => {
try {
// 1. Initialize MartianPay with public key
const martian = await loadMartian(import.meta.env.VITE_PUBLIC_API_KEY);
if (!martian) {
throw new Error("Failed to initialize payment system");
}

// 2. Retrieve payment intent
await martian.retrievePaymentIntent(clientSecret);

// 3. Create and mount payment element
const elements = martian.elements();
const paymentElement = elements.create();
paymentElement.mount("#martian-container");

// 4. Handle element ready state
paymentElement.on("ready", () => {
setLoading(false);
});

// 5. Confirm payment
const result = await martian.confirmPayment({ element: paymentElement });

if (result?.paymentIntent?.status === "Success") {
// Payment successful
setSuccess(true);
} else {
// Payment failed
setError("Payment failed. Please try again.");
}
} catch (error) {
handlePaymentError(error);
}
};

React Component Integration

import React, { useEffect, useState } from "react";
import { loadMartian } from "@martianpay/js";

const PaymentComponent = () => {
const [martian, setMartian] = useState(null);
const [loading, setLoading] = useState(false);

useEffect(() => {
const initMartian = async () => {
const instance = await loadMartian(import.meta.env.VITE_PUBLIC_API_KEY);
setMartian(instance);
};

initMartian();
}, []);

const handlePayment = async (clientSecret) => {
if (!martian) return;

setLoading(true);
try {
await martian.retrievePaymentIntent(clientSecret);
const elements = martian.elements();
const paymentElement = elements.create();
paymentElement.mount("#payment-container");

paymentElement.on("ready", () => setLoading(false));

const result = await martian.confirmPayment({ element: paymentElement });
// Handle result
} catch (error) {
console.error("Payment error:", error);
}
};

return (
<div>
{loading && <div>Processing payment...</div>}
<div id="payment-container"></div>
</div>
);
};

Error Handling

Common Error Types

const handlePaymentError = (error) => {
if (error.message?.includes("insufficient")) {
setError(
"Insufficient funds. Please check your account balance and try again."
);
} else if (error.message?.includes("declined")) {
setError(
"Payment was declined. Please check your payment method or try a different one."
);
} else if (error.message?.includes("expired")) {
setError("Payment session expired. Please refresh the page and try again.");
} else if (error.message?.includes("network")) {
setError(
"Network error during payment. Please check your connection and try again."
);
} else {
setError(
error.message ||
"Payment processing failed. Please try again or contact support."
);
}
};

Error Handling Best Practices

  1. Always wrap payment operations in try-catch blocks
  2. Provide user-friendly error messages
  3. Log errors for debugging purposes
  4. Implement retry mechanisms for transient failures

Best Practices

1. Environment Configuration

// Use environment variables for API keys
const PUBLIC_API_KEY = import.meta.env.VITE_PUBLIC_API_KEY;
const martian = await loadMartian(PUBLIC_API_KEY);

Note: Use your public API key for frontend integrations, not your secret key.

2. Loading States

const [martianLoading, setMartianLoading] = useState(false);

// Show loading indicator during payment processing
{
martianLoading && <LoadingBar text="Processing payment..." />;
}

3. Container Management

// Provide a dedicated container for the payment element
<div id="martian-container"></div>

4. Cleanup

useEffect(() => {
return () => {
// Cleanup payment elements when component unmounts
const container = document.getElementById("martian-container");
if (container) {
container.innerHTML = "";
}
};
}, []);

5. Payment Intent Management

// Always retrieve payment intent before creating elements
await martian.retrievePaymentIntent(clientSecret);

// Use the same client secret throughout the payment flow
const intent = response.data.payment_intent;

Troubleshooting

Common Issues

1. Payment Element Not Mounting

  • Ensure the container element exists in the DOM
  • Check that the container ID matches the mount selector
  • Verify the payment intent has been retrieved

2. API Key Errors

  • Verify you are using your public API key (not secret key)
  • Ensure the public key is correct and has the necessary permissions
  • Check that the key is properly set in environment variables
  • Remember: secret keys are for backend use only

3. Payment Confirmation Failures

  • Verify the payment element is ready before confirming
  • Check that the client secret is valid and not expired
  • Ensure sufficient funds are available

4. Network Issues

  • Check your internet connection
  • Verify API endpoints are accessible
  • Implement retry logic for transient failures

Debug Mode

Enable debug logging for troubleshooting:

// Add console logs for debugging
console.log("Martian instance:", martian);
console.log("Payment element:", paymentElement);
console.log("Payment result:", result);

TypeScript Support

The library includes TypeScript definitions. Key types include:

interface ConfirmPaymentOptions {
element: PaymentElement;
}

interface PaymentResult {
paymentIntent?: {
status: string;
// ... other properties
};
}

interface PaymentElement {
mount: (selector: string) => void;
on: (event: string, callback: Function) => void;
}

Browser Compatibility

  • Chrome 60+
  • Firefox 55+
  • Safari 12+
  • Edge 79+

Support

For additional support:

  • Check the official documentation
  • Review error logs and console output
  • Contact MartianPay support with specific error details

Note: This documentation is based on the implementation patterns found in the Demo page. For the most up-to-date information, refer to the official MartianPay documentation and API reference.