Third-Party Integrations
Connect to external services and APIs
Integrate your Replov services with popular third-party APIs for payments, email, messaging, analytics, and more. We provide secure credential management and webhook handling.
SendGrid, Mailgun
Payments
Stripe, Razorpay
Messaging
Twilio, Slack
Webhooks
Receive events
Email Services
Send transactional and marketing emails from your application:
SendGrid
Reliable email delivery with analytics and templates.
# Add API key to environment variablesSENDGRID_API_KEY=SG.xxx...
Node.js Example:
const sgMail = require('@sendgrid/mail');sgMail.setApiKey(process.env.SENDGRID_API_KEY);async function sendEmail(to, subject, html) {const msg = {to,from: 'noreply@yourdomain.com',subject,html};try {await sgMail.send(msg);console.log('Email sent successfully');} catch (error) {console.error('Email error:', error);throw error;}}// Send welcome emailawait sendEmail('user@example.com','Welcome to Our Platform','<h1>Welcome!</h1><p>Thanks for signing up.</p>');
Mailgun
Developer-friendly email API with powerful routing.
# Environment variablesMAILGUN_API_KEY=key-xxx...MAILGUN_DOMAIN=mg.yourdomain.com
import requestsimport osdef send_email(to, subject, html):return requests.post(f"https://api.mailgun.net/v3/{os.environ['MAILGUN_DOMAIN']}/messages",auth=("api", os.environ['MAILGUN_API_KEY']),data={"from": "noreply@yourdomain.com","to": to,"subject": subject,"html": html})# Send emailsend_email("user@example.com","Welcome","<h1>Welcome!</h1>")
Payment Processing
Accept payments securely with Stripe or Razorpay:
Stripe
Global payment processing with extensive features.
# Environment variablesSTRIPE_SECRET_KEY=sk_test_xxx...STRIPE_PUBLISHABLE_KEY=pk_test_xxx...STRIPE_WEBHOOK_SECRET=whsec_xxx...
Create Payment Intent:
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);async function createPayment(amount, currency = 'usd') {const paymentIntent = await stripe.paymentIntents.create({amount: amount * 100, // Convert to centscurrency,automatic_payment_methods: {enabled: true}});return {clientSecret: paymentIntent.client_secret};}// Express routeapp.post('/create-payment', async (req, res) => {const { amount } = req.body;try {const payment = await createPayment(amount);res.json(payment);} catch (error) {res.status(500).json({ error: error.message });}});
Handle Webhooks:
app.post('/webhooks/stripe',express.raw({ type: 'application/json' }),async (req, res) => {const sig = req.headers['stripe-signature'];try {const event = stripe.webhooks.constructEvent(req.body,sig,process.env.STRIPE_WEBHOOK_SECRET);// Handle eventswitch (event.type) {case 'payment_intent.succeeded':const payment = event.data.object;console.log('Payment succeeded:', payment.id);// Update database, send confirmation emailbreak;case 'payment_intent.payment_failed':console.log('Payment failed');// Notify userbreak;}res.json({ received: true });} catch (err) {res.status(400).send(`Webhook Error: ${err.message}`);}});
Razorpay (India)
Popular payment gateway for Indian businesses.
# Environment variablesRAZORPAY_KEY_ID=rzp_test_xxx...RAZORPAY_KEY_SECRET=xxx...
const Razorpay = require('razorpay');const razorpay = new Razorpay({key_id: process.env.RAZORPAY_KEY_ID,key_secret: process.env.RAZORPAY_KEY_SECRET});async function createOrder(amount, currency = 'INR') {const order = await razorpay.orders.create({amount: amount * 100, // Convert to paisecurrency,receipt: `order_${Date.now()}`});return order;}// Verify payment signaturefunction verifyPayment(orderId, paymentId, signature) {const crypto = require('crypto');const text = orderId + '|' + paymentId;const generated = crypto.createHmac('sha256', process.env.RAZORPAY_KEY_SECRET).update(text).digest('hex');return generated === signature;}
Messaging Services
Send SMS, WhatsApp messages, and Slack notifications:
Twilio SMS
# Environment variablesTWILIO_ACCOUNT_SID=ACxxx...TWILIO_AUTH_TOKEN=xxx...TWILIO_PHONE_NUMBER=+1234567890
const twilio = require('twilio');const client = twilio(process.env.TWILIO_ACCOUNT_SID,process.env.TWILIO_AUTH_TOKEN);async function sendSMS(to, message) {const result = await client.messages.create({body: message,from: process.env.TWILIO_PHONE_NUMBER,to});return result.sid;}// Send OTPawait sendSMS('+919876543210', 'Your OTP is: 123456');
Slack Notifications
# Environment variableSLACK_WEBHOOK_URL=https://hooks.slack.com/services/xxx/yyy/zzz
const axios = require('axios');async function sendSlackNotification(message, channel = '#general') {await axios.post(process.env.SLACK_WEBHOOK_URL, {channel,username: 'Replov Bot',text: message,icon_emoji: ':rocket:'});}// Send deployment notificationawait sendSlackNotification('🚀 New deployment successful: v1.2.3','#deployments');
Receiving Webhooks
Handle incoming webhooks from third-party services:
1. Create Webhook Endpoint
app.post('/webhooks/:provider', async (req, res) => {const { provider } = req.params;// Verify webhook signatureif (!verifyWebhookSignature(req, provider)) {return res.status(401).json({ error: 'Invalid signature' });}// Process webhooktry {await processWebhook(provider, req.body);res.json({ received: true });} catch (error) {console.error('Webhook error:', error);res.status(500).json({ error: 'Processing failed' });}});
2. Verify Signatures
Always verify webhook signatures to prevent spoofing:
const crypto = require('crypto');function verifyWebhookSignature(req, provider) {const signature = req.headers['x-webhook-signature'];const secret = process.env[`${provider.toUpperCase()}_WEBHOOK_SECRET`];const computed = crypto.createHmac('sha256', secret).update(JSON.stringify(req.body)).digest('hex');return crypto.timingSafeEqual(Buffer.from(signature),Buffer.from(computed));}
3. Handle Idempotency
Webhooks may be delivered multiple times. Use idempotency keys:
async function processWebhook(provider, data) {const eventId = data.id || data.event_id;// Check if already processedconst existing = await db.query('SELECT id FROM webhook_events WHERE event_id = $1',[eventId]);if (existing.rows.length > 0) {console.log('Webhook already processed:', eventId);return;}// Process webhookawait handleWebhookEvent(provider, data);// Mark as processedawait db.query('INSERT INTO webhook_events (event_id, provider, processed_at) VALUES ($1, $2, NOW())',[eventId, provider]);}
Analytics & Monitoring
Google Analytics
# Environment variableGA_MEASUREMENT_ID=G-XXXXXXXXXX
// Frontend trackingimport ReactGA from 'react-ga4';ReactGA.initialize(process.env.REACT_APP_GA_MEASUREMENT_ID);// Track page viewsReactGA.send({ hitType: "pageview", page: window.location.pathname });// Track eventsReactGA.event({category: 'User',action: 'Signup',label: 'Free Tier'});
Sentry Error Tracking
# Environment variableSENTRY_DSN=https://xxx@sentry.io/yyy
const Sentry = require('@sentry/node');Sentry.init({dsn: process.env.SENTRY_DSN,environment: process.env.NODE_ENV,tracesSampleRate: 1.0});// Capture errorstry {// Your code} catch (error) {Sentry.captureException(error);throw error;}
Best Practices
1. Use Environment Variables
Never hardcode API keys. Always use environment variables and rotate keys regularly.
2. Implement Retry Logic
Third-party APIs can fail. Implement exponential backoff and retry mechanisms.
3. Rate Limiting
Respect API rate limits. Cache responses when possible and implement request queuing.
4. Monitor API Usage
Track API calls, errors, and costs. Set up alerts for unusual activity or quota limits.
5. Secure Webhooks
Always verify webhook signatures. Use HTTPS endpoints and implement idempotency.
Troubleshooting
API Authentication Failed
Check:
- • API key is correct and not expired
- • Using correct environment (test vs production keys)
- • API key has required permissions
- • Request headers are properly formatted
Webhook Not Receiving Events
Check:
- • Webhook URL is publicly accessible (HTTPS)
- • Endpoint returns 200 status code
- • Webhook is configured in provider dashboard
- • Check provider's webhook delivery logs
Rate Limit Exceeded
Solution: Implement request queuing, caching, or upgrade API plan.