Skip to main content

What is UniBee webhook?

A Webhook is an HTTP endpoint that receives events from UniBee Webhooks allow you to be notified about payment events that happen outside of your payment flow such as:
  • Successful payments (payment.succeeded)
  • Invoice creation(invoice.created)
  • Subscription Auto-charged(subscription.auto-charge.success)

When to use UniBee webhooks?

UniBee generates multi events that you can listen to in order to trigger your business logic. You will be more fast to receive these events when its generated while using webhook. Also each time an event is generated, you can view it in the Unibee Admin Portal using the webhook logs page. This allows you to take a closer look at the generated events, detect possible errors, and retry them.

How to use UniBee webhooks?

Create Your webhook endpoint (By Admin Portal)

  • Go to the Configuration section via the sidebar
  • Open the Webhook tab
  • Click + to add an endpoint
  • Enter the webhook URL
  • Choose events what you want
  • Click Ok to confirm
Webhook URL Requirements:
  • Must be publicly accessible: Your webhook endpoint must be reachable from the internet
  • Must use HTTPS: UniBee requires HTTPS URLs for webhook endpoints (HTTP is not supported for security reasons)
  • Valid domain: The URL must resolve to a valid server that accepts HTTP POST requests
  • Test in Sandbox: For testing, you can use staging servers, cloud functions, or local development tools that expose HTTPS URLs
Testing Webhooks Locally: For local development and testing, you can use tools that create temporary public HTTPS URLs pointing to your local server:
  • Deploy to a staging environment (recommended for production testing)
  • Use tunneling tools like ngrok, localtunnel, or similar services
  • Ensure the URL remains stable during testing, as webhook events will be sent to the configured URL

Access Your webhook logs

  • Go to the Configuration section via the sidebar
  • Open the Webhooks tab
  • Click on the webhook endpoint to see the list of events
  • Mouse up to the Request Body And Response , you will see the log detail
  • Click the resend icon to repeat event call (optional)

Accessing a specific event

You can see the details of a specific event by checking on logs. A list of properties, including: Datetime: the time of the event
  • Webhook URL: the URL used to listen to events;
  • Msg Id: idempotency Id associated with the event;
  • Webhook event: the webhook event used to understand the action triggered;
  • Response: the response code (i.e. acknowledgement of receipt);
  • Number of retries: if the event failed, the number of retries attempted;
  • A JSON snippet with the arguments sent by UniBee
If the event failed, an error response will be saved.

Webhook Event Headers

UniBee sends the following headers with each webhook request:
HeaderDescriptionExample
Content-TypeAlways application/jsonapplication/json
Msg-idIdempotency ID for the event20250626vAcrK1750930711070
DatetimeEvent timestamp2006-01-02T15:04:05+08:00
EventTypeType of webhook eventinvoice.created
EventIdUnique event identifierev20250626APADJKhuw91AOa9
AuthorizationBearer token with API keyBearer ${APIKey}
X-Signature-AlgorithmSignature algorithm (optional)hmac
X-SignatureHMAC-SHA256 signature (optional, Base64 encoded)abc123...
Note: The EventId header can be used to ensure you process each webhook event only once (idempotency).

Verifying Webhook Requests

UniBee provides two methods for verifying webhook requests. You can choose either method based on your security requirements: Method 1: API Key Verification (Simpler) Verify the webhook by checking the Authorization header contains your API key. Get Your API Key:
  • Copy your API key from UniBee Admin Portal (Configuration → Integrations → UniBee API Key)
  • Store it securely in your environment variables
Implementation Example:
app.post('/webhooks/unibee', express.json(), async (req, res) => {
  // Get Authorization header
  const authHeader = req.headers['authorization'];
  const expectedAuth = `Bearer ${process.env.UNIBEE_API_KEY}`;
  
  // Verify API key
  if (authHeader !== expectedAuth) {
    return res.status(401).send('Invalid API key');
  }
  
  // Process webhook event
  const payload = req.body;
  const eventType = req.headers['eventtype'];
  
  // Handle different event types
  switch (eventType) {
    case 'subscription.activate':
      await handleSubscriptionActivate(payload);
      break;
    case 'invoice.paid':
      await handleInvoicePaid(payload);
      break;
    // ... other event types
  }
  
  // Return success response
  res.status(200).send('success');
});
Method 2: HMAC Signature Verification (More Secure) Verify the webhook by validating the HMAC-SHA256 signature. This provides stronger security guarantees. Implementation Example:
const crypto = require('crypto');

