// SECURE - Using environment variables and secure initialization
const stripe = require('stripe');
const paypal = require('@paypal/checkout-server-sdk');
class SecurePaymentProcessor {
constructor() {
this.initializeProviders();
}
async initializeProviders() {
// Load from environment variables or secrets manager
const stripeKey = process.env.STRIPE_SECRET_KEY;
const paypalClientId = process.env.PAYPAL_CLIENT_ID;
const paypalSecret = process.env.PAYPAL_CLIENT_SECRET;
// Validate keys exist
if (!stripeKey || !paypalClientId || !paypalSecret) {
throw new Error('Payment credentials not configured');
}
// Initialize Stripe with restricted key
this.stripe = stripe(stripeKey, {
apiVersion: '2023-10-16',
maxNetworkRetries: 2,
timeout: 20000
});
// Initialize PayPal with appropriate environment
const environment = process.env.NODE_ENV === 'production'
? new paypal.core.LiveEnvironment(paypalClientId, paypalSecret)
: new paypal.core.SandboxEnvironment(paypalClientId, paypalSecret);
this.paypalClient = new paypal.core.PayPalHttpClient(environment);
}
// Use webhook endpoints for secure payment confirmation
async handleStripeWebhook(request) {
const sig = request.headers['stripe-signature'];
const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET;
try {
const event = this.stripe.webhooks.constructEvent(
request.body,
sig,
webhookSecret
);
// Process webhook event
await this.processPaymentEvent(event);
} catch (err) {
console.error('Webhook signature verification failed');
throw err;
}
}
}
// Use a secrets manager for production
const { SecretManagerServiceClient } = require('@google-cloud/secret-manager');
async function getPaymentCredentials() {
const client = new SecretManagerServiceClient();
const [stripeSecret] = await client.accessSecretVersion({
name: 'projects/my-project/secrets/stripe-key/versions/latest',
});
return {
stripe: stripeSecret.payload.data.toString(),
// ... other credentials
};
}