Code Examples
Ready-to-use code examples for integrating PYMSTR into your application. Examples available in JavaScript, Python, PHP, and cURL.
💡 Tip: Replace YOUR_API_KEY with your actual API key from the PYMSTR dashboard.
Create Payment Link
Create a new single-use payment link for your customer.
// Node.js with fetch
const createPaymentLink = async () => {
const response = await fetch('https://api.pymstr.com/v1/payment-links', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_API_KEY'
},
body: JSON.stringify({
price: 50.00,
currency: 'USDC',
chain: 'Polygon',
description: 'Monthly Subscription',
metadata: {
userId: 'user_123',
planId: 'basic_monthly'
}
})
});
const data = await response.json();
console.log('Payment URL:', data.url);
// Redirect customer to payment page
window.location.href = data.url;
};
import requests
def create_payment_link():
url = 'https://api.pymstr.com/v1/payment-links'
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_API_KEY'
}
payload = {
'price': 50.00,
'currency': 'USDC',
'chain': 'Polygon',
'description': 'Monthly Subscription',
'metadata': {
'userId': 'user_123',
'planId': 'basic_monthly'
}
}
response = requests.post(url, json=payload, headers=headers)
data = response.json()
print(f"Payment URL: {data['url']}")
return data['url']
50.00,
'currency' => 'USDC',
'chain' => 'Polygon',
'description' => 'Monthly Subscription',
'metadata' => array(
'userId' => 'user_123',
'planId' => 'basic_monthly'
)
);
$options = array(
'http' => array(
'method' => 'POST',
'header' => "Content-Type: application/json\r\n" .
"Authorization: Bearer YOUR_API_KEY\r\n",
'content' => json_encode($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
$response = json_decode($result, true);
echo "Payment URL: " . $response['url'];
return $response['url'];
}
?>
curl -X POST https://api.pymstr.com/v1/payment-links \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"price": 50.00,
"currency": "USDC",
"chain": "Polygon",
"description": "Monthly Subscription",
"metadata": {
"userId": "user_123",
"planId": "basic_monthly"
}
}'
Verify Payment Status
Check if a payment link has been completed and retrieve the transaction hash.
const verifyPayment = async (linkId) => {
const response = await fetch(`https://api.pymstr.com/v1/payment-links/${linkId}`, {
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
});
const payment = await response.json();
if (payment.status === 'completed') {
console.log('Payment confirmed!');
console.log('Transaction hash:', payment.txHash);
console.log('Completed at:', payment.completedAt);
// Process the order, grant access, etc.
return true;
} else {
console.log('Payment status:', payment.status);
return false;
}
};
import requests
def verify_payment(link_id):
url = f'https://api.pymstr.com/v1/payment-links/{link_id}'
headers = {
'Authorization': 'Bearer YOUR_API_KEY'
}
response = requests.get(url, headers=headers)
payment = response.json()
if payment['status'] == 'completed':
print('Payment confirmed!')
print(f"Transaction hash: {payment['txHash']}")
print(f"Completed at: {payment['completedAt']}")
return True
else:
print(f"Payment status: {payment['status']}")
return False
array(
'method' => 'GET',
'header' => "Authorization: Bearer YOUR_API_KEY\r\n"
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
$payment = json_decode($result, true);
if ($payment['status'] === 'completed') {
echo "Payment confirmed!\n";
echo "Transaction hash: " . $payment['txHash'] . "\n";
echo "Completed at: " . $payment['completedAt'] . "\n";
return true;
} else {
echo "Payment status: " . $payment['status'] . "\n";
return false;
}
}
?>
curl -X GET https://api.pymstr.com/v1/payment-links/PL_abc123 \
-H "Authorization: Bearer YOUR_API_KEY"
Webhook Handler
Handle incoming webhook notifications when payments are completed.
// Express.js webhook endpoint
app.post('/webhooks/pymstr', express.json(), (req, res) => {
const event = req.body;
// Verify webhook signature (recommended)
// const signature = req.headers['x-pymstr-signature'];
// if (!verifyWebhookSignature(req.body, signature)) {
// return res.status(401).send('Invalid signature');
// }
switch (event.event) {
case 'payment.completed':
console.log('Payment completed:', event.linkId);
console.log('Transaction hash:', event.txHash);
console.log('Price:', event.price, event.currency);
// Process the payment
// Grant user access, update database, etc.
processCompletedPayment(event);
break;
case 'payment.expired':
console.log('Payment expired:', event.linkId);
// Handle expired payment
break;
}
// Respond with 200 to acknowledge receipt
res.status(200).send('Webhook received');
});
# Flask webhook endpoint
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/webhooks/pymstr', methods=['POST'])
def webhook_handler():
event = request.json
# Verify webhook signature (recommended)
# signature = request.headers.get('X-Pymstr-Signature')
# if not verify_webhook_signature(request.data, signature):
# return jsonify({'error': 'Invalid signature'}), 401
if event['event'] == 'payment.completed':
print(f"Payment completed: {event['linkId']}")
print(f"Transaction hash: {event['txHash']}")
print(f"Price: {event['price']} {event['currency']}")
# Process the payment
process_completed_payment(event)
elif event['event'] == 'payment.expired':
print(f"Payment expired: {event['linkId']}")
# Handle expired payment
# Respond with 200 to acknowledge receipt
return jsonify({'status': 'success'}), 200
'success']);
?>
List Payment Links
Retrieve a list of payment links with optional filtering.
const listPaymentLinks = async (status = null, source = null) => {
let url = 'https://api.pymstr.com/v1/payment-links?limit=50';
if (status) url += `&status=${status}`;
if (source) url += `&source=${source}`;
const response = await fetch(url, {
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
});
const data = await response.json();
console.log(`Found ${data.payments.length} payment links`);
data.payments.forEach(payment => {
console.log(`${payment.linkId}: ${payment.status} - ${payment.price} ${payment.currency}`);
});
return data.payments;
};
// Examples:
// listPaymentLinks('completed'); // Only completed payments
// listPaymentLinks(null, 'api'); // Only API-generated links
// listPaymentLinks('active', 'manual'); // Active manual links
import requests
def list_payment_links(status=None, source=None):
url = 'https://api.pymstr.com/v1/payment-links'
headers = {
'Authorization': 'Bearer YOUR_API_KEY'
}
params = {'limit': 50}
if status:
params['status'] = status
if source:
params['source'] = source
response = requests.get(url, headers=headers, params=params)
data = response.json()
print(f"Found {len(data['payments'])} payment links")
for payment in data['payments']:
print(f"{payment['linkId']}: {payment['status']} - {payment['price']} {payment['currency']}")
return data['payments']
# Examples:
# list_payment_links(status='completed')
# list_payment_links(source='api')
# list_payment_links(status='active', source='manual')
array(
'method' => 'GET',
'header' => "Authorization: Bearer YOUR_API_KEY\r\n"
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
$data = json_decode($result, true);
echo "Found " . count($data['payments']) . " payment links\n";
foreach ($data['payments'] as $payment) {
echo "{$payment['linkId']}: {$payment['status']} - {$payment['price']} {$payment['currency']}\n";
}
return $data['payments'];
}
// Examples:
// listPaymentLinks('completed');
// listPaymentLinks(null, 'api');
// listPaymentLinks('active', 'manual');
?>
# List all payment links
curl -X GET "https://api.pymstr.com/v1/payment-links?limit=50" \
-H "Authorization: Bearer YOUR_API_KEY"
# Filter by status
curl -X GET "https://api.pymstr.com/v1/payment-links?status=completed&limit=50" \
-H "Authorization: Bearer YOUR_API_KEY"
# Filter by source
curl -X GET "https://api.pymstr.com/v1/payment-links?source=api&limit=50" \
-H "Authorization: Bearer YOUR_API_KEY"
Next Steps
Ready to integrate PYMSTR? Check out these resources:
- Quick Start Guide - Step-by-step integration guide
- API Reference - Complete API documentation
- SDKs - Official client libraries (coming soon)
- Testing - Sandbox environment and test networks