app.post('/webhooks/unibee', express.raw({ type: 'application/json' }), async (req, res) => {
  // Get headers
  const signature = req.headers['x-signature'];
  const algorithm = req.headers['x-signature-algorithm'];
  const eventType = req.headers['eventtype'];
  const eventId = req.headers['eventid'];
  const msgId = req.headers['msg-id'];
  
  // Get raw body as string for signature verification
  const rawBody = req.body.toString();
  
  // Verify HMAC signature
  if (signature && algorithm === 'hmac') {
    const expectedSignature = crypto
      .createHmac('sha256', process.env.UNIBEE_API_KEY)
      .update(rawBody)
      .digest('base64');
    
    if (!crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expectedSignature))) {
      return res.status(401).send('Invalid signature');
    }
  } else {
    // Fallback to API key verification if signature is not present
    const authHeader = req.headers['authorization'];
    const expectedAuth = `Bearer ${process.env.UNIBEE_API_KEY}`;
    
    if (authHeader !== expectedAuth) {
      return res.status(401).send('Invalid API key');
    }
  }
  
  // Parse JSON payload
  const payload = JSON.parse(rawBody);
  
  // Handle different event types
  switch (payload.eventType || eventType) {
    case 'subscription.activate':
      await handleSubscriptionActivate(payload);
      break;
    case 'invoice.paid':
      await handleInvoicePaid(payload);
      break;
    // ... other event types
  }
  
  // Return success response
  res.status(200).send('success');
});
Key Points for Signature Verification:
  • Use the raw JSON body string for signature verification (before parsing)
  • Use your API Key as the secret
  • Signature algorithm is HMAC-SHA256 with Base64 encoding
  • Always use crypto.timingSafeEqual() for signature comparison to prevent timing attacks
  • You can combine both methods for defense in depth
Choosing a Verification Method:
  • API Key Verification (Method 1): Simpler to implement, suitable for most use cases
  • HMAC Signature Verification (Method 2): Provides stronger security, recommended for production systems handling sensitive data
  • Both Methods: You can implement both checks for maximum security
Important: Response Format Your webhook endpoint must return HTTP 200 status code with body content “success” (not “OK” or any other value). UniBee will retry the webhook if it doesn’t receive this exact response.

Errors and retries

Your webhook server should response with a 200 status code and success data, to acknowledge the receipt of the event. If the response is not supported as a success, UniBee will consider it as failed and try for several times, UniBee will retry up to 8 times when its time cap between retry will increase from 1 min to 7 mins under normal circumstances.

Testing Webhooks

Before going live, test your webhook integration using UniBee’s Sandbox environment: Testing Setup:
  1. Use Sandbox API: Point your integration to https://api-sandbox.unibee.top
  2. Configure Webhook Endpoint:
    • Option A: Deploy your webhook endpoint to a public URL (e.g., a staging server or cloud function) - recommended for production testing
    • Option B: Use a local development tool (e.g., ngrok, localtunnel, or similar) to temporarily expose your local webhook endpoint to the internet
    • Ensure the URL remains stable during testing, as webhook events will be sent to the configured URL
  3. Test Webhook Events: Trigger events in the Sandbox environment (e.g., create subscriptions, process payments)
  4. Verify Webhook Deliveries: Monitor webhook deliveries in UniBee Admin Portal to ensure events are received correctly
    • Go to Configuration → Webhooks → Webhook Endpoints
    • Click on your webhook endpoint to see the list of events
    • Check the Request Body and Response to verify event processing
  5. Test Verification Methods: Ensure both API key and HMAC signature verification work correctly in your testing environment
Best Practices for Testing:
  • Test all webhook events you’ve subscribed to
  • Verify idempotency handling using the EventId header
  • Test error scenarios (network failures, invalid responses)
  • Monitor webhook logs to catch any issues early
  • Use test cards for payment-related webhooks (see Testing Cards)
Production Checklist: Before deploying to production, ensure:
  • Webhook endpoint uses HTTPS
  • Webhook signature verification is implemented
  • Idempotency is handled correctly (using EventId header)
  • Error handling is robust
  • Monitoring and alerting are set up for webhook failures
  • All subscribed webhook events are tested