Crypto Payments
Overview
The Crypto Payment API is Shiba Inu's service to integrate payment with blockchain tokens in your application.
If you don't require assistance on how to connect to the Crypto Payment service and just need to check the API endpoints and parameters, you can head to the Swagger docs.
Integrate Crypto Payments in your Application
By following these steps and utilizing the provided code snippets, you can integrate the crypto payment API into your projects more efficiently. Adjust the code to fit your specific technology stack and application requirements.
1. Create a Merchant Account
Currently, merchants are being manually onboarded by the Shiba Inu's team. Use this form to apply for a Merchant's position.
2. Set Up a Payment Request Endpoint
Create a server-side route that handles payment requests from your application.
Action:
Implement an Endpoint: Create an endpoint (e.g., /create-payment-session) that your application will call to initiate a payment session. Accept Necessary Parameters: This endpoint should accept parameters like amount, currency, and any other relevant data.
// paymentRoute.js
const express = require('express');
const router = express.Router();
const axios = require('axios');
const savePaymentSession = require('./savePaymentSession');
// Replace with your actual API base URL
const API_BASE_URL = 'https://payments.shibinternal.com';
router.post('/create-payment-session', async (req, res) => {
const { amount, currency, description } = req.body;
try {
// Create a Payment Session via API
const response = await axios.post(`${API_BASE_URL}/api/payments/public/api/v1/session`, {
merchant_id: 'your_merchant_id', // Replace with your merchant ID
amount,
currency,
description,
}, {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
});
const { session_id, session_url } = response.data;
// Store Payment Session Data
await savePaymentSession({
sessionId: session_id,
sessionUrl: session_url,
amount,
currency,
status: 'pending',
});
// Send the session_url to the client
res.json({ session_url });
} catch (error) {
console.error('Error creating payment session:', error.response?.data || error.message);
res.status(500).send('Error creating payment session');
}
});
module.exports = router;
3. Create a Payment Session via API
Obtain a payment session that includes a unique URL for the user to complete the transaction.
Action:
Use the API Endpoint: Make a POST request to /api/payments/public/api/v1/session
to create a new payment session.
Provide Required Data: Include merchant_id, amount, currency, and description in the request body.
API Endpoint: POST https://payments.shibinternal.com/api/payments/public/api/v1/session
const response = await axios.post(`${API_BASE_URL}/api/payments/public/api/v1/session`, {
merchant_id: 'your_merchant_id',
amount,
currency,
description,
}, {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
});
4. Store Payment Session Data
Keep track of the payment session and its details for status updates and verification.
Action:
Save Session Details: Store session_id, session_url, amount, currency, status, and any other relevant details in your database.
// models/PaymentSession.js
const mongoose = require('mongoose');
const PaymentSessionSchema = new mongoose.Schema({
sessionId: String,
sessionUrl: String,
amount: Number,
currency: String,
status: String,
createdAt: { type: Date, default: Date.now },
});
module.exports = mongoose.model('PaymentSession', PaymentSessionSchema);
javascript
Copiar código
// savePaymentSession.js
const PaymentSession = require('./models/PaymentSession');
async function savePaymentSession(sessionData) {
const paymentSession = new PaymentSession(sessionData);
await paymentSession.save();
}
module.exports = savePaymentSession;
5. Redirect User to Payment Page
Direct the user to the payment interface to complete the transaction.
Action:
Send session_url to the Client: The client application uses this URL to open the payment page. Handle Different Platforms:
- Web Applications: Redirect or open the URL in a new tab/window.
- Mobile Applications: Use a WebView component to load the payment page.
res.json({ session_url });
// On receiving the session_url from the server
fetch('/create-payment-session', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ amount: 100, currency: 'USDT', description: 'Order #1234' }),
})
.then((response) => response.json())
.then((data) => {
window.location.href = data.session_url; // Redirect to payment page
})
.catch((error) => console.error('Error:', error));
6. Handle Payment Status Updates via Webhook
Receive real-time updates about the payment status from the Payment API.
Action:
Set Up a Webhook Endpoint: Create an endpoint (e.g., /payment-webhook) to receive POST requests from the Payment API. Update Payment Status: Update the payment session in your database based on the webhook payload.
type PostbackBody struct {
PaymentSessionID string `json:"payment_session_id"`
Status string `json:"status"`
Amount decimal.Decimal `json:"amount"`
Currency string `json:"currency"`
}
// webhook.js
const express = require('express');
const router = express.Router();
const PaymentSession = require('./models/PaymentSession');
router.post('/payment-webhook', async (req, res) => {
const { payment_session_id, status, amount, currency } = req.body;
try {
const paymentSession = await PaymentSession.findOne({ sessionId: payment_session_id });
if (paymentSession) {
paymentSession.status = status;
paymentSession.amount = amount;
paymentSession.currency = currency;
await paymentSession.save();
}
res.status(200).send('Webhook received');
} catch (error) {
console.error('Error handling webhook:', error.message);
res.status(500).send('Error handling webhook');
}
});
module.exports = router;
7. Implement Payment Status Checking
Allow the client application to check the current status of the payment.
Action:
Create a Status Endpoint: An endpoint (e.g., /payment-status/:sessionId) that returns the status of a payment session. Client Polling: The client can poll this endpoint periodically to get updates.
// statusRoute.js
const express = require('express');
const router = express.Router();
const PaymentSession = require('./models/PaymentSession');
router.get('/payment-status/:sessionId', async (req, res) => {
const { sessionId } = req.params;
try {
const paymentSession = await PaymentSession.findOne({ sessionId });
if (paymentSession) {
res.json({ status: paymentSession.status });
} else {
res.status(404).send('Payment session not found');
}
} catch (error) {
console.error('Error fetching payment status:', error.message);
res.status(500).send('Error fetching payment status');
}
});
module.exports = router;
function checkPaymentStatus(sessionId) {
fetch(`/payment-status/${sessionId}`)
.then((response) => response.json())
.then((data) => {
if (data.status === 'accepted') {
// Payment successful logic
alert('Payment successful!');
} else if (data.status === 'rejected' || data.status === 'abandoned') {
// Payment failed or abandoned logic
alert('Payment was not completed.');
} else {
// Payment is still pending
setTimeout(() => checkPaymentStatus(sessionId), 5000); // Poll every 5 seconds
}
})
.catch((error) => console.error('Error:', error));
}
// Start checking payment status
const sessionId = 'your_session_id'; // Replace with actual session ID
checkPaymentStatus(sessionId);
8. Monitor User Interaction with Payment Interface
Detect if the user abandons the payment process to handle it appropriately.
Action:
Implement Client-Side Detection: Use event listeners to detect when the payment page is closed or navigated away from. Notify the Server: Send a request to update the payment status to 'abandoned' or handle it accordingly.
<!-- Include this script on the payment page if possible -->
<script>
window.addEventListener('beforeunload', function () {
navigator.sendBeacon('/payment-abandoned', JSON.stringify({ sessionId: 'your_session_id' }));
});
</script>
router.post('/payment-abandoned', express.json(), async (req, res) => {
const { sessionId } = req.body;
try {
const paymentSession = await PaymentSession.findOne({ sessionId });
if (paymentSession && paymentSession.status === 'pending') {
paymentSession.status = 'abandoned';
await paymentSession.save();
}
res.status(200).send('Payment abandonment recorded');
} catch (error) {
console.error('Error handling payment abandonment:', error.message);
res.status(500).send('Error handling payment abandonment');
}
});
These steps should be sufficient for the integration of our Crypto Payment API with your application. Make sure to adapt the code to your needs and technology stack.