Skip to content

Instantly share code, notes, and snippets.

@coolaj86
Created September 19, 2024 22:29
Show Gist options
  • Save coolaj86/63ffdfbfc83bdd37648d57c53279c9e0 to your computer and use it in GitHub Desktop.
Save coolaj86/63ffdfbfc83bdd37648d57c53279c9e0 to your computer and use it in GitHub Desktop.
A Simple Demo using Google reCAPTCHA with Express, lovingly coaxed out of GPT4o with a heavy hand.
const express = require('express');
const AsyncRouter = require('@root/async-router');
const fetch = require('node-fetch'); // For making external API requests
const app = AsyncRouter.Router();
// Secret key for reCAPTCHA
const RECAPTCHA_SECRET_KEY = 'YOUR_SECRET_KEY';
app.post('/api/process-payment', async (req, res) => {
const { captcha, creditcard } = req.body;
if (!captcha) {
const error = new Error('CAPTCHA token is missing');
error.status = 400;
error.code = 'CAPTCHA_MISSING';
throw error;
}
// Verify the CAPTCHA with Google
const verifyUrl = `https://www.google.com/recaptcha/api/siteverify?secret=${RECAPTCHA_SECRET_KEY}&response=${captcha}`;
const response = await fetch(verifyUrl, { method: 'POST' });
const captchaResult = await response.json();
if (!captchaResult.success) {
const error = new Error('CAPTCHA verification failed');
error.status = 403;
error.code = 'CAPTCHA_FAILED';
throw error;
}
// Call your payment processing logic here, e.g.:
const paymentResult = processPayment(creditcard);
if (!paymentResult) {
const error = new Error('Payment failed');
error.status = 402;
error.code = 'PAYMENT_FAILED';
throw error;
}
return res.json({ success: true, message: 'Payment processed successfully' });
});
// Payment processing function (replace with actual logic)
function processPayment(creditcard) {
// Add your payment processing logic here
return true; // Return true if payment is successful, false otherwise
}
// Global Error Handler
app.use(function async (err, req, res, next) {
res.status(err.status || 500);
res.json({
message: err.message,
code: err.code || 'INTERNAL_SERVER_ERROR',
status: err.status || 500,
});
});
// Start server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment