HU-BACK-002 Implementing CardNet API For Payment Session Creation
Introduction
This document details the implementation of a backend service designed to consume the CardNet session API, enabling payment transactions initiation from our platform. As a backend developer, the goal is to create a robust and secure service that interacts seamlessly with CardNet's API. This involves handling requests, processing responses, ensuring security, and maintaining audit logs. This comprehensive guide outlines the requirements, acceptance criteria, and implementation details for the CardNet payment session creation API.
Acceptance Criteria
1. Request Structure
The request structure is crucial for successful communication with CardNet's API. Before sending any request, the service must rigorously validate all mandatory fields to ensure data integrity and compliance with CardNet's requirements.
The Amount field, representing the transaction amount, must be in centavos, ensuring accurate monetary representation. The OrdenId field must follow a specific format: ORD-[timestamp]-[random4digits], ensuring uniqueness and traceability of each transaction. The ReturnUrl and CancelUrl must be dynamically generated to provide users with a seamless redirection experience based on the transaction outcome. These URLs are essential for informing the user about the status of their payment and guiding them back to our platform.
Detailed Validation Requirements
- Amount Validation: The service must verify that the amount is a positive integer and represents the value in centavos. Any non-numeric or negative values should be rejected with appropriate error messages.
- OrdenId Generation and Validation: The OrdenId must be generated using the specified format. This includes creating a timestamp and a random four-digit number. The service should also ensure that the generated OrdenId is unique to prevent conflicts and ensure proper transaction tracking.
- Dynamic URL Generation: The ReturnUrl and CancelUrl must be dynamically generated based on the environment and transaction context. This ensures that users are redirected to the correct pages on our platform, providing a consistent user experience. The URLs should include necessary parameters to identify the transaction and its status.
2. Response Handling
The response handling mechanism is essential for interpreting CardNet's feedback and taking appropriate actions. The service must be capable of processing both successful and error responses from the CardNet API.
Upon a successful transaction, the service must extract the SESSION and session-key values. These values are crucial for subsequent interactions with CardNet, such as finalizing the payment. In case of an error, the service must classify errors based on the provided error codes. For instance, a 401 error typically indicates authentication failure, while a 500 error suggests an internal server error on CardNet's side. Proper error classification allows for precise debugging and issue resolution.
Comprehensive Response Processing
- Successful Response Processing: When a successful response is received, the service must parse the JSON response to extract the SESSION and session-key. These values should be stored securely and used in subsequent payment processing steps. Additionally, the service should log the successful response for auditing purposes.
- Error Response Processing: In the event of an error response, the service must first identify the error code. Based on the error code, specific actions should be taken. For example, a 401 error might trigger a retry mechanism with fresh credentials, while a 500 error might indicate the need to alert the operations team. Each error code should have a corresponding handling strategy to ensure the system's robustness.
- Error Logging: All error responses should be logged with sufficient detail to facilitate debugging. This includes the error code, the error message, the request payload, and any other relevant information. Proper error logging is critical for maintaining system stability and quickly resolving issues.
3. Security
Security is a paramount concern when dealing with payment transactions. The service must implement robust security measures to protect sensitive data and prevent unauthorized access.
CardNet credentials, such as MerchantNumber and Terminal, must be encrypted both in transit and at rest. This prevents exposure of sensitive information in case of a data breach. The service must also implement IP whitelisting, allowing only authorized servers to access the API. This prevents unauthorized access and enhances the overall security posture.
Robust Security Implementation
- Credential Encryption: The MerchantNumber and Terminal credentials must be encrypted using a strong encryption algorithm. The encryption keys should be managed securely, preferably using a hardware security module (HSM) or a similar key management system. The encrypted credentials should be stored securely, and access to the encryption keys should be strictly controlled.
- IP Whitelisting: The service should maintain a whitelist of IP addresses that are allowed to access the API. Any requests originating from non-whitelisted IPs should be rejected. This helps prevent unauthorized access and mitigates the risk of attacks from unknown sources. The whitelist should be reviewed and updated regularly to ensure that it remains current and accurate.
- Secure Communication: All communication with the CardNet API should occur over HTTPS to ensure that data is encrypted in transit. The service should also enforce the use of TLS 1.2 or later to comply with industry best practices for secure communication.
4. Audit
Auditing is crucial for tracking transactions and identifying potential issues. The service must log all requests and responses, excluding sensitive data such as card numbers.
This log data is invaluable for debugging, monitoring, and compliance purposes. Each log entry should include relevant information such as timestamps, request details, response codes, and any error messages. This comprehensive logging ensures that all interactions with the CardNet API are recorded and can be reviewed as needed.
Comprehensive Audit Logging
- Request Logging: All requests sent to the CardNet API should be logged. The log entry should include a timestamp, the request URL, the request headers, and the request payload (excluding sensitive data). This information is crucial for tracking the requests sent by the service and identifying any issues that may arise.
- Response Logging: All responses received from the CardNet API should be logged. The log entry should include a timestamp, the response code, the response headers, and the response body (excluding sensitive data). This information is essential for understanding how the CardNet API responded to each request and for identifying any errors or issues.
- Data Sensitivity: Sensitive data, such as card numbers and session keys, should not be logged. Instead, unique identifiers or masked versions of the data should be used to maintain compliance with data protection regulations. The logging mechanism should be designed to ensure that sensitive data is never exposed in the logs.
Curl Example
The following curl command demonstrates how to create a session using the CardNet API:
curl --location 'https://lab.cardnet.com.do/sessions' \
--header 'Content-Type: application/json' \
--header 'Cookie: visid_incap_2647163=S4sDnTHERDmSdt+AMzLkVT7hWmgAAAAAQUIPAAAAAADfLew5tciQHg7vVnYd/Xyr' \
--data '{
"TransactionType": "200",
"CurrencyCode": "2145",
"AcquiringInstitutionCode": "349",
"MerchantType": "7997",
"MerchantNumber": "349000000",
"MerchantTerminal": "58585858",
"MerchantTerminal_amex": "00000001",
"ReturnUrl": "https://taylorasprilla.dev ",
"CancelUrl": "https://taylorasprilla.dev ",
"PageLanguaje": "ESP",
"OrdenId": "689",
"TransactionId": "14580",
"Tax": "100",
"MerchantName": "Congregación Mita RD",
"AVS": "33024 1000 ST JOHN PLACE PEMBROKE PINES FLORIDA",
"Amount": "1000"
}'
Explanation of Curl Command
curl --location 'https://lab.cardnet.com.do/sessions'
- This specifies the URL endpoint for creating a session in CardNet's lab environment. The
--location
flag is used to follow any HTTP redirects.
- This specifies the URL endpoint for creating a session in CardNet's lab environment. The
--header 'Content-Type: application/json'
- Sets the content type header to
application/json
, indicating that the request body is in JSON format.
- Sets the content type header to
--header 'Cookie: visid_incap_2647163=...'
- Includes a cookie in the request headers. This cookie might be required for session management or authentication purposes.
--data '{...}'
- Provides the JSON payload as the request body. This payload includes all the necessary information for creating a payment session.
- JSON Payload Details:
TransactionType
: Specifies the type of transaction.CurrencyCode
: Indicates the currency code (2145 for Dominican Peso).AcquiringInstitutionCode
: The code for the acquiring institution.MerchantType
: The type of merchant.MerchantNumber
: The merchant's unique identifier.MerchantTerminal
: The merchant's terminal identifier.MerchantTerminal_amex
: The merchant's terminal identifier for AMEX transactions.ReturnUrl
: The URL to redirect the user after a successful transaction.CancelUrl
: The URL to redirect the user if the transaction is canceled.PageLanguaje
: The language for the payment page.OrdenId
: A unique order identifier.TransactionId
: A unique transaction identifier.Tax
: The tax amount.MerchantName
: The name of the merchant.AVS
: Address Verification System details.Amount
: The transaction amount in centavos.
Documentation
Additional documentation is attached, providing further details on the CardNet API and its functionalities. This documentation should be consulted for a comprehensive understanding of the API and its capabilities. This documentation includes detailed information on request parameters, response formats, error codes, and other relevant topics.
Conclusion
Implementing the CardNet API for payment session creation involves careful attention to detail across various aspects, including request structure, response handling, security, and auditing. By adhering to the acceptance criteria and following the implementation guidelines outlined in this document, we can create a robust, secure, and efficient service for initiating payment transactions from our platform. This service will not only streamline the payment process but also ensure the security and integrity of financial transactions.