Authentication overview
Recurly provides authentication mechanisms to secure programmatic access to its API, enabling developers to manage subscription billing, customer accounts, and transactions. The primary method for authenticating API requests is through API keys, which are used to identify and authorize applications communicating with Recurly's backend systems. For securing inbound communication, specifically webhooks, Recurly employs HMAC signatures to verify the integrity and origin of notifications sent to your application. This dual approach ensures that both outgoing API calls and incoming webhook events are protected against unauthorized access and tampering.
Integration with Recurly typically involves configuring your application to send API keys with each request. These keys grant your application specific permissions based on the key's configuration within the Recurly administrative console. When setting up webhooks, an additional security layer is implemented where Recurly signs each outgoing webhook payload with a shared secret. Your application can then use this secret to compute its own signature of the received payload and compare it to Recurly's provided signature, thereby confirming the webhook's authenticity and preventing spoofing. Adhering to these authentication protocols is crucial for maintaining the security and compliance of your billing operations, especially given Recurly's PCI DSS Level 1 compliance Recurly compliance information.
Supported authentication methods
Recurly supports two primary methods for authentication and message integrity, catering to different interaction patterns with its platform.
API Keys
API keys are the standard method for authenticating requests made from your application to the Recurly API. These keys are unique identifiers associated with your Recurly account and carry specific permissions. When you make an API call, the key is included in the request header, allowing Recurly to verify your identity and authorization.
- Application: Server-to-server API calls for managing subscriptions, invoices, refunds, and customer data.
- Mechanism: The API key is sent in the
Authorizationheader using Basic Authentication, where the key acts as the username and an empty string or placeholder acts as the password. - Security Considerations: API keys should be treated as sensitive credentials, similar to passwords. They should never be hardcoded into client-side code or exposed publicly.
HMAC Signatures for Webhooks
HMAC (Hash-based Message Authentication Code) signatures are used to secure webhooks, which are automated POST requests sent from Recurly to your application when certain events occur (e.g., successful payment, subscription renewal). This method ensures that the webhook payload was sent by Recurly and has not been tampered with in transit.
- Application: Verifying the authenticity and integrity of event notifications received from Recurly.
- Mechanism: Recurly calculates an HMAC signature using a shared secret key and the webhook payload. This signature is included in a header (e.g.,
X-Recurly-Signature) of the webhook request. Your application performs the same calculation with the shared secret and the received payload to verify the signature. - Security Considerations: The webhook shared secret must be kept confidential. If compromised, an attacker could send forged webhook events to your system.
Here's a summary of Recurly's authentication methods:
| Method | When to Use | Security Level & Use Case |
|---|---|---|
| API Keys | Outbound API calls from your application to Recurly. | High: Primarily for server-side operations, ensuring authorized access to Recurly's core functionalities like managing subscriptions, creating invoices, and processing transactions. Requires secure storage. |
| HMAC Signatures for Webhooks | Inbound webhook events from Recurly to your application. | Very High: Verifies sender authenticity and payload integrity of event notifications (e.g., payment success, subscription changes). Crucial for reliable and secure asynchronous processing. |
Getting your credentials
To obtain the necessary authentication credentials for Recurly, you will typically use the Recurly Admin Console. Access to this console is restricted to authorized users of your Recurly account.
Obtaining API Keys
- Log in: Access your Recurly Admin Console using your account credentials.
- Navigate to Integrations: Look for a section related to 'Integrations', 'API Credentials', or 'Developers'. The exact path may vary slightly across Recurly's UI updates, but it's generally found in the configuration or administrative settings.
- Generate New API Key: Within the API settings, you will find an option to generate a new API key. Recurly often distinguishes between 'Sandbox' (for testing) and 'Production' (for live operations) API keys. Ensure you generate the correct type of key for your environment.
- Copy Key: Once generated, the API key will be displayed. It's crucial to copy this key immediately and store it securely, as Recurly may only show the full key once for security reasons.
- Permissions (if applicable): Some Recurly accounts or API key types may allow you to configure specific permissions for the key, limiting its access to certain API resources or operations. Configure these permissions according to the principle of least privilege.
For detailed, up-to-date instructions on navigating the Recurly Admin Console to generate API keys, refer to the official Recurly API Authentication documentation.
Obtaining Webhook Shared Secret
- Log in: Access your Recurly Admin Console.
- Navigate to Webhooks: Find the 'Webhooks' or 'Integrations' section within your settings.
- Configure Webhook Endpoint: If you haven't already, you'll need to add your webhook endpoint URL where Recurly should send event notifications.
- Retrieve Shared Secret: Associated with your webhook configuration, Recurly will provide a unique 'shared secret' or 'signature key'. This secret is used to generate and verify HMAC signatures. Like API keys, it should be copied and stored securely.
Refer to the Recurly Webhooks guide for the most current instructions on configuring webhooks and retrieving the shared secret.
Authenticated request example
This section provides examples of how to make an authenticated request to the Recurly API using an API key and how to verify a Recurly webhook using an HMAC signature. These examples demonstrate common integration patterns.
API Key Example (Ruby)
Recurly provides client libraries (SDKs) for several languages, including Ruby, Python, PHP, Java, and Node.js Recurly client libraries. These SDKs abstract away the low-level HTTP request details, including authentication headers. Below is an example using the Ruby client library.
require 'recurly'
# Configure Recurly with your API Key
Recurly.configure do |config|
config.api_key = ENV['RECURLY_API_KEY'] # It's best practice to use environment variables
config.default_currency = 'USD'
end
begin
# Example: Fetch an account by its account code
account = Recurly::Account.find('account_code_here')
puts "Found account: #{account.email}"
# Example: Create a new subscription
# subscription = Recurly::Subscription.create(
# account: { account_code: 'new_customer_123', email: '[email protected]' },
# plan_code: 'gold_plan',
# currency: 'USD'
# )
# puts "New subscription created for: #{subscription.account.email}"
rescue Recurly::Errors::NotFound
puts "Account not found."
rescue Recurly::Errors::APIError => e
puts "API Error: #{e.message}"
end
In this Ruby example, the API key is loaded from an environment variable (RECURLY_API_KEY) and configured globally for the Recurly client. Subsequent calls using the Recurly::Account or Recurly::Subscription objects will automatically include this key in the request headers.
Webhook Verification Example (Node.js)
When Recurly sends a webhook, it includes an X-Recurly-Signature header. Your application must verify this signature using the shared secret to ensure the webhook's authenticity. This example uses Node.js.
const express = require('express');
const crypto = require('crypto');
const bodyParser = require('body-parser');
const app = express();
const webhookSecret = process.env.RECURLY_WEBHOOK_SECRET; // Store securely!
// Use raw body parser to get the raw request body for signature verification
app.use(bodyParser.raw({
type: 'application/json',
verify: (req, res, buf) => {
if (req.url === '/recurly-webhook') {
req.rawBody = buf; // Attach raw body to request for later use
}
},
}));
app.post('/recurly-webhook', (req, res) => {
const recurlySignature = req.headers['x-recurly-signature'];
const payload = req.rawBody; // The raw body is needed for signature calculation
if (!recurlySignature || !payload) {
return res.status(400).send('Webhook request missing signature or payload.');
}
// Calculate HMAC signature
const hmac = crypto.createHmac('sha256', webhookSecret);
hmac.update(payload);
const calculatedSignature = hmac.digest('hex');
// Compare calculated signature with the signature from Recurly
if (calculatedSignature === recurlySignature) {
console.log('Webhook signature verified successfully.');
try {
const event = JSON.parse(payload.toString());
console.log('Received Recurly event:', event);
// Process the Recurly event here
res.status(200).send('Webhook received and processed.');
} catch (error) {
console.error('Error parsing webhook payload:', error);
res.status(400).send('Invalid webhook payload.');
}
} else {
console.warn('Webhook signature verification failed. Possible tampering or incorrect secret.');
res.status(401).send('Invalid webhook signature.');
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server listening on port ${PORT}`));
This Node.js example demonstrates how to set up an Express endpoint to receive Recurly webhooks. It uses body-parser.raw to access the raw request body, which is essential for calculating the HMAC signature. The crypto module is used to compute the SHA256 HMAC, which is then compared against the signature provided in the X-Recurly-Signature header. This process is a common security practice for webhooks, also implemented by other platforms like Stripe Stripe webhook signatures guide.
Security best practices
Properly securing your Recurly integration is critical, especially when handling sensitive customer and payment information. Adhering to these best practices will help protect your data and maintain compliance.
API Key Management
- Environment Variables: Never hardcode API keys directly into your source code. Instead, store them as environment variables (e.g.,
RECURLY_API_KEY) on your server or use a secure secret management service. This prevents keys from being exposed in version control systems or publicly accessible code. - Least Privilege: If Recurly allows for granular permissions on API keys, configure them with the minimum necessary permissions required for the specific tasks your application performs. Do not grant broad access if only specific actions are needed.
- Key Rotation: Periodically rotate your API keys. This practice minimizes the window of exposure if a key is compromised. Recurly's Admin Console should provide functionality for generating new keys and revoking old ones.
- Restrict Access: Limit who has access to your API keys. Only developers and systems that absolutely require access should be granted it.
Webhook Security
- Verify Signatures: Always verify the HMAC signature of every incoming Recurly webhook. This is the primary mechanism to ensure that the webhook originated from Recurly and that its payload has not been altered in transit. Reject any webhooks with invalid or missing signatures.
- Use HTTPS: Ensure your webhook endpoint uses HTTPS (TLS/SSL) to encrypt communications between Recurly and your server. This protects the webhook payload from eavesdropping.
- Idempotency: Design your webhook processing logic to be idempotent. This means that processing the same webhook event multiple times should have the same effect as processing it once. This protects against duplicate event deliveries, which can sometimes occur in distributed systems.
- Asynchronous Processing: Process webhooks asynchronously. Your webhook endpoint should quickly acknowledge receipt (HTTP 200 OK) and then hand off the actual processing to a background job or queue. This prevents timeouts and ensures Recurly doesn't retry events excessively.
- Monitor Webhooks: Implement monitoring for your webhook endpoint to detect failures, invalid signatures, or unusual activity.
General Security Practices
- HTTPS Everywhere: All communication with Recurly's API should occur over HTTPS. Recurly enforces this, but always double-check your integration configuration.
- Error Handling: Implement robust error handling and logging for API requests and webhook processing. Avoid exposing sensitive information in error messages to end-users.
- Input Validation: Always validate and sanitize any data received from external sources, including webhook payloads, before processing it.
- Regular Audits: Conduct regular security audits and penetration testing of your application and infrastructure, especially those parts that interact with Recurly.
- Stay Updated: Keep your Recurly client libraries (SDKs) and any related dependencies updated to benefit from the latest security patches and features.