Webhook integration
Description: A webhook is a mechanism that automatically sends an HTTP POST request to a specified URL when a specific event occurs. By using webhooks, your app can receive notifications in real-time about specific events, such as data updates, status changes, and more.
How to use Webhook?
To use Webhook,You need to follow these steps:
- Register Webhook URL: Create a URL in your application to receive webhook requests.
- Configure Webhooks: Configure the service or application to send an HTTP POST request to the webhook URL you provide when a specific event is triggered. EDITION Pass the URL into the 'webhookUrl' field of the payment interface, and the payment interface will send a notification to the URL when the payment status changes.
- Handling Webhook Requests: Write code in your application to process the received webhook requests, performing the appropriate actions or logic.
Webhook request parameters
Parameter name | Type | Requirement | Description |
---|---|---|---|
event | string | R | For details about the definition of event types, see Appendix B Webhook Event Types |
data | string | R | The specific parameters are determined by the event type, as defined in "Appendix C Supported Event Types". |
Here's the format of an example webhook request:
- Deposit events
{
"event": "DEPOSIT_EVENT",
"data": {
"trackingId": "123",
"status": 1,
"amount": 100
}
}
- Withdrawal events
{
"event": "WITHDRAWAL_EVENT",
"data": {
"trackingId": "123",
"status": 1,
"amount": 100,
"stayReason": ""
}
}
Webhook response
Return string: Webhook received Otherwise, any case will be deemed non-delivered
Webhook Example
@PostMapping("/webhook")
public String handleWebhookRequest(@RequestBody String payload, @RequestHeader("X-Signature") String receivedSignature) {
log.info("payload:{},receivedSignature:{}", payload, receivedSignature);
String calculatedSignature = calculateHMAC(payload, secretKey);
if (calculatedSignature.equals(receivedSignature)) {
// The signature verification is successful, and the request is processed
// Parse request parameters
// JSONObject jsonObject = JSONUtil.parseObj(payload);
// String eventType = jsonObject.getStr("event");
// JSONObject data = jsonObject.getJSONObject("data");
// String trackingId = data.getStr("trackingId");
// Call the deposit or withdrawal query interface to confirm whether the notification is valid
return "Webhook received";
} else {
// Signature verification fails, requests are rejected, or logs are recorded
log.info("calculatedSignature:{},receivedSignature:{},webhook signature error", calculatedSignature,
receivedSignature);
return "Unauthorized";
}
}
public static String calculateHMAC(String data, String secretKey) {
try {
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), HMAC_SHA_512);
Mac mac = Mac.getInstance(HMAC_SHA_512);
mac.init(secretKeySpec);
byte[] rawHmac = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(rawHmac);
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
throw new RuntimeException("Failed to calculate HMAC: " + e.getMessage(), e);
}
}
Here is an example of a Node.js version of webhook handling and HMAC calculation:
const express = require('express');
const crypto = require('crypto');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.text());
const secretKey = 'your_secret_key'; // Replace it with your key
app.post('/webhook', (req, res) => {
const payload = req.body;
const receivedSignature = req.header('X-Signature');
console.log(`Payload: ${payload}, Received Signature: ${receivedSignature}`);
const calculatedSignature = calculateHMAC(payload, secretKey);
if (calculatedSignature === receivedSignature) {
// The signature is verified successfully, and the request is processed
// Parse request parameters
// let jsonObject = JSON.parse(payload);
// let eventType = jsonObject.event;
// let data = jsonObject.data;
// let trackingId = data.trackingId;
// Call the deposit or withdrawal query API to confirm whether the notification is valid
res.send('Webhook received');
} else {
// Signature verification fails, requests are rejected, or logs are recorded
console.log(`Calculated Signature: ${calculatedSignature}, Received Signature: ${receivedSignature}, Webhook signature error`);
res.status(401).send('Unauthorized');
}
});
function calculateHMAC(data, secretKey) {
const hmac = crypto.createHmac('sha512', secretKey);
const dataHmac = hmac.update(data);
const hmacDigest = dataHmac.digest('base64');
return hmacDigest;
}
app.listen(3000, () => console.log('Server is listening on port 3000'));
This example uses Express.js, which is a very popular Node.js web framework. This code creates a Express.js server and listens for POST requests for the /webhook path. When a request is received, it calculates the HMAC and compares it to the X-Signature in the request header. If the HMAC matches, it returns "Webhook received", otherwise it returns an HTTP 401 error and an "Unauthorized" message.
Note that you need to use npm to install the two dependencies express and body-parser:
npm install express body-parser
Safety Considerations
When using webhooks, it's important to consider security concerns to prevent unauthorized access or data breaches. Here are some security recommendations:
- Secure webhook communication using the HTTPS protocol.
- Verify the origin and content of the received webhook request to ensure its legitimacy. (After receiving the notification, call the deposit query or withdrawal query interface to obtain the data and compare whether the data is consistent)
Appendix B Webhook Event Types
Event type | Description |
---|---|
DEPOSIT_EVENT | Deposit Event |
WITHDRAWAL_EVENT | Withdrawal Event |
Appendix C Supported Event Types
-
DEPOSIT_EVENT
Parameter name Type Requirement Description trackingId string R Tracking ID status int R Deposit Status amount int R Deposit amount -
WITHDRAWAL_EVENT
Parameter name Type Requirement Description trackingId string R Tracking ID status int R Withdrawal Status amount int R Withdrawal amount stayReason string O Reasons for abnormal withdrawals