Node.js新手求助:如何集成Bpoint支付网关?
Hey there! I totally get how tricky it can be to wrap your head around integrating a payment gateway when you're new to Node.js—let's walk through how to set up BPOINT step by step, no jargon overload.
Before writing any code, you need to grab your merchant-specific details from the BPOINT portal (you should have these once you've signed up as a merchant):
- Merchant ID
- API Key/Secret pair
- Base API endpoint URL (sandbox for testing, production for live payments)
Pro tip: Never hardcode these values in your code! Store them securely using environment variables—we'll cover that next.
If you haven't already initialized your project, run these commands in your terminal:
npm init -y npm install axios dotenv express
axios: Handles HTTP requests to the BPOINT APIdotenv: Manages environment variables safelyexpress: (Optional but recommended) Lets you set up a server for webhooks and payment endpoints
Create a .env file in your project root and add your credentials:
BPOINT_MERCHANT_ID=your_merchant_id_here BPOINT_API_KEY=your_api_key_here BPOINT_API_SECRET=your_api_secret_here BPOINT_BASE_URL=https://sandbox.bpoint.com.au/api/v1 # Use sandbox first!
Then load these variables in your main Node.js file:
require('dotenv').config(); // Pull in credentials const merchantId = process.env.BPOINT_MERCHANT_ID; const apiKey = process.env.BPOINT_API_KEY; const apiSecret = process.env.BPOINT_API_SECRET; const baseUrl = process.env.BPOINT_BASE_URL;
BPOINT uses REST APIs for payment processing. Here's a simplified example of charging a card (adjust the payload to match BPOINT's exact API specs—they'll outline required fields in their merchant docs):
const axios = require('axios'); async function processBpointPayment(amount, cardDetails, customerInfo) { try { // BPOINT often expects amounts in cents (e.g., $50.00 becomes 5000) const paymentPayload = { merchantId: merchantId, amount: Math.round(amount * 100), card: { number: cardDetails.number, expiry: cardDetails.expiry, // Format: MMYY (e.g., 1228) cvv: cardDetails.cvv }, customer: { name: customerInfo.name, email: customerInfo.email } }; // Add authentication headers (BPOINT typically uses Basic Auth or HMAC signing) const authHeaders = { 'Authorization': `Basic ${Buffer.from(`${apiKey}:${apiSecret}`).toString('base64')}`, 'Content-Type': 'application/json' }; const response = await axios.post(`${baseUrl}/payments`, paymentPayload, { headers: authHeaders }); console.log('Payment successful!', response.data); return response.data; } catch (error) { // Handle errors like declined cards, invalid credentials, or expired tokens console.error('Payment failed:', error.response?.data || error.message); throw error; } }
Critical Note: Never handle raw card details directly in your server if you can avoid it! BPOINT likely offers client-side tokenization to safely capture card info without exposing sensitive data to your backend. This is mandatory for PCI compliance—check their docs for tokenization steps.
Use BPOINT's test card details to verify your setup works:
// Example test payment const runTestPayment = async () => { try { const result = await processBpointPayment( 50.00, // $50.00 test charge { number: '4111111111111111', // BPOINT's test card number expiry: '1228', cvv: '123' }, { name: 'Test User', email: 'test@example.com' } ); console.log('Test payment result:', result); } catch (err) { console.error('Test payment failed:', err); } }; runTestPayment();
BPOINT will send webhook notifications for payment status updates (e.g., successful, failed, refunded). Here's how to set up an endpoint to receive these:
const express = require('express'); const app = express(); app.use(express.json()); app.post('/bpoint-webhook', (req, res) => { // Verify the webhook signature to ensure it's actually from BPOINT const incomingSignature = req.headers['x-bpoint-signature']; const isValid = verifyWebhookSignature(req.body, incomingSignature); if (!isValid) { return res.status(403).send('Invalid webhook signature'); } // Process the payment status update const { paymentId, status, amount } = req.body; console.log(`Payment ${paymentId} updated to status: ${status}`); res.status(200).send('Webhook received'); }); // Helper function to verify signature (match BPOINT's signing method) function verifyWebhookSignature(payload, incomingSignature) { const crypto = require('crypto'); const generatedSignature = crypto.createHmac('sha256', apiSecret) .update(JSON.stringify(payload)) .digest('hex'); return generatedSignature === incomingSignature; } app.listen(3000, () => { console.log('Server running on port 3000—ready for webhooks!'); });
Don't forget to register your webhook URL in the BPOINT merchant dashboard so they know where to send updates.
- Double-check your credentials: Typos in merchant IDs or API keys are the #1 cause of early failures.
- Stick to the sandbox first: Don't use real cards until you've confirmed every step works.
- Check BPOINT's error codes: Their API returns specific messages (e.g., "invalid expiry date") that will point you to the issue.
- Expose your local server for webhooks: If testing locally, use a tool like ngrok to make your server accessible to BPOINT's systems.
内容的提问来源于stack exchange,提问作者Kuldeep Mishra

