How do I use an API? 1. Please add the IPv4 or IPv6 addresses that will be allowed to…
- User
How do I use an API? 1. Please add the IPv4 or IPv6 addresses that will be allowed to access the API 2. Your Account Data account['encryption_iv'] = 'c820564bcc23e125'; dataSet, algo) { if (isset(dataSet['sign'])) { unset(dataSet['sign']); } ksort(dataSet, signString = implode(':', signString = hash(signString, true); return base64_encode(signString); } // Function [Encrypting data] function encrypt(secret_pw, string) { pw = hash('sha256', iv = substr(hash('sha256', output = openssl_encrypt(encrypt_method, iv); output); return output; } 4. Generating API signature PHP Examples payment['amount'] = 1000; //required; allowed up to two decimal places payment['description'] = "Test Payment"; //required payment['type_payment'] = "merchant"; //required; variable = merchant payment['custom_field'] = ""; //required; this variable can be empty payment['customer_email'] = "demo@example.com"; //If you provide an email, it will not be requested on the payment page payment['error_url'] = base64_encode("https://example.com/error.php"); //URL for button on error payment page // Generating API signature using Encryption Password payment, payment = json_encode(payment = encrypt(account['encryption_iv'], API_URL = "https://api.b2pay.io/merchantpayments.php"; Before accepting live payments, you can use our test cards Use the value data['payment'] = data['id'] = account['username_id'] = it is your Username ID curl, CURLOPT_URL, curl, CURLOPT_POST, true); curl_setopt(data)); curl_setopt(curl, CURLOPT_HEADER, false); curl_setopt(curl, CURLOPT_TIMEOUT, 60); curl_setopt(response = curl_exec(response = json_decode(curl)) { exit(curl_error(curl)); } else { httpCode = curl_getinfo(httpCode == "200") { if (response['data']['status'] == "success") { print_r(response['data']); exit; } else { exit(response['data']['message']); } } else { if (isset(response['data'])) { exit(response['data']['message']); } else exit(httpCode); } } curl_close(result = json_decode(file_get_contents('php://input'), true); result['pay_id'] = ""; //payment id result['type'] = "pay"; //тип платежа: pay result['orderNumber'] = ""; //your order number result['amount'] = ""; //payment amount result['gatewayRate'] = ""; //gateway rate result['gatewayCurrency'] = ""; //gateway currency // Signature Verification // Generating API signature using Encryption Password result, result['sign'] != $signature) { exit("Incorrect signature"); } We define a notification as “successfully being sent” only in the case that your server responded with a 200 HTTP status code and body “ok” If your server responded any error codes, we schedule recursive callbacks within a 15 minutes interval, but not more than 5 times Payment status Статус Описание pending Payment in progress approved Платеж успешно завершен declined Unsuccessful payment [If applicable, fee apply] rejected Unsuccessful payment expired Unsuccessful payment chargeback Funds returned to the cardholder refund Funds returned to the cardholder refund_request Refund request created refund_canceled Refund request canceled no_suitable No suitable payment gateways gateway_error Payment failed due to a technical error at the gateway Есть такая документация напиши ее реализацию на express nodejs
- Assistant
To implement the described API integration using Node.js and Express, we need to break down the process into steps and write the required functions and routes. Here's a basic setup:
-
Environment Setup: Ensure you have Node.js installed, and then set up an Express project.
-
Install Required Packages: Make sure to install necessary packages like
express,axios,crypto, andbody-parser. -
Write the Code:
Here's an implementation based on the provided PHP code:
const express = require('express'); const axios = require('axios'); const crypto = require('crypto'); const bodyParser = require('body-parser'); const app = express(); app.use(bodyParser.json()); // Your account data const account = { username_id: 1153, encryption_iv: 'c820564bcc23e125', encryption_password: 'e6ecdc4a28138d7946d0b70e140537abb681a5e6a46202faf383ad554ecd4c92eab626f8bcfe9020abd30c51b731fe07adf5182b600fa0bd6adb5e5b8afb1f14', }; // Helper function to generate signature function sign(dataSet, pw, algo) { if (dataSet.sign) { delete dataSet.sign; } const keys = Object.keys(dataSet); keys.sort(); const signData = keys.map((key) => dataSet[key]).join(':') + `:${pw}`; const hash = crypto.createHash(algo).update(signData).digest('base64'); return hash; } // Helper function to encrypt data function encrypt(secretPw, secretIv, text) { const cipher = crypto.createCipheriv( 'aes-256-cbc', crypto.createHash('sha256').update(secretPw).digest(), crypto.createHash('sha256').update(secretIv).digest().slice(0, 16) ); let encrypted = cipher.update(text, 'utf8', 'base64'); encrypted += cipher.final('base64'); return encrypted; } // Example payment data let payment = { amount: 1000, currency: "RUB", description: "Test Payment", order_number: "6c8e9483e15f", type_payment: "merchant", usr: "new", custom_field: "", callback_url: Buffer.from("https://example.com/callback.php").toString('base64'), customer_email: "demo@example.com", success_url: Buffer.from("https://example.com/success.php").toString('base64'), error_url: Buffer.from("https://example.com/error.php").toString('base64'), }; // Generate signature and encrypt the data payment.signature = sign(payment, account.encryption_password, 'md5'); const jsonPayment = JSON.stringify(payment); const encryptedPayment = encrypt(account.encryption_password, account.encryption_iv, jsonPayment); // Sending a request to the API app.post('/api/payment', async (req, res) => { const API_URL = "https://sandbox.b2pay.io/merchantpayments.php"; // Use sandbox for testing const data = { payment: encryptedPayment, id: account.username_id, }; try { const response = await axios.post(API_URL, new URLSearchParams(data), { headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, }); if (response.status === 200 && response.data.data && response.data.data.status === 'success') { console.log(response.data.data); // Successfully processed data res.json({ success: true, message: 'Payment processed', data: response.data.data }); } else { throw new Error(response.data.data.message); } } catch (error) { console.error('Error processing payment:', error); res.status(500).json({ success: false, message: error.message }); } }); const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server running on port ${PORT}`); });Explanation:
- Sign Function: Creates a hash signature of the payment data, excluding the
signkey. - Encrypt Function: Encrypts the JSON string of payment details using AES-256-CBC.
- Express Route: Sets up a POST route to process the payment and send it to the API.
- Axios: Sends HTTP POST requests to the API endpoint.
Notes:
- Replace the sensitive data (
encryption_iv,encryption_password,username_id) with your actual credentials. - Test with the sandbox URL first.
- Adjust the server environment, error handling, and security practices as needed for a production environment.
-