# Create API Key Source: https://digitzs.mintlify.app/api-reference/authorization/create-key POST /auth/key Generate an app key for your application to create access tokens ## Endpoint ``` POST https://api.digitzs.com/auth/key ``` ## Overview Use this endpoint to generate an app key for your application. The app key is required to create access tokens via the `/auth/token` endpoint. Creating a new app key renders the previous key unusable. Plan key rotation carefully to avoid service disruption. ## Authentication This endpoint requires only the `x-api-key` header. No Bearer token is needed. | Header | Value | Required | | -------------- | ---------------------------- | -------- | | `x-api-key` | Your API key from onboarding | Yes | | `Content-Type` | `application/json` | Yes | ## Request Body Container for API data Must be `"auth"` Container for authentication attributes Your application ID provided during onboarding ### Example Request ```json theme={null} { "data": { "type": "auth", "attributes": { "appId": "your-application-id" } } } ``` ## Response ### Success Response (201 Created) Contains URLs related to the resource URL of the current endpoint Container for response data Resource type - will be `"auth"` Your API key (same as the x-api-key header) Generated app key for creating access tokens ### Example Response ```json theme={null} { "links": { "self": "https://api.digitzs.com/auth/key" }, "data": { "type": "auth", "id": "api-key-xyz", "attributes": { "appKey": "generated-app-key-abc123" } } } ``` ## Code Examples ```bash cURL theme={null} curl -X POST https://api.digitzs.com/auth/key \ -H "x-api-key: your-api-key" \ -H "Content-Type: application/json" \ -d '{ "data": { "type": "auth", "attributes": { "appId": "your-application-id" } } }' ``` ```javascript JavaScript theme={null} const axios = require('axios'); async function createAppKey() { const response = await axios.post( 'https://api.digitzs.com/auth/key', { data: { type: 'auth', attributes: { appId: 'your-application-id' } } }, { headers: { 'x-api-key': 'your-api-key', 'Content-Type': 'application/json' } } ); const appKey = response.data.data.attributes.appKey; console.log('App Key:', appKey); return appKey; } createAppKey(); ``` ```python Python theme={null} import requests def create_app_key(): url = "https://api.digitzs.com/auth/key" headers = { "x-api-key": "your-api-key", "Content-Type": "application/json" } payload = { "data": { "type": "auth", "attributes": { "appId": "your-application-id" } } } response = requests.post(url, headers=headers, json=payload) response.raise_for_status() app_key = response.json()["data"]["attributes"]["appKey"] print(f"App Key: {app_key}") return app_key create_app_key() ``` ```php PHP theme={null} [ "type" => "auth", "attributes" => [ "appId" => "your-application-id" ] ] ]); $ch = curl_init($url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if ($httpCode === 201) { $data = json_decode($response, true); $appKey = $data["data"]["attributes"]["appKey"]; echo "App Key: " . $appKey . "\n"; return $appKey; } else { throw new Exception("Error creating app key: " . $response); } } createAppKey(); ?> ``` ```ruby Ruby theme={null} require 'net/http' require 'json' require 'uri' def create_app_key uri = URI('https://api.digitzs.com/auth/key') request = Net::HTTP::Post.new(uri) request['x-api-key'] = 'your-api-key' request['Content-Type'] = 'application/json' request.body = { data: { type: 'auth', attributes: { appId: 'your-application-id' } } }.to_json response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http| http.request(request) end if response.code == '201' data = JSON.parse(response.body) app_key = data['data']['attributes']['appKey'] puts "App Key: #{app_key}" app_key else raise "Error creating app key: #{response.body}" end end create_app_key ``` ## Error Responses ```json 400 Bad Request theme={null} { "errors": [ { "status": "400", "title": "Bad Request", "detail": "The appId field is required", "source": { "pointer": "/data/attributes/appId" } } ] } ``` ```json 401 Unauthorized theme={null} { "errors": [ { "status": "401", "title": "Unauthorized", "detail": "Invalid API key" } ] } ``` ```json 403 Forbidden theme={null} { "errors": [ { "status": "403", "title": "Forbidden", "detail": "The account is not authorized" } ] } ``` ## Common Error Scenarios **Error:** 401 Unauthorized **Solution:** Ensure the `x-api-key` header is included in the request with your valid API key. **Error:** 400 Bad Request **Solution:** Verify your application ID matches the ID provided during onboarding. **Error:** 403 Forbidden **Solution:** Contact Digitzs support to check your account status. ## Best Practices **Store Securely:** Save the returned app key in a secure location (environment variable or secret management service). You'll need it to generate access tokens. **Key Rotation:** When creating a new app key, the previous key becomes invalid immediately. Ensure all services are updated before rotating keys. ## Next Steps After creating an app key, use it to generate an access token: Generate an access token using your app key # Create App Token Source: https://digitzs.mintlify.app/api-reference/authorization/create-token POST /auth/token Generate a temporary access token for authenticating API requests ## Endpoint ``` POST https://api.digitzs.com/auth/token ``` ## Overview Use this endpoint to generate a temporary access token (app token) using your app key. This token is required for all subsequent API calls and expires after one hour. **Tokens expire after one hour.** Implement token refresh logic to avoid authentication failures. ## Authentication This endpoint requires the `x-api-key` header but not a Bearer token. | Header | Value | Required | | -------------- | ---------------------------- | -------- | | `x-api-key` | Your API key from onboarding | Yes | | `Content-Type` | `application/json` | Yes | ## Request Body Container for API data Must be `"auth"` Container for authentication attributes The app key obtained from `/auth/key` endpoint ### Example Request ```json theme={null} { "data": { "type": "auth", "attributes": { "appKey": "your-app-key-from-auth-key-endpoint" } } } ``` ## Response ### Success Response (201 Created) Contains URLs related to the resource Container for response data Resource type - will be `"auth"` Your API key **The access token to use in your API requests.** This token expires after 1 hour. Use this token in the `Authorization` header as: `Bearer {appToken}` ### Example Response ```json theme={null} { "links": { "self": "https://api.digitzs.com/auth/token" }, "data": { "type": "auth", "id": "api-key-xyz", "attributes": { "appToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c" } } } ``` ## Using the Token Include the token in all authenticated API requests: ```bash theme={null} curl -X GET https://api.digitzs.com/merchants \ -H "Authorization: Bearer your-app-token" \ -H "x-api-key: your-api-key" \ -H "appId: your-app-id" ``` The `Authorization` header must be formatted as `Bearer {token}` with a capital "B" and a space between "Bearer" and your token. ## Code Examples ```bash cURL theme={null} curl -X POST https://api.digitzs.com/auth/token \ -H "x-api-key: your-api-key" \ -H "Content-Type: application/json" \ -d '{ "data": { "type": "auth", "attributes": { "appKey": "your-app-key" } } }' ``` ```javascript JavaScript theme={null} const axios = require('axios'); async function createAppToken(appKey) { const response = await axios.post( 'https://api.digitzs.com/auth/token', { data: { type: 'auth', attributes: { appKey: appKey } } }, { headers: { 'x-api-key': 'your-api-key', 'Content-Type': 'application/json' } } ); const appToken = response.data.data.attributes.appToken; const expiresAt = Date.now() + (60 * 60 * 1000); // 1 hour from now console.log('App Token:', appToken); console.log('Expires at:', new Date(expiresAt).toISOString()); return { appToken, expiresAt }; } // Usage createAppToken('your-app-key'); ``` ```python Python theme={null} import requests from datetime import datetime, timedelta def create_app_token(app_key): url = "https://api.digitzs.com/auth/token" headers = { "x-api-key": "your-api-key", "Content-Type": "application/json" } payload = { "data": { "type": "auth", "attributes": { "appKey": app_key } } } response = requests.post(url, headers=headers, json=payload) response.raise_for_status() app_token = response.json()["data"]["attributes"]["appToken"] expires_at = datetime.now() + timedelta(hours=1) print(f"App Token: {app_token}") print(f"Expires at: {expires_at.isoformat()}") return { "app_token": app_token, "expires_at": expires_at } # Usage create_app_token("your-app-key") ``` ```php PHP theme={null} [ "type" => "auth", "attributes" => [ "appKey" => $appKey ] ] ]); $ch = curl_init($url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if ($httpCode === 201) { $data = json_decode($response, true); $appToken = $data["data"]["attributes"]["appToken"]; $expiresAt = date('Y-m-d H:i:s', strtotime('+1 hour')); echo "App Token: " . $appToken . "\n"; echo "Expires at: " . $expiresAt . "\n"; return [ "appToken" => $appToken, "expiresAt" => $expiresAt ]; } else { throw new Exception("Error creating app token: " . $response); } } createAppToken("your-app-key"); ?> ``` ```ruby Ruby theme={null} require 'net/http' require 'json' require 'uri' def create_app_token(app_key) uri = URI('https://api.digitzs.com/auth/token') request = Net::HTTP::Post.new(uri) request['x-api-key'] = 'your-api-key' request['Content-Type'] = 'application/json' request.body = { data: { type: 'auth', attributes: { appKey: app_key } } }.to_json response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http| http.request(request) end if response.code == '201' data = JSON.parse(response.body) app_token = data['data']['attributes']['appToken'] expires_at = Time.now + (60 * 60) # 1 hour from now puts "App Token: #{app_token}" puts "Expires at: #{expires_at.iso8601}" { app_token: app_token, expires_at: expires_at } else raise "Error creating app token: #{response.body}" end end create_app_token('your-app-key') ``` ## Token Management ### Automatic Refresh Implement automatic token refresh logic to avoid authentication failures: ```javascript theme={null} class TokenManager { constructor(apiKey, appKey) { this.apiKey = apiKey; this.appKey = appKey; this.token = null; this.expiresAt = null; } async getToken() { // Refresh if token is missing or expires in less than 5 minutes const refreshBuffer = 5 * 60 * 1000; // 5 minutes const shouldRefresh = !this.token || Date.now() >= (this.expiresAt - refreshBuffer); if (shouldRefresh) { await this.refreshToken(); } return this.token; } async refreshToken() { const response = await axios.post( 'https://api.digitzs.com/auth/token', { data: { type: 'auth', attributes: { appKey: this.appKey } } }, { headers: { 'x-api-key': this.apiKey, 'Content-Type': 'application/json' } } ); this.token = response.data.data.attributes.appToken; this.expiresAt = Date.now() + (60 * 60 * 1000); // 1 hour } } // Usage const tokenManager = new TokenManager('your-api-key', 'your-app-key'); const token = await tokenManager.getToken(); // Automatically refreshes if needed ``` ## Error Responses ```json 400 Bad Request theme={null} { "errors": [ { "status": "400", "title": "Bad Request", "detail": "The appKey field is required" } ] } ``` ```json 401 Unauthorized theme={null} { "errors": [ { "status": "401", "title": "Unauthorized", "detail": "Invalid app key" } ] } ``` ```json 403 Forbidden theme={null} { "errors": [ { "status": "403", "title": "Forbidden", "detail": "The account is not authorized" } ] } ``` ## Common Error Scenarios **Error:** 401 Unauthorized **Solution:** Verify your app key is correct. If you've regenerated your app key, use the new one. **Error:** 401 Unauthorized **Solution:** Generate a new app key using the `/auth/key` endpoint. **Error:** 401 Unauthorized (from other endpoints) **Solution:** Catch 401 errors and automatically refresh the token before retrying the request. ## Best Practices Store and reuse tokens for their full 1-hour lifetime to minimize API calls Refresh tokens 5 minutes before expiration to avoid service interruptions Implement automatic token refresh on 401 responses Track token expiration time and log refresh events ## Next Steps Now that you have an access token, you can start making authenticated API requests: Set up merchant accounts Accept payments Retrieve merchant data # Authorization Endpoints Source: https://digitzs.mintlify.app/api-reference/authorization/overview Generate API keys and access tokens for secure API access ## Overview The Authorization endpoints handle authentication and authorization for the Digitzs API. A two-step process is required: 1. Generate an app key using your API credentials 2. Create an access token using the app key Access tokens expire after one hour and must be refreshed regularly. ## Authorization Flow ```mermaid theme={null} sequenceDiagram participant App as Your Application participant Auth as /auth/key participant Token as /auth/token participant API as Digitzs API App->>Auth: POST /auth/key (with x-api-key, appId) Auth-->>App: Returns appKey App->>Token: POST /auth/token (with appKey) Token-->>App: Returns appToken (expires in 1 hour) App->>API: API Requests (with Bearer token) API-->>App: API Responses Note over App,Token: Token expires after 1 hour App->>Token: POST /auth/token (refresh) Token-->>App: New appToken ``` ## Endpoints Generate an app key for token creation `POST /auth/key` Generate an access token (expires in 1 hour) `POST /auth/token` ## Quick Start ### Step 1: Create App Key ```bash theme={null} curl -X POST https://api.digitzs.com/auth/key \ -H "x-api-key: your-api-key" \ -H "Content-Type: application/json" \ -d '{ "data": { "type": "auth", "attributes": { "appId": "your-app-id" } } }' ``` ### Step 2: Create App Token ```bash theme={null} curl -X POST https://api.digitzs.com/auth/token \ -H "x-api-key: your-api-key" \ -H "Content-Type: application/json" \ -d '{ "data": { "type": "auth", "attributes": { "appKey": "app-key-from-step-1" } } }' ``` ### Step 3: Use Token in Requests ```bash theme={null} curl -X GET https://api.digitzs.com/merchants \ -H "Authorization: Bearer your-app-token" \ -H "x-api-key: your-api-key" \ -H "appId: your-app-id" ``` ## Best Practices Store your API key and app key securely: * Use environment variables * Never commit credentials to version control * Use secret management services in production Cache access tokens and reuse them: * Tokens are valid for 1 hour * Track token expiration time * Refresh tokens proactively before expiration Implement robust error handling: * Catch 401 errors and refresh tokens automatically * Implement retry logic with exponential backoff * Log authentication failures for monitoring Rotate app keys periodically: * Creating a new app key invalidates the old one * Plan key rotation during low-traffic periods * Update all services using the old key ## Common Issues **Token Format:** The Authorization header must be formatted as `Bearer {token}` with: * A capital "B" in "Bearer" * A space between "Bearer" and your token **Token Expiration:** Implement automatic token refresh 5 minutes before expiration to avoid service interruptions. ## Security Considerations Always use HTTPS for API requests to protect credentials in transit Rotate API keys and app keys regularly as part of security best practices Use separate API keys for different environments (dev, staging, production) Monitor authentication failures and unusual access patterns ## Next Steps Contact Digitzs to receive your API key and application ID Follow the quick start guide to test the authentication flow Build token caching and refresh logic into your application Begin making authenticated requests to other endpoints ## Additional Resources Detailed authentication tutorial with code examples Handle authentication errors properly # Create Merchant Source: https://digitzs.mintlify.app/api-reference/merchants/create POST /merchants Create a new merchant account with full onboarding information ## Endpoint ``` POST https://api.digitzs.com/merchants ``` ## Overview Use this endpoint to create a new merchant account. This comprehensive onboarding process collects personal, business, and banking information required for payment processing. Merchant accounts are created in real-time and can begin processing payments immediately upon approval. ## Authentication | Header | Value | Required | | --------------- | ------------------- | -------- | | `x-api-key` | Your API key | Yes | | `Authorization` | `Bearer {appToken}` | Yes | | `appId` | Your application ID | Yes | | `Content-Type` | `application/json` | Yes | ## Request Body Must be `"merchants"` Merchant account attributes AVS mode: `"Standard"`, `"Strict"`, or `"Disabled"` Account type: `"personal"` or `"business"` Name for the merchant account Optional additional metadata Personal information for account holder First name Last name Email address Daytime phone number Evening phone number Date of birth (MM-DD-YYYY format) Social Security Number (SSN) Personal address Street address Address line 2 City State code ZIP code Country code Business information (required for business accounts) Legal business name Employer Identification Number (EIN) Business phone number Business email address Business website URL Business address (required for business accounts) Bank account information for deposits Name of financial institution `"personal"` or `"business"` `"checking"` or `"savings"` Account holder name Bank account number 9-digit routing number Verification and compliance data IP address of account holder during signup Whether email has been verified ISO 8601 timestamp of email verification Account holder's signature ISO 8601 timestamp of signature Must be `true` - indicates terms acceptance Fraud detection policy: `"Default"`, `"Strict"`, or `"Disabled"` ThreatMetrix session identifier for fraud screening ### Example Request ```json theme={null} { "data": { "type": "merchants", "attributes": { "AVS": "Standard", "accountType": "business", "accountName": "Acme Corporation", "personalInfo": { "firstName": "John", "lastName": "Doe", "email": "john.doe@example.com", "dayPhone": "4155551234", "eveningPhone": "4155551234", "birthDate": "01-15-1980", "socialSecurity": "123456789" }, "personalAddress": { "line1": "123 Main Street", "line2": "Suite 100", "city": "San Francisco", "state": "CA", "zip": "94102", "country": "USA" }, "businessInfo": { "businessName": "Acme Corporation", "ein": "987654321", "phone": "4155555000", "email": "info@acme.com", "url": "https://acme.com" }, "businessAddress": { "line1": "456 Market Street", "city": "San Francisco", "state": "CA", "zip": "94102", "country": "USA" }, "bankInfo": { "bankName": "Bank of America", "accountOwnership": "business", "accountType": "checking", "accountName": "Acme Corporation", "accountNumber": "1234567890", "routingNumber": "026009593" }, "verificationData": { "ipAddress": "192.168.1.1", "emailVerified": true, "emailVerifiedTimestamp": "2024-01-15T10:00:00Z", "signature": "John Doe", "signatureTimestamp": "2024-01-15T10:05:00Z", "termsAccepted": true }, "threatMetrixPolicy": "Default", "threatMetrixSessionId": "abc123session456" } } } ``` ## Response ### Success Response (201 Created) ```json theme={null} { "links": { "self": "https://api.digitzs.com/merchants" }, "data": { "type": "merchants", "id": "merchant_abc123xyz" } } ``` Unique merchant account identifier. Use this ID for all payment processing. ## Code Examples ```bash cURL theme={null} curl -X POST https://api.digitzs.com/merchants \ -H "x-api-key: your-api-key" \ -H "Authorization: Bearer your-app-token" \ -H "appId: your-app-id" \ -H "Content-Type: application/json" \ -d '{ "data": { "type": "merchants", "attributes": { "AVS": "Standard", "accountType": "business", "accountName": "Acme Corporation", "personalInfo": { ... }, "personalAddress": { ... }, "businessInfo": { ... }, "businessAddress": { ... }, "bankInfo": { ... }, "verificationData": { ... } } } }' ``` ```javascript JavaScript theme={null} const axios = require('axios'); async function createMerchant(merchantData) { const response = await axios.post( 'https://api.digitzs.com/merchants', { data: { type: 'merchants', attributes: merchantData } }, { headers: { 'x-api-key': 'your-api-key', 'Authorization': 'Bearer your-app-token', 'appId': 'your-app-id', 'Content-Type': 'application/json' } } ); const merchantId = response.data.data.id; console.log('New Merchant ID:', merchantId); return merchantId; } ``` ```python Python theme={null} import requests def create_merchant(merchant_data): url = "https://api.digitzs.com/merchants" headers = { "x-api-key": "your-api-key", "Authorization": "Bearer your-app-token", "appId": "your-app-id", "Content-Type": "application/json" } payload = { "data": { "type": "merchants", "attributes": merchant_data } } response = requests.post(url, headers=headers, json=payload) response.raise_for_status() merchant_id = response.json()["data"]["id"] print(f"New Merchant ID: {merchant_id}") return merchant_id ``` ```php PHP theme={null} [ "type" => "merchants", "attributes" => $merchantData ] ]); $ch = curl_init($url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "x-api-key: your-api-key", "Authorization: Bearer your-app-token", "appId: your-app-id", "Content-Type: application/json" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); $data = json_decode($response, true); curl_close($ch); return $data["data"]["id"]; } ?> ``` ```ruby Ruby theme={null} require 'net/http' require 'json' def create_merchant(merchant_data) uri = URI('https://api.digitzs.com/merchants') request = Net::HTTP::Post.new(uri) request['x-api-key'] = 'your-api-key' request['Authorization'] = 'Bearer your-app-token' request['appId'] = 'your-app-id' request['Content-Type'] = 'application/json' request.body = { data: { type: 'merchants', attributes: merchant_data } }.to_json response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http| http.request(request) end data = JSON.parse(response.body) data['data']['id'] end ``` ## AVS Modes | Mode | Description | | ---------- | --------------------------------------------- | | `Standard` | Requires ZIP code match for card payments | | `Strict` | Requires full address match for card payments | | `Disabled` | No AVS verification required | ## Important Notes **Sensitive Data:** This endpoint handles sensitive personal and financial information. Ensure your application uses HTTPS and follows security best practices. **Real-Time Creation:** Merchant accounts are created instantly and can process payments immediately after successful creation. **Fraud Prevention:** Use ThreatMetrix integration for enhanced fraud detection during merchant onboarding. ## Best Practices 1. **Validate Data:** Validate all fields before submission to prevent errors 2. **Secure Collection:** Use secure forms to collect sensitive information 3. **Email Verification:** Verify email addresses before creating accounts 4. **Terms Acceptance:** Ensure users explicitly accept terms and conditions 5. **IP Logging:** Record accurate IP addresses for compliance 6. **Test Mode:** Test thoroughly in sandbox before production deployment ## Next Steps Retrieve merchant account information Update merchant bank account details # Get Merchant by ID Source: https://digitzs.mintlify.app/api-reference/merchants/get-by-id GET /merchants/{id} Retrieve detailed information about a specific merchant account ## Endpoint ``` GET https://api.digitzs.com/merchants/{id} ``` ## Overview Use this endpoint to retrieve complete details of a merchant account, including personal information, business details, and bank account information. ## Authentication | Header | Value | Required | | --------------- | ------------------- | -------- | | `x-api-key` | Your API key | Yes | | `Authorization` | `Bearer {appToken}` | Yes | | `appId` | Your application ID | Yes | ## Path Parameters The merchant account ID ## Response ### Success Response (200 OK) ```json theme={null} { "links": { "self": "https://api.digitzs.com/merchants/merchant_abc123" }, "data": { "type": "merchants", "id": "merchant_abc123", "attributes": { "AVS": "Standard", "accountType": "business", "accountName": "Acme Corporation", "status": "active", "createdAt": "2024-01-15T10:00:00Z", "personalInfo": { "firstName": "John", "lastName": "Doe", "email": "john.doe@example.com", "dayPhone": "4155551234" }, "businessInfo": { "businessName": "Acme Corporation", "ein": "***4321", "email": "info@acme.com", "url": "https://acme.com" }, "bankInfo": { "bankName": "Bank of America", "accountType": "checking", "last4": "7890" } } } } ``` **Sensitive Data Masked:** SSN, EIN, and full account numbers are masked in responses for security. ## Code Examples ```bash cURL theme={null} curl -X GET https://api.digitzs.com/merchants/merchant_abc123 \ -H "x-api-key: your-api-key" \ -H "Authorization: Bearer your-app-token" \ -H "appId: your-app-id" ``` ```javascript JavaScript theme={null} const axios = require('axios'); async function getMerchant(merchantId) { const response = await axios.get( `https://api.digitzs.com/merchants/${merchantId}`, { headers: { 'x-api-key': 'your-api-key', 'Authorization': 'Bearer your-app-token', 'appId': 'your-app-id' } } ); console.log('Merchant:', response.data.data.attributes.accountName); return response.data; } ``` ```python Python theme={null} import requests def get_merchant(merchant_id): url = f"https://api.digitzs.com/merchants/{merchant_id}" headers = { "x-api-key": "your-api-key", "Authorization": "Bearer your-app-token", "appId": "your-app-id" } response = requests.get(url, headers=headers) response.raise_for_status() return response.json() ``` ```php PHP theme={null} ``` ```ruby Ruby theme={null} require 'net/http' require 'json' def get_merchant(merchant_id) uri = URI("https://api.digitzs.com/merchants/#{merchant_id}") request = Net::HTTP::Get.new(uri) request['x-api-key'] = 'your-api-key' request['Authorization'] = 'Bearer your-app-token' request['appId'] = 'your-app-id' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http| http.request(request) end JSON.parse(response.body) end ``` ## Merchant Status Values | Status | Description | | ----------- | ----------------------------- | | `active` | Merchant can process payments | | `pending` | Merchant account under review | | `suspended` | Account temporarily suspended | | `closed` | Account permanently closed | ## Next Steps View all merchant accounts # List Merchants Source: https://digitzs.mintlify.app/api-reference/merchants/list GET /merchants Retrieve a list of merchant accounts ## Endpoint ``` GET https://api.digitzs.com/merchants ``` ## Overview Use this endpoint to retrieve a paginated list of all merchant accounts associated with your application. ## Authentication | Header | Value | Required | | --------------- | ------------------- | -------- | | `x-api-key` | Your API key | Yes | | `Authorization` | `Bearer {appToken}` | Yes | | `appId` | Your application ID | Yes | ## Query Parameters Number of results per page (default: 25, max: 100) Number of results to skip for pagination (default: 0) Filter by status: `active`, `pending`, `suspended`, `closed` ## Response ### Success Response (200 OK) ```json theme={null} { "links": { "self": "https://api.digitzs.com/merchants?limit=25", "next": "https://api.digitzs.com/merchants?limit=25&offset=25" }, "data": [ { "type": "merchants", "id": "merchant_abc123", "attributes": { "accountName": "Acme Corporation", "accountType": "business", "status": "active", "createdAt": "2024-01-15T10:00:00Z", "email": "info@acme.com" } }, { "type": "merchants", "id": "merchant_xyz789", "attributes": { "accountName": "Bob's Shop", "accountType": "personal", "status": "active", "createdAt": "2024-01-10T14:30:00Z", "email": "bob@shop.com" } } ], "meta": { "total": 156, "limit": 25, "offset": 0, "hasMore": true } } ``` ## Code Examples ```bash cURL theme={null} curl -X GET "https://api.digitzs.com/merchants?limit=25" \ -H "x-api-key: your-api-key" \ -H "Authorization: Bearer your-app-token" \ -H "appId: your-app-id" ``` ```javascript JavaScript theme={null} const axios = require('axios'); async function listMerchants(options = {}) { const params = new URLSearchParams({ limit: options.limit || 25, offset: options.offset || 0, ...options.filters }); const response = await axios.get( `https://api.digitzs.com/merchants?${params}`, { headers: { 'x-api-key': 'your-api-key', 'Authorization': 'Bearer your-app-token', 'appId': 'your-app-id' } } ); console.log(`Retrieved ${response.data.data.length} merchants`); return response.data; } // Get active merchants listMerchants({ filters: { status: 'active' } }); ``` ```python Python theme={null} import requests def list_merchants(limit=25, offset=0, **filters): url = "https://api.digitzs.com/merchants" params = { "limit": limit, "offset": offset, **filters } headers = { "x-api-key": "your-api-key", "Authorization": "Bearer your-app-token", "appId": "your-app-id" } response = requests.get(url, headers=headers, params=params) return response.json() # Get active merchants list_merchants(status="active") ``` ```php PHP theme={null} 25, 'offset' => 0 ], $options); $url = "https://api.digitzs.com/merchants?" . http_build_query($params); $ch = curl_init($url); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "x-api-key: your-api-key", "Authorization: Bearer your-app-token", "appId: your-app-id" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); return json_decode(curl_exec($ch), true); } ?> ``` ```ruby Ruby theme={null} require 'net/http' require 'json' def list_merchants(options = {}) params = { limit: options[:limit] || 25, offset: options[:offset] || 0 }.merge(options[:filters] || {}) uri = URI('https://api.digitzs.com/merchants') uri.query = URI.encode_www_form(params) request = Net::HTTP::Get.new(uri) request['x-api-key'] = 'your-api-key' request['Authorization'] = 'Bearer your-app-token' request['appId'] = 'your-app-id' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http| http.request(request) end JSON.parse(response.body) end ``` ## Next Steps Create a new merchant account # Merchant Endpoints Source: https://digitzs.mintlify.app/api-reference/merchants/overview Create and manage merchant accounts for processing payments ## Overview The Merchant endpoints allow you to create, update, and manage merchant accounts within your application. Merchants can be created in real-time, enabling your users to start accepting payments immediately without leaving your platform. Merchants pay a flat rate of 2.9% + 30¢ per transaction with no hidden fees or surprise charges. ## Key Features Create merchant accounts instantly without manual approval Update settings, bank info, and preferences programmatically Eligible merchants can receive funds instantly with qualified debit cards ## Available Endpoints Create a new merchant account `POST /merchants` Retrieve merchant details `GET /merchants/{id}` Get all merchants in your account `GET /merchants` Update merchant banking information `PUT /merchants/{id}` Configure Address Verification Service settings `PUT /merchants/{id}` ## Quick Start ### Create a Merchant ```bash theme={null} curl -X POST https://api.digitzs.com/merchants \ -H "Authorization: Bearer your-app-token" \ -H "x-api-key: your-api-key" \ -H "appId: your-app-id" \ -H "Content-Type: application/json" \ -d '{ "data": { "type": "merchants", "attributes": { "businessInfo": { "businessName": "Acme Corporation", "businessType": "LLC", "taxId": "12-3456789", "phoneNumber": "555-123-4567", "website": "https://acme.example.com" }, "contactInfo": { "firstName": "John", "lastName": "Doe", "email": "john@acme.example.com", "phone": "555-123-4567" }, "address": { "street": "123 Main St", "city": "San Francisco", "state": "CA", "postalCode": "94105", "country": "US" }, "bankInfo": { "accountName": "Acme Corporation", "accountNumber": "1234567890", "routingNumber": "026009593", "accountType": "checking" } } } }' ``` ### List Merchants ```bash theme={null} curl -X GET https://api.digitzs.com/merchants \ -H "Authorization: Bearer your-app-token" \ -H "x-api-key: your-api-key" \ -H "appId: your-app-id" ``` ## Merchant Lifecycle ```mermaid theme={null} sequenceDiagram participant User participant App as Your Application participant API as Digitzs API participant Merchant User->>App: Register Business App->>API: POST /merchants API-->>App: Merchant Created (201) App-->>User: Account Active User->>App: Update Bank Info App->>API: PUT /merchants/{id} API-->>App: Bank Info Updated (200) Note over Merchant: Ready to accept payments User->>App: Process Payment App->>API: POST /payments API-->>Merchant: Funds Deposited ``` ## Merchant Data Structure ### Business Information | Field | Description | | -------------- | ----------------------------------------------------- | | `businessName` | Legal business name | | `businessType` | Entity type (LLC, Corporation, Sole Proprietor, etc.) | | `taxId` | Federal Tax ID or EIN | | `phoneNumber` | Business phone number | | `website` | Business website URL (optional) | ### Contact Information | Field | Description | | ----------- | --------------------------- | | `firstName` | Contact person's first name | | `lastName` | Contact person's last name | | `email` | Contact email address | | `phone` | Contact phone number | ### Bank Information | Field | Description | | --------------- | ---------------------------------- | | `accountName` | Name on the bank account | | `accountNumber` | Bank account number | | `routingNumber` | Bank routing number (ABA) | | `accountType` | Account type (checking or savings) | ### Address Information | Field | Description | | ------------ | ---------------------------------- | | `street` | Street address | | `city` | City name | | `state` | State code (2 letters) | | `postalCode` | ZIP or postal code | | `country` | Country code (2 letters, e.g., US) | ## Address Verification Service (AVS) AVS helps prevent fraud by verifying the cardholder's billing address matches the address on file with the card issuer. ### AVS Modes | Mode | Description | | ---------- | ------------------------------------------------- | | `strict` | Reject transactions if AVS check fails | | `moderate` | Flag suspicious transactions but allow processing | | `lenient` | Log AVS results but don't block transactions | | `off` | Disable AVS checking | Disabling AVS increases fraud risk. Use strict or moderate mode for best security. ## Merchant Status | Status | Description | | ----------- | ---------------------------- | | `active` | Merchant can accept payments | | `pending` | Account under review | | `suspended` | Account temporarily disabled | | `closed` | Account permanently closed | ## Testing ### Test Mode When using test credentials, you can create test merchants without real business verification: ```json theme={null} { "data": { "type": "merchants", "attributes": { "businessInfo": { "businessName": "Test Business", "businessType": "Sole Proprietor", "taxId": "00-0000000" }, ... } } } ``` ## Revenue Sharing As a platform using Digitzs, you earn revenue on every transaction processed by your merchants: Configure your platform fee percentage or fixed amount per transaction. Fees are automatically deducted and deposited to your account. Use split payments to automatically distribute funds between the merchant and your platform without manual invoicing. Track your platform revenue in real-time with detailed reporting and analytics. ## Compliance and Verification Merchants must provide valid business and identity information for compliance Bank account details are verified during merchant onboarding Digitzs handles tax reporting and 1099 generation for merchants Automated fraud detection and risk assessment for all merchants ## Best Practices * Verify email addresses are valid * Validate phone numbers are properly formatted * Check tax IDs match business entity type * Ensure routing numbers are valid ABA numbers * Save the returned merchant ID with your user record * Use the merchant ID for all payment operations * Don't expose internal merchant IDs to end users * Some fields cannot be updated after creation * Bank info updates may require reverification * Notify merchants of any changes to their account * Regularly check merchant account status * Handle suspended or closed accounts appropriately * Notify merchants of any status changes ## Common Use Cases **Scenario:** Multi-vendor marketplace where sellers need to accept payments **Implementation:** 1. Create merchant account when seller registers 2. Store merchant ID with seller profile 3. Use merchant ID when processing orders 4. Use split payments to collect platform fees **Benefits:** * Sellers get paid directly * Automatic fee collection * No manual payouts needed **Scenario:** Service providers need to receive payments from customers **Implementation:** 1. Create merchant account for each service provider 2. Process payments with provider's merchant ID 3. Use instant funding for urgent cases 4. Handle refunds for cancellations **Benefits:** * Fast provider payouts * Built-in refund handling * Automated fee collection **Scenario:** Multiple parties receive portions of each sale **Implementation:** 1. Create merchant accounts for sellers 2. Use multiple split payments 3. Distribute to seller, platform, and affiliates 4. Track commissions automatically **Benefits:** * Automatic commission splitting * Real-time revenue tracking * No manual calculations needed ## Error Handling Common merchant creation errors and solutions: | Error | Cause | Solution | | ---------------------- | ----------------------------- | ------------------------------------ | | Invalid Tax ID | Tax ID format incorrect | Verify format matches entity type | | Invalid Routing Number | Routing number not recognized | Use valid 9-digit ABA routing number | | Duplicate Merchant | Email or Tax ID already used | Check for existing merchant account | | Missing Required Field | Required field omitted | Include all mandatory fields | ## Next Steps Use test credentials to create a merchant account Save the merchant ID with your user record Use the merchant ID to process a test payment Check that funds are properly distributed ## Additional Resources Process payments for your merchants Handle merchant creation errors # Update Merchant AVS Mode Source: https://digitzs.mintlify.app/api-reference/merchants/update-avs-mode PUT /merchants/{id}/avsMode Update the Address Verification System (AVS) mode for a merchant ## Endpoint ``` PUT https://api.digitzs.com/merchants/{id} ``` ## Overview Use this endpoint to update the AVS (Address Verification System) verification mode for a merchant account. AVS helps prevent fraudulent card transactions by verifying the cardholder's billing address. ## Authentication | Header | Value | Required | | --------------- | ------------------- | -------- | | `x-api-key` | Your API key | Yes | | `Authorization` | `Bearer {appToken}` | Yes | | `appId` | Your application ID | Yes | | `Content-Type` | `application/json` | Yes | ## Path Parameters The merchant account ID ## Request Body Must be `"merchants"` Must be `"AVS"` AVS mode to set: * `"Standard"` - Requires ZIP code match * `"Strict"` - Requires full address match * `"Disabled"` - No AVS verification ### Example Request ```json theme={null} { "data": { "type": "merchants", "attributes": { "group": "AVS", "AVS": "Strict" } } } ``` ## Response ### Success Response (200 OK) ```json theme={null} { "links": { "self": "https://api.digitzs.com/merchants/merchant_abc123" }, "data": { "type": "merchants", "id": "merchant_abc123", "attributes": { "AVS": "Strict", "updatedAt": "2024-01-20T16:00:00Z" } } } ``` ## Code Examples ```bash cURL theme={null} curl -X PUT https://api.digitzs.com/merchants/merchant_abc123 \ -H "x-api-key: your-api-key" \ -H "Authorization: Bearer your-app-token" \ -H "appId: your-app-id" \ -H "Content-Type: application/json" \ -d '{ "data": { "type": "merchants", "attributes": { "group": "AVS", "AVS": "Strict" } } }' ``` ```javascript JavaScript theme={null} const axios = require('axios'); async function updateMerchantAVS(merchantId, avsMode) { const response = await axios.put( `https://api.digitzs.com/merchants/${merchantId}`, { data: { type: 'merchants', attributes: { group: 'AVS', AVS: avsMode } } }, { headers: { 'x-api-key': 'your-api-key', 'Authorization': 'Bearer your-app-token', 'appId': 'your-app-id', 'Content-Type': 'application/json' } } ); console.log(`AVS mode updated to: ${avsMode}`); return response.data; } // Set to strict mode updateMerchantAVS('merchant_abc123', 'Strict'); ``` ```python Python theme={null} import requests def update_merchant_avs(merchant_id, avs_mode): url = f"https://api.digitzs.com/merchants/{merchant_id}" headers = { "x-api-key": "your-api-key", "Authorization": "Bearer your-app-token", "appId": "your-app-id", "Content-Type": "application/json" } payload = { "data": { "type": "merchants", "attributes": { "group": "AVS", "AVS": avs_mode } } } response = requests.put(url, headers=headers, json=payload) response.raise_for_status() print(f"AVS mode updated to: {avs_mode}") return response.json() # Set to strict mode update_merchant_avs("merchant_abc123", "Strict") ``` ```php PHP theme={null} [ "type" => "merchants", "attributes" => [ "group" => "AVS", "AVS" => $avsMode ] ] ]); $ch = curl_init($url); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "x-api-key: your-api-key", "Authorization: Bearer your-app-token", "appId: your-app-id", "Content-Type: application/json" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); echo "AVS mode updated to: $avsMode\n"; return json_decode($response, true); } // Set to strict mode updateMerchantAVS("merchant_abc123", "Strict"); ?> ``` ```ruby Ruby theme={null} require 'net/http' require 'json' def update_merchant_avs(merchant_id, avs_mode) uri = URI("https://api.digitzs.com/merchants/#{merchant_id}") request = Net::HTTP::Put.new(uri) request['x-api-key'] = 'your-api-key' request['Authorization'] = 'Bearer your-app-token' request['appId'] = 'your-app-id' request['Content-Type'] = 'application/json' request.body = { data: { type: 'merchants', attributes: { group: 'AVS', AVS: avs_mode } } }.to_json response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http| http.request(request) end puts "AVS mode updated to: #{avs_mode}" JSON.parse(response.body) end # Set to strict mode update_merchant_avs('merchant_abc123', 'Strict') ``` ## AVS Mode Comparison | Mode | Verification Level | Fraud Protection | Customer Friction | Best For | | ------------ | ------------------ | ---------------- | ----------------- | -------------------------------------------- | | **Disabled** | None | Low | None | Low-risk businesses, high trust environments | | **Standard** | ZIP code match | Medium | Low | Most businesses, balanced approach | | **Strict** | Full address match | High | Medium | High-risk categories, maximum security | ## Understanding AVS **Requirements:** ZIP/postal code must match billing address on file with card issuer **Pros:** * Good fraud prevention * Minimal customer friction * Industry standard **Cons:** * Won't catch address fraud if ZIP is correct **Recommended for:** General e-commerce, most businesses **Requirements:** Street address AND ZIP code must match **Pros:** * Maximum fraud prevention * Comprehensive address verification * Protects high-value transactions **Cons:** * Higher false decline rate * More customer friction * Legitimate typos cause failures **Recommended for:** High-value items, high-risk industries, luxury goods **Requirements:** No address verification **Pros:** * No customer friction * Faster checkout * No legitimate decline from AVS **Cons:** * Minimal fraud protection * Higher chargeback risk * May violate compliance requirements **Recommended for:** Known customers, trusted environments, low-risk scenarios ## Important Notes **Fraud Risk:** Disabling AVS increases fraud risk. Only disable if you have alternative fraud prevention measures in place. **Immediate Effect:** AVS mode changes apply immediately to all new transactions. In-flight transactions use the mode active at the time they were initiated. **Balance Security and Conversion:** Standard mode provides good security while minimizing false declines. Start with Standard and adjust based on fraud patterns. ## Best Practices 1. **Monitor Fraud Rates:** Track chargeback rates after AVS changes 2. **Consider Your Industry:** High-risk industries should use Strict mode 3. **Test Changes:** Test AVS impact on legitimate transactions before switching modes 4. **Customer Communication:** Inform customers about address verification requirements 5. **Gradual Changes:** When increasing strictness, monitor conversion rates closely ## When to Use Each Mode **Use Standard when:** * Running general e-commerce * Balancing security and conversion * Processing medium-value transactions **Use Strict when:** * Selling high-value items (\$500+) * Operating in high-fraud industries * Experiencing elevated chargeback rates * Regulatory requirements demand it **Use Disabled when:** * Processing known/trusted customers * Running internal testing * Accepting only low-value transactions * Having comprehensive alternative fraud tools ## Next Steps Verify updated AVS settings Process payments with your AVS configuration # Update Merchant Bank Info Source: https://digitzs.mintlify.app/api-reference/merchants/update-bank-info PUT /merchants/{id}/bankInfo Update the bank account information for a merchant ## Endpoint ``` PUT https://api.digitzs.com/merchants/{id} ``` ## Overview Use this endpoint to update a merchant's bank account information used for receiving payment deposits. Changing bank information affects where funds are deposited. Verify all details carefully before submitting. ## Authentication | Header | Value | Required | | --------------- | ------------------- | -------- | | `x-api-key` | Your API key | Yes | | `Authorization` | `Bearer {appToken}` | Yes | | `appId` | Your application ID | Yes | | `Content-Type` | `application/json` | Yes | ## Path Parameters The merchant account ID ## Request Body Must be `"merchants"` Must be `"bankInfo"` New bank account information Name of financial institution `"personal"` or `"business"` `"checking"` or `"savings"` Account holder name Bank account number 9-digit routing number ### Example Request ```json theme={null} { "data": { "type": "merchants", "attributes": { "group": "bankInfo", "bankInfo": { "bankName": "Chase Bank", "accountOwnership": "business", "accountType": "checking", "accountName": "Acme Corporation", "accountNumber": "9876543210", "routingNumber": "026009593" } } } } ``` ## Response ### Success Response (200 OK) ```json theme={null} { "links": { "self": "https://api.digitzs.com/merchants/merchant_abc123" }, "data": { "type": "merchants", "id": "merchant_abc123", "attributes": { "bankInfo": { "bankName": "Chase Bank", "accountType": "checking", "last4": "3210", "updatedAt": "2024-01-20T15:30:00Z" } } } } ``` ## Code Examples ```bash cURL theme={null} curl -X PUT https://api.digitzs.com/merchants/merchant_abc123 \ -H "x-api-key: your-api-key" \ -H "Authorization: Bearer your-app-token" \ -H "appId: your-app-id" \ -H "Content-Type: application/json" \ -d '{ "data": { "type": "merchants", "attributes": { "group": "bankInfo", "bankInfo": { "bankName": "Chase Bank", "accountOwnership": "business", "accountType": "checking", "accountName": "Acme Corporation", "accountNumber": "9876543210", "routingNumber": "026009593" } } } }' ``` ```javascript JavaScript theme={null} const axios = require('axios'); async function updateMerchantBankInfo(merchantId, bankInfo) { const response = await axios.put( `https://api.digitzs.com/merchants/${merchantId}`, { data: { type: 'merchants', attributes: { group: 'bankInfo', bankInfo: bankInfo } } }, { headers: { 'x-api-key': 'your-api-key', 'Authorization': 'Bearer your-app-token', 'appId': 'your-app-id', 'Content-Type': 'application/json' } } ); console.log('Bank info updated successfully'); return response.data; } ``` ```python Python theme={null} import requests def update_merchant_bank_info(merchant_id, bank_info): url = f"https://api.digitzs.com/merchants/{merchant_id}" headers = { "x-api-key": "your-api-key", "Authorization": "Bearer your-app-token", "appId": "your-app-id", "Content-Type": "application/json" } payload = { "data": { "type": "merchants", "attributes": { "group": "bankInfo", "bankInfo": bank_info } } } response = requests.put(url, headers=headers, json=payload) response.raise_for_status() return response.json() ``` ```php PHP theme={null} [ "type" => "merchants", "attributes" => [ "group" => "bankInfo", "bankInfo" => $bankInfo ] ] ]); $ch = curl_init($url); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "x-api-key: your-api-key", "Authorization: Bearer your-app-token", "appId: your-app-id", "Content-Type: application/json" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); return json_decode(curl_exec($ch), true); } ?> ``` ```ruby Ruby theme={null} require 'net/http' require 'json' def update_merchant_bank_info(merchant_id, bank_info) uri = URI("https://api.digitzs.com/merchants/#{merchant_id}") request = Net::HTTP::Put.new(uri) request['x-api-key'] = 'your-api-key' request['Authorization'] = 'Bearer your-app-token' request['appId'] = 'your-app-id' request['Content-Type'] = 'application/json' request.body = { data: { type: 'merchants', attributes: { group: 'bankInfo', bankInfo: bank_info } } }.to_json response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http| http.request(request) end JSON.parse(response.body) end ``` ## Important Notes **Verification Required:** New bank accounts may require verification before funds can be deposited. Check with Digitzs support for verification procedures. **Pending Deposits:** Existing pending deposits will complete to the old account. Only new deposits use the updated account. **Double Check:** Verify routing and account numbers carefully. Incorrect information will cause deposit failures. ## Best Practices 1. **Validate Before Update:** Verify bank details with merchant before submission 2. **Notify Merchant:** Inform merchant of bank account changes 3. **Audit Trail:** Log all bank account updates for compliance 4. **Test Deposits:** Consider micro-deposit verification for added security ## Next Steps Verify updated bank information # API Reference Source: https://digitzs.mintlify.app/api-reference/overview Complete reference documentation for the Digitzs API ## Base URL All API requests should be made to: ``` https://api.digitzs.com ``` The Digitzs API follows REST principles and returns JSON-formatted responses. ## API Sections The Digitzs API is organized into three main sections: Generate API keys and access tokens Process and manage payment transactions Create and manage merchant accounts ## Authentication All API requests (except authorization endpoints) require authentication using three headers: | Header | Description | Required For | | --------------- | ---------------------------------------- | -------------------------------- | | `x-api-key` | Your API key from onboarding | All endpoints | | `Authorization` | Bearer token format: `Bearer {appToken}` | All endpoints except `/auth/key` | | `appId` | Your application ID from onboarding | Payment and merchant endpoints | | `Content-Type` | Should be `application/json` | All POST/PUT requests | App tokens expire after one hour. Implement token refresh logic in your application. See the [Authentication Guide](/authentication) for details. ## Request Format ### JSON API Specification The Digitzs API follows the JSON API specification for request and response formatting: ```json theme={null} { "data": { "type": "resource-type", "id": "resource-id", "attributes": { "field1": "value1", "field2": "value2" } } } ``` ### Key Concepts All requests and responses wrap data in a `data` object that contains the resource type, ID, and attributes. The `type` field identifies the resource type (e.g., "auth", "payments", "merchants"). The `attributes` object contains all the resource-specific data and parameters. Responses include a `links` object with URLs related to the resource. ## Response Format ### Successful Response ```json theme={null} { "links": { "self": "https://api.digitzs.com/payments/123" }, "data": { "type": "payments", "id": "payment-123", "attributes": { "paymentType": "card", "transaction": { "code": "0", "message": "Success", "amount": "1000", "currency": "USD" } } } } ``` ### Error Response ```json theme={null} { "errors": [ { "status": "400", "title": "Bad Request", "detail": "The amount field is required", "source": { "pointer": "/data/attributes/transaction/amount" } } ] } ``` ## Common Data Types ### Amounts All monetary amounts are specified in cents (smallest currency unit). ```json Example theme={null} { "amount": "1000" // Represents $10.00 } ``` ```javascript JavaScript theme={null} const amountInDollars = 10.00; const amountInCents = Math.round(amountInDollars * 100).toString(); // Result: "1000" ``` ```python Python theme={null} amount_in_dollars = 10.00 amount_in_cents = str(int(amount_in_dollars * 100)) # Result: "1000" ``` ### Currency Codes Use three-character ISO 4217 currency codes: | Code | Currency | | ----- | --------------- | | `USD` | US Dollar | | `EUR` | Euro | | `GBP` | British Pound | | `CAD` | Canadian Dollar | ### Dates and Times All timestamps are returned in ISO 8601 format: ``` 2024-01-15T14:30:00Z ``` ## Rate Limiting The Digitzs API implements rate limiting to ensure fair usage and system stability. If you exceed rate limits, you'll receive a `429 Too Many Requests` error. Implement exponential backoff in your retry logic: ```javascript theme={null} async function makeRequestWithRetry(requestFn, maxRetries = 3) { for (let attempt = 0; attempt < maxRetries; attempt++) { try { return await requestFn(); } catch (error) { if (error.response?.status === 429 && attempt < maxRetries - 1) { const delay = Math.pow(2, attempt) * 1000; // Exponential backoff await new Promise(resolve => setTimeout(resolve, delay)); continue; } throw error; } } } ``` ## Idempotency To prevent duplicate transactions, you can include a `requestId` in your payment requests: ```json theme={null} { "data": { "requestId": "unique-uuid-v4", "type": "payments", "attributes": { ... } } } ``` Use UUID v4 format for request IDs. The same request ID will return the original response if submitted multiple times. ## Testing ### Test Mode Use test credentials provided during onboarding to test your integration without processing real transactions. ### Test Cards For testing card payments, use these test card numbers: | Card Number | Result | | ------------------ | ------------------ | | `4111111111111111` | Successful charge | | `4000000000000002` | Card declined | | `4000000000009995` | Insufficient funds | ### Test ACH For testing ACH payments, use any valid routing number (must be real) with test account numbers: | Account Number | Result | | -------------- | ------------------ | | `1234567` | Successful payment | | `9876543` | Insufficient funds | ## Webhooks Webhook support is coming soon. Check back for updates on event notifications. ## SDK and Libraries Complete examples available in the authentication guide Complete examples available in the authentication guide Complete examples available in the authentication guide Complete examples available in the authentication guide ## Next Steps Follow the [authentication guide](/authentication) to generate your access tokens Use the [merchant endpoints](/api-reference/merchants/overview) to set up accounts Start accepting payments with the [payment endpoints](/api-reference/payments/overview) ## Additional Resources Complete error code reference Download the complete manual # Create ACH Payment Source: https://digitzs.mintlify.app/api-reference/payments/create-ach-payment POST /payments Process an ACH (Automated Clearing House) bank transfer payment ## Endpoint ``` POST https://api.digitzs.com/payments ``` ## Overview Use this endpoint to process ACH payments directly from a customer's bank account. This method does not require creating a customer account or storing payment method tokens. ACH payments typically take 3-5 business days to settle. Funds are not immediately available. ## Authentication | Header | Value | Required | | --------------- | ---------------------------- | -------- | | `x-api-key` | Your API key from onboarding | Yes | | `Authorization` | `Bearer {appToken}` | Yes | | `appId` | Your application ID | Yes | | `Content-Type` | `application/json` | Yes | ## Request Body Container for API data UUID for idempotency. If provided, must be in valid UUID format. Optional but recommended for preventing duplicate transactions. Must be `"payments"` Container for payment attributes Must be `"ACH"` for ACH payments The merchant account identifier Optional JSON string containing additional metadata like email, IP addresses, or custom data Must be `"WEB"` for internet-initiated ACH transactions Bank account information Name of the financial institution Type of account - must be `"checking"` or `"savings"` Full name of the account holder Bank account number 9-digit bank routing number. Must be a valid routing number even in test environment. Transaction details Payment amount in cents (e.g., "3635" for \$36.35) Three-letter currency code (ISO 4217). Currently only `"USD"` is supported. Invoice or reference number for the transaction ### Example Request ```json theme={null} { "data": { "requestId": "f8d0fedd-fad0-4c53-bb8d-44a4cd28573b", "type": "payments", "attributes": { "paymentType": "ACH", "merchantId": "merchant_123456", "miscData": "{\"email\":\"customer@example.com\",\"originIp\":\"192.168.1.1\",\"customerIp\":\"203.0.113.0\"}", "StandardEntryClassCode": "WEB", "bank": { "bankName": "Wells Fargo", "accountType": "checking", "accountName": "John Doe", "accountNumber": "1234567890", "routingNumber": "026009593" }, "transaction": { "amount": "3635", "currency": "USD", "invoice": "INV-2024-001" } } } } ``` ## Response ### Success Response (201 Created) Contains URLs related to the resource URL of the current endpoint Container for response data Resource type - will be `"payments"` Unique payment transaction identifier Payment type - `"ACH"` Response code - `"0"` indicates success Human-readable response message Transaction amount in cents Currency code Invoice reference number ### Example Response ```json theme={null} { "links": { "self": "https://api.digitzs.com/payments" }, "data": { "type": "payments", "id": "pay_ach_abc123xyz", "attributes": { "paymentType": "ACH", "transaction": { "code": "0", "message": "Success", "amount": "3635", "currency": "USD", "invoice": "INV-2024-001" } } } } ``` ## Code Examples ```bash cURL theme={null} curl -X POST https://api.digitzs.com/payments \ -H "x-api-key: your-api-key" \ -H "Authorization: Bearer your-app-token" \ -H "appId: your-app-id" \ -H "Content-Type: application/json" \ -d '{ "data": { "type": "payments", "attributes": { "paymentType": "ACH", "merchantId": "merchant_123456", "StandardEntryClassCode": "WEB", "bank": { "bankName": "Wells Fargo", "accountType": "checking", "accountName": "John Doe", "accountNumber": "1234567890", "routingNumber": "026009593" }, "transaction": { "amount": "3635", "currency": "USD", "invoice": "INV-2024-001" } } } }' ``` ```javascript JavaScript theme={null} const axios = require('axios'); async function createACHPayment() { const response = await axios.post( 'https://api.digitzs.com/payments', { data: { type: 'payments', attributes: { paymentType: 'ACH', merchantId: 'merchant_123456', StandardEntryClassCode: 'WEB', bank: { bankName: 'Wells Fargo', accountType: 'checking', accountName: 'John Doe', accountNumber: '1234567890', routingNumber: '026009593' }, transaction: { amount: '3635', currency: 'USD', invoice: 'INV-2024-001' } } } }, { headers: { 'x-api-key': 'your-api-key', 'Authorization': 'Bearer your-app-token', 'appId': 'your-app-id', 'Content-Type': 'application/json' } } ); console.log('Payment ID:', response.data.data.id); return response.data; } createACHPayment(); ``` ```python Python theme={null} import requests def create_ach_payment(): url = "https://api.digitzs.com/payments" headers = { "x-api-key": "your-api-key", "Authorization": "Bearer your-app-token", "appId": "your-app-id", "Content-Type": "application/json" } payload = { "data": { "type": "payments", "attributes": { "paymentType": "ACH", "merchantId": "merchant_123456", "StandardEntryClassCode": "WEB", "bank": { "bankName": "Wells Fargo", "accountType": "checking", "accountName": "John Doe", "accountNumber": "1234567890", "routingNumber": "026009593" }, "transaction": { "amount": "3635", "currency": "USD", "invoice": "INV-2024-001" } } } } response = requests.post(url, headers=headers, json=payload) response.raise_for_status() payment_id = response.json()["data"]["id"] print(f"Payment ID: {payment_id}") return response.json() create_ach_payment() ``` ```php PHP theme={null} [ "type" => "payments", "attributes" => [ "paymentType" => "ACH", "merchantId" => "merchant_123456", "StandardEntryClassCode" => "WEB", "bank" => [ "bankName" => "Wells Fargo", "accountType" => "checking", "accountName" => "John Doe", "accountNumber" => "1234567890", "routingNumber" => "026009593" ], "transaction" => [ "amount" => "3635", "currency" => "USD", "invoice" => "INV-2024-001" ] ] ] ]); $ch = curl_init($url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if ($httpCode === 201) { $data = json_decode($response, true); $paymentId = $data["data"]["id"]; echo "Payment ID: " . $paymentId . "\n"; return $data; } else { throw new Exception("Error creating payment: " . $response); } } createACHPayment(); ?> ``` ```ruby Ruby theme={null} require 'net/http' require 'json' require 'uri' def create_ach_payment uri = URI('https://api.digitzs.com/payments') request = Net::HTTP::Post.new(uri) request['x-api-key'] = 'your-api-key' request['Authorization'] = 'Bearer your-app-token' request['appId'] = 'your-app-id' request['Content-Type'] = 'application/json' request.body = { data: { type: 'payments', attributes: { paymentType: 'ACH', merchantId: 'merchant_123456', StandardEntryClassCode: 'WEB', bank: { bankName: 'Wells Fargo', accountType: 'checking', accountName: 'John Doe', accountNumber: '1234567890', routingNumber: '026009593' }, transaction: { amount: '3635', currency: 'USD', invoice: 'INV-2024-001' } } } }.to_json response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http| http.request(request) end if response.code == '201' data = JSON.parse(response.body) payment_id = data['data']['id'] puts "Payment ID: #{payment_id}" data else raise "Error creating payment: #{response.body}" end end create_ach_payment ``` ## Error Responses ```json 400 Bad Request theme={null} { "errors": [ { "status": "400", "title": "Bad Request", "detail": "Invalid routing number", "source": { "pointer": "/data/attributes/bank/routingNumber" } } ] } ``` ```json 401 Unauthorized theme={null} { "errors": [ { "status": "401", "title": "Unauthorized", "detail": "Invalid or expired app token" } ] } ``` ```json 422 Unprocessable Entity theme={null} { "errors": [ { "status": "422", "title": "Unprocessable Entity", "detail": "Payment processing failed - insufficient funds" } ] } ``` ## Common Error Scenarios **Error:** 400 Bad Request **Solution:** Verify the routing number is a valid 9-digit ABA routing number. The test environment requires real routing numbers. **Error:** 400 Bad Request **Solution:** Ensure accountType is either "checking" or "savings" (lowercase). **Error:** 400 Bad Request **Solution:** Verify all required fields are present: paymentType, merchantId, StandardEntryClassCode, bank object, and transaction object. **Error:** 422 Unprocessable Entity **Solution:** The payment was rejected by the bank. Common reasons include insufficient funds, closed account, or invalid account information. ## Important Notes **Real Routing Numbers Required:** Even in the test environment, you must use valid bank routing numbers. Invalid routing numbers will be rejected. **Settlement Time:** ACH payments take 3-5 business days to settle. The payment will appear as "pending" during this time. **Idempotency:** Use the optional `requestId` field with a UUID to prevent duplicate payments if your request is accidentally submitted multiple times. ## Best Practices 1. **Validate Bank Information:** Verify routing and account numbers before submitting to reduce failed payments 2. **Store Payment IDs:** Save the returned payment ID for status checking and reconciliation 3. **Handle Async Nature:** ACH is asynchronous - implement webhooks or polling to track payment status 4. **Collect Customer Consent:** Ensure you have proper authorization to debit the customer's account 5. **Use miscData Field:** Store additional context like customer email, IP addresses for fraud prevention and customer support ## Next Steps Check the status of your ACH payment Learn how to refund an ACH payment # Create Second Split Source: https://digitzs.mintlify.app/api-reference/payments/create-second-split POST /payments Add an additional split to an existing transaction ## Endpoint ``` POST https://api.digitzs.com/payments ``` ## Overview Use this endpoint to perform a second split on an existing transaction. This allows you to distribute proceeds to a third merchant account after the original payment has been processed. This feature requires special configuration. Contact Digitzs support to enable second split functionality for your merchant accounts. ## Authentication | Header | Value | Required | | --------------- | ---------------------------- | -------- | | `x-api-key` | Your API key from onboarding | Yes | | `Authorization` | `Bearer {appToken}` | Yes | | `appId` | Your application ID | Yes | | `Content-Type` | `application/json` | Yes | ## Request Body Must be `"payments"` Container for payment attributes Must be `"secondSplit"` The payment ID of the original transaction to split from Split configuration Merchant account to receive the second split amount Amount to split in cents. Must be less than remaining available balance. Optional JSON string with additional metadata ### Example Request ```json theme={null} { "data": { "type": "payments", "attributes": { "paymentType": "secondSplit", "parentPaymentId": "pay_abc123xyz", "split": { "merchantId": "merchant_third_789", "amount": "50" }, "miscData": "{\"reason\":\"referral_fee\"}" } } } ``` ## Response ### Success Response (201 Created) ```json theme={null} { "links": { "self": "https://api.digitzs.com/payments" }, "data": { "type": "payments", "id": "pay_split2_xyz789", "attributes": { "paymentType": "secondSplit", "parentPaymentId": "pay_abc123xyz", "transaction": { "code": "0", "message": "Success", "amount": "50", "currency": "USD" } } } } ``` ## Code Examples ```bash cURL theme={null} curl -X POST https://api.digitzs.com/payments \ -H "x-api-key: your-api-key" \ -H "Authorization: Bearer your-app-token" \ -H "appId: your-app-id" \ -H "Content-Type: application/json" \ -d '{ "data": { "type": "payments", "attributes": { "paymentType": "secondSplit", "parentPaymentId": "pay_abc123xyz", "split": { "merchantId": "merchant_third_789", "amount": "50" } } } }' ``` ```javascript JavaScript theme={null} const axios = require('axios'); async function createSecondSplit(parentPaymentId, merchantId, amount) { const response = await axios.post( 'https://api.digitzs.com/payments', { data: { type: 'payments', attributes: { paymentType: 'secondSplit', parentPaymentId: parentPaymentId, split: { merchantId: merchantId, amount: amount } } } }, { headers: { 'x-api-key': 'your-api-key', 'Authorization': 'Bearer your-app-token', 'appId': 'your-app-id', 'Content-Type': 'application/json' } } ); console.log('Second Split ID:', response.data.data.id); return response.data; } createSecondSplit('pay_abc123xyz', 'merchant_third_789', '50'); ``` ```python Python theme={null} import requests def create_second_split(parent_payment_id, merchant_id, amount): url = "https://api.digitzs.com/payments" headers = { "x-api-key": "your-api-key", "Authorization": "Bearer your-app-token", "appId": "your-app-id", "Content-Type": "application/json" } payload = { "data": { "type": "payments", "attributes": { "paymentType": "secondSplit", "parentPaymentId": parent_payment_id, "split": { "merchantId": merchant_id, "amount": amount } } } } response = requests.post(url, headers=headers, json=payload) response.raise_for_status() return response.json() create_second_split("pay_abc123xyz", "merchant_third_789", "50") ``` ```php PHP theme={null} [ "type" => "payments", "attributes" => [ "paymentType" => "secondSplit", "parentPaymentId" => $parentPaymentId, "split" => [ "merchantId" => $merchantId, "amount" => $amount ] ] ] ]); $ch = curl_init($url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); return json_decode($response, true); } createSecondSplit("pay_abc123xyz", "merchant_third_789", "50"); ?> ``` ```ruby Ruby theme={null} require 'net/http' require 'json' require 'uri' def create_second_split(parent_payment_id, merchant_id, amount) uri = URI('https://api.digitzs.com/payments') request = Net::HTTP::Post.new(uri) request['x-api-key'] = 'your-api-key' request['Authorization'] = 'Bearer your-app-token' request['appId'] = 'your-app-id' request['Content-Type'] = 'application/json' request.body = { data: { type: 'payments', attributes: { paymentType: 'secondSplit', parentPaymentId: parent_payment_id, split: { merchantId: merchant_id, amount: amount } } } }.to_json response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http| http.request(request) end JSON.parse(response.body) end create_second_split('pay_abc123xyz', 'merchant_third_789', '50') ``` ## Important Notes **Configuration Required:** Second split functionality must be enabled for your merchant accounts. Contact Digitzs support before using this feature. **Available Balance:** The second split amount cannot exceed the available balance after the first split and processing fees. **Use Case:** This is useful for complex revenue sharing scenarios like referral fees, affiliate commissions, or multi-party marketplaces. ## Best Practices 1. **Verify Parent Payment:** Ensure the parent payment has settled before creating a second split 2. **Track All Splits:** Maintain records of all split transactions for reconciliation 3. **Validate Amount:** Check that sufficient funds remain for the second split 4. **Clear Documentation:** Document the reason for each split in the miscData field ## Next Steps View complete payment details including all splits # Create Split Payment Source: https://digitzs.mintlify.app/api-reference/payments/create-split-payment POST /payments Process a tokenized payment and split the proceeds between multiple merchant accounts ## Endpoint ``` POST https://api.digitzs.com/payments ``` ## Overview Use this endpoint to process tokenized payments and automatically split the proceeds between two merchant accounts. This is ideal for marketplace and platform applications where you need to collect fees or distribute revenue. Split payments require a TokenEx token from the embedded checkout and multiple merchant accounts configured for split processing. ## Authentication | Header | Value | Required | | --------------- | ---------------------------- | -------- | | `x-api-key` | Your API key from onboarding | Yes | | `Authorization` | `Bearer {appToken}` | Yes | | `appId` | Your application ID | Yes | | `Content-Type` | `application/json` | Yes | ## Request Body Container for API data UUID for idempotency to prevent duplicate transactions Must be `"payments"` Container for payment attributes Must be `"tokenv3Split"` for split payments Primary merchant account identifier (receives the net amount after split) Optional JSON string with additional metadata Tokenized payment method information TokenEx token ID from embedded checkout Cardholder's name Card expiration in MMYY format Whether to require AVS verification Transaction details Total payment amount in cents Currency code (e.g., "USD") Invoice or reference number Split configuration Secondary merchant account to receive the split amount (typically your platform fee account) Amount to split to secondary merchant in cents. Must be less than transaction amount. Billing address information (optional but recommended) Street address Address line 2 City State code ZIP code Country code ### Example Request ```json theme={null} { "data": { "type": "payments", "attributes": { "paymentType": "tokenv3Split", "merchantId": "merchant_primary_123", "token": { "tokenId": "tok_abc123xyz789", "holder": "John Doe", "expiry": "0229", "useAVS": true }, "transaction": { "amount": "500", "currency": "USD", "invoice": "INV-2024-001" }, "split": { "merchantId": "merchant_platform_456", "amount": "100" }, "billingAddress": { "line1": "123 Main Street", "city": "San Francisco", "state": "CA", "zip": "94102", "country": "USA" } } } } ``` ## Response ### Success Response (201 Created) Unique payment transaction identifier Payment type - `"card"` Transaction details including split information Response code - `"0"` indicates success Transaction status message Total transaction amount Authorization code Gross amount charged Net amount to primary merchant (after split and fees) ### Example Response ```json theme={null} { "links": { "self": "https://api.digitzs.com/payments" }, "data": { "type": "payments", "id": "pay_split_abc123", "attributes": { "paymentType": "card", "transaction": { "code": "0", "message": "Success", "amount": "500", "invoice": "INV-2024-001", "currency": "USD", "authCode": "A11111", "avsResult": "Y", "gross": "500", "net": "365", "grossMinusNet": "135", "fee": "35", "rate": "2.95" } } } } ``` ## Code Examples ```bash cURL theme={null} curl -X POST https://api.digitzs.com/payments \ -H "x-api-key: your-api-key" \ -H "Authorization: Bearer your-app-token" \ -H "appId: your-app-id" \ -H "Content-Type: application/json" \ -d '{ "data": { "type": "payments", "attributes": { "paymentType": "tokenv3Split", "merchantId": "merchant_primary_123", "token": { "tokenId": "tok_abc123xyz789", "holder": "John Doe", "expiry": "0229", "useAVS": true }, "transaction": { "amount": "500", "currency": "USD", "invoice": "INV-2024-001" }, "split": { "merchantId": "merchant_platform_456", "amount": "100" }, "billingAddress": { "line1": "123 Main Street", "city": "San Francisco", "state": "CA", "zip": "94102", "country": "USA" } } } }' ``` ```javascript JavaScript theme={null} const axios = require('axios'); async function createSplitPayment(tokenId, amount, splitAmount) { const response = await axios.post( 'https://api.digitzs.com/payments', { data: { type: 'payments', attributes: { paymentType: 'tokenv3Split', merchantId: 'merchant_primary_123', token: { tokenId: tokenId, holder: 'John Doe', expiry: '0229', useAVS: true }, transaction: { amount: amount, currency: 'USD', invoice: `INV-${Date.now()}` }, split: { merchantId: 'merchant_platform_456', amount: splitAmount }, billingAddress: { line1: '123 Main Street', city: 'San Francisco', state: 'CA', zip: '94102', country: 'USA' } } } }, { headers: { 'x-api-key': 'your-api-key', 'Authorization': 'Bearer your-app-token', 'appId': 'your-app-id', 'Content-Type': 'application/json' } } ); console.log('Payment ID:', response.data.data.id); console.log('Net to Primary:', response.data.data.attributes.transaction.net); return response.data; } // Process $5.00 payment with $1.00 platform fee createSplitPayment('tok_abc123xyz789', '500', '100'); ``` ```python Python theme={null} import requests def create_split_payment(token_id, amount, split_amount): url = "https://api.digitzs.com/payments" headers = { "x-api-key": "your-api-key", "Authorization": "Bearer your-app-token", "appId": "your-app-id", "Content-Type": "application/json" } payload = { "data": { "type": "payments", "attributes": { "paymentType": "tokenv3Split", "merchantId": "merchant_primary_123", "token": { "tokenId": token_id, "holder": "John Doe", "expiry": "0229", "useAVS": True }, "transaction": { "amount": amount, "currency": "USD", "invoice": f"INV-{int(time.time())}" }, "split": { "merchantId": "merchant_platform_456", "amount": split_amount }, "billingAddress": { "line1": "123 Main Street", "city": "San Francisco", "state": "CA", "zip": "94102", "country": "USA" } } } } response = requests.post(url, headers=headers, json=payload) response.raise_for_status() payment_id = response.json()["data"]["id"] net = response.json()["data"]["attributes"]["transaction"]["net"] print(f"Payment ID: {payment_id}") print(f"Net to Primary: ${float(net)/100:.2f}") return response.json() # Process $5.00 payment with $1.00 platform fee create_split_payment("tok_abc123xyz789", "500", "100") ``` ```php PHP theme={null} [ "type" => "payments", "attributes" => [ "paymentType" => "tokenv3Split", "merchantId" => "merchant_primary_123", "token" => [ "tokenId" => $tokenId, "holder" => "John Doe", "expiry" => "0229", "useAVS" => true ], "transaction" => [ "amount" => $amount, "currency" => "USD", "invoice" => "INV-" . time() ], "split" => [ "merchantId" => "merchant_platform_456", "amount" => $splitAmount ], "billingAddress" => [ "line1" => "123 Main Street", "city" => "San Francisco", "state" => "CA", "zip" => "94102", "country" => "USA" ] ] ] ]); $ch = curl_init($url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if ($httpCode === 201) { $data = json_decode($response, true); echo "Payment ID: " . $data["data"]["id"] . "\n"; echo "Net to Primary: $" . ($data["data"]["attributes"]["transaction"]["net"] / 100) . "\n"; return $data; } else { throw new Exception("Error: " . $response); } } // Process $5.00 payment with $1.00 platform fee createSplitPayment("tok_abc123xyz789", "500", "100"); ?> ``` ```ruby Ruby theme={null} require 'net/http' require 'json' require 'uri' def create_split_payment(token_id, amount, split_amount) uri = URI('https://api.digitzs.com/payments') request = Net::HTTP::Post.new(uri) request['x-api-key'] = 'your-api-key' request['Authorization'] = 'Bearer your-app-token' request['appId'] = 'your-app-id' request['Content-Type'] = 'application/json' request.body = { data: { type: 'payments', attributes: { paymentType: 'tokenv3Split', merchantId: 'merchant_primary_123', token: { tokenId: token_id, holder: 'John Doe', expiry: '0229', useAVS: true }, transaction: { amount: amount, currency: 'USD', invoice: "INV-#{Time.now.to_i}" }, split: { merchantId: 'merchant_platform_456', amount: split_amount }, billingAddress: { line1: '123 Main Street', city: 'San Francisco', state: 'CA', zip: '94102', country: 'USA' } } } }.to_json response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http| http.request(request) end if response.code == '201' data = JSON.parse(response.body) puts "Payment ID: #{data['data']['id']}" puts "Net to Primary: $#{data['data']['attributes']['transaction']['net'].to_f / 100}" data else raise "Error: #{response.body}" end end # Process $5.00 payment with $1.00 platform fee create_split_payment('tok_abc123xyz789', '500', '100') ``` ## Understanding Split Payments Split payments automatically distribute transaction proceeds: 1. **Customer pays total amount:** e.g., \$5.00 2. **Platform fee is split:** e.g., \$1.00 goes to secondary merchant 3. **Processing fees applied:** Standard 2.9% + \$0.30 4. **Primary merchant receives net:** Remaining amount after split and fees ### Calculation Example For a $5.00 transaction with $1.00 split: * **Gross:** \$5.00 * **Split to secondary merchant:** \$1.00 * \*\*Processing fee on $5.00:** $0.45 (2.9% + \$0.30) * **Net to primary merchant:** \$3.55 ## Error Responses ```json 400 Bad Request - Split amount exceeds total theme={null} { "errors": [ { "status": "400", "title": "Bad Request", "detail": "Split amount must be less than transaction amount" } ] } ``` ```json 403 Forbidden - Merchant not authorized for splits theme={null} { "errors": [ { "status": "403", "title": "Forbidden", "detail": "Merchant account not configured for split payments" } ] } ``` ## Common Error Scenarios **Error:** 400 Bad Request **Solution:** Ensure split.amount is less than transaction.amount. The split cannot be equal to or greater than the total. **Error:** 400 Bad Request **Solution:** Verify the secondary merchantId exists and is configured for receiving split payments. **Error:** 403 Forbidden **Solution:** Contact Digitzs support to enable split payment functionality for your merchant accounts. ## Important Notes **Pre-configuration Required:** Both merchant accounts must be configured for split payments. Contact Digitzs support to enable this feature. **Processing Fees:** Standard processing fees (2.9% + \$0.30) apply to the gross transaction amount, not the split amount. **Use Cases:** Split payments are ideal for marketplaces, platforms, and applications where you need to collect platform fees or distribute revenue to vendors. ## Best Practices 1. **Validate Split Amounts:** Ensure split amount is reasonable and less than total transaction amount 2. **Track Both Accounts:** Monitor transactions in both primary and secondary merchant accounts 3. **Clear Communication:** Inform users about how payment will be distributed 4. **Handle Refunds Properly:** Use split refund endpoint to properly reverse split transactions 5. **Test Thoroughly:** Verify split amounts are correctly distributed in your test environment ## Next Steps Add an additional split to an existing transaction Learn how to refund split payments # Create Token Payment Source: https://digitzs.mintlify.app/api-reference/payments/create-token-payment POST /payments Process a payment using a tokenized payment method from the embedded checkout ## Endpoint ``` POST https://api.digitzs.com/payments ``` ## Overview Use this endpoint to process payments using TokenEx tokens generated from the Digitzs embedded checkout. This secure method keeps sensitive payment data out of your application while maintaining PCI compliance. A TokenEx token must be generated through the Digitzs embedded checkout before using this endpoint. Contact Digitzs support to integrate the embedded checkout into your application. ## Authentication | Header | Value | Required | | --------------- | ---------------------------- | -------- | | `x-api-key` | Your API key from onboarding | Yes | | `Authorization` | `Bearer {appToken}` | Yes | | `appId` | Your application ID | Yes | | `Content-Type` | `application/json` | Yes | ## Request Body Container for API data UUID for idempotency. If provided, must be in valid UUID format. Recommended for preventing duplicate transactions. Must be `"payments"` Container for payment attributes Must be `"tokenv3"` for tokenized payments The merchant account identifier Optional JSON string containing additional metadata like email, IP addresses, or custom data Tokenized payment method information The TokenEx token ID retrieved from the embedded checkout Cardholder's name as it appears on the card Card expiration date in MMYY format (e.g., "0229" for February 2029) Whether to require AVS (Address Verification System) match. Set to `true` to require ZIP code match or better for payment capture. Transaction details Payment amount in cents (e.g., "500" for \$5.00) Three-letter currency code (ISO 4217). Currently only `"USD"` is supported. Invoice or reference number for the transaction Billing address information Primary street address. Optional but recommended for AVS verification. Secondary address line (apartment, suite, etc.). Optional. City. Optional but recommended. State or province code (e.g., "CA"). Optional but recommended. ZIP or postal code. Optional but recommended, especially when useAVS is true. Country code (e.g., "USA") ### Example Request ```json theme={null} { "data": { "requestId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", "type": "payments", "attributes": { "paymentType": "tokenv3", "merchantId": "merchant_123456", "miscData": "{\"email\":\"customer@example.com\",\"originIp\":\"192.168.1.1\",\"customerIp\":\"203.0.113.0\"}", "token": { "tokenId": "tok_abc123xyz789", "holder": "John Doe", "expiry": "0229", "useAVS": true }, "transaction": { "amount": "2500", "currency": "USD", "invoice": "INV-2024-001" }, "billingAddress": { "line1": "123 Main Street", "line2": "Suite 100", "city": "San Francisco", "state": "CA", "zip": "94102", "country": "USA" } } } } ``` ## Response ### Success Response (201 Created) Contains URLs related to the resource URL of the current endpoint Container for response data Resource type - will be `"payments"` Unique payment transaction identifier Payment type - `"card"` Response code - `"0"` indicates success Human-readable response message Transaction amount in cents Currency code Invoice reference number Authorization code from the payment processor AVS verification result code Gross transaction amount in cents Net amount after fees in cents Total fees charged in cents Fixed fee component in cents Percentage rate applied to the transaction ### Example Response ```json theme={null} { "links": { "self": "https://api.digitzs.com/payments" }, "data": { "type": "payments", "id": "pay_card_abc123xyz", "attributes": { "paymentType": "card", "transaction": { "code": "0", "message": "Success", "amount": "2500", "invoice": "INV-2024-001", "currency": "USD", "authCode": "A11111", "avsResult": "Y", "gross": "2500", "net": "2399", "grossMinusNet": "101", "fee": "30", "rate": "2.90" } } } } ``` ## Code Examples ```bash cURL theme={null} curl -X POST https://api.digitzs.com/payments \ -H "x-api-key: your-api-key" \ -H "Authorization: Bearer your-app-token" \ -H "appId: your-app-id" \ -H "Content-Type: application/json" \ -d '{ "data": { "type": "payments", "attributes": { "paymentType": "tokenv3", "merchantId": "merchant_123456", "token": { "tokenId": "tok_abc123xyz789", "holder": "John Doe", "expiry": "0229", "useAVS": true }, "transaction": { "amount": "2500", "currency": "USD", "invoice": "INV-2024-001" }, "billingAddress": { "line1": "123 Main Street", "city": "San Francisco", "state": "CA", "zip": "94102", "country": "USA" } } } }' ``` ```javascript JavaScript theme={null} const axios = require('axios'); async function createTokenPayment(tokenId) { const response = await axios.post( 'https://api.digitzs.com/payments', { data: { type: 'payments', attributes: { paymentType: 'tokenv3', merchantId: 'merchant_123456', token: { tokenId: tokenId, holder: 'John Doe', expiry: '0229', useAVS: true }, transaction: { amount: '2500', currency: 'USD', invoice: 'INV-2024-001' }, billingAddress: { line1: '123 Main Street', city: 'San Francisco', state: 'CA', zip: '94102', country: 'USA' } } } }, { headers: { 'x-api-key': 'your-api-key', 'Authorization': 'Bearer your-app-token', 'appId': 'your-app-id', 'Content-Type': 'application/json' } } ); console.log('Payment ID:', response.data.data.id); console.log('Auth Code:', response.data.data.attributes.transaction.authCode); return response.data; } // Use with token from embedded checkout createTokenPayment('tok_abc123xyz789'); ``` ```python Python theme={null} import requests def create_token_payment(token_id): url = "https://api.digitzs.com/payments" headers = { "x-api-key": "your-api-key", "Authorization": "Bearer your-app-token", "appId": "your-app-id", "Content-Type": "application/json" } payload = { "data": { "type": "payments", "attributes": { "paymentType": "tokenv3", "merchantId": "merchant_123456", "token": { "tokenId": token_id, "holder": "John Doe", "expiry": "0229", "useAVS": True }, "transaction": { "amount": "2500", "currency": "USD", "invoice": "INV-2024-001" }, "billingAddress": { "line1": "123 Main Street", "city": "San Francisco", "state": "CA", "zip": "94102", "country": "USA" } } } } response = requests.post(url, headers=headers, json=payload) response.raise_for_status() payment_id = response.json()["data"]["id"] auth_code = response.json()["data"]["attributes"]["transaction"]["authCode"] print(f"Payment ID: {payment_id}") print(f"Auth Code: {auth_code}") return response.json() # Use with token from embedded checkout create_token_payment("tok_abc123xyz789") ``` ```php PHP theme={null} [ "type" => "payments", "attributes" => [ "paymentType" => "tokenv3", "merchantId" => "merchant_123456", "token" => [ "tokenId" => $tokenId, "holder" => "John Doe", "expiry" => "0229", "useAVS" => true ], "transaction" => [ "amount" => "2500", "currency" => "USD", "invoice" => "INV-2024-001" ], "billingAddress" => [ "line1" => "123 Main Street", "city" => "San Francisco", "state" => "CA", "zip" => "94102", "country" => "USA" ] ] ] ]); $ch = curl_init($url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if ($httpCode === 201) { $data = json_decode($response, true); $paymentId = $data["data"]["id"]; $authCode = $data["data"]["attributes"]["transaction"]["authCode"]; echo "Payment ID: " . $paymentId . "\n"; echo "Auth Code: " . $authCode . "\n"; return $data; } else { throw new Exception("Error creating payment: " . $response); } } // Use with token from embedded checkout createTokenPayment("tok_abc123xyz789"); ?> ``` ```ruby Ruby theme={null} require 'net/http' require 'json' require 'uri' def create_token_payment(token_id) uri = URI('https://api.digitzs.com/payments') request = Net::HTTP::Post.new(uri) request['x-api-key'] = 'your-api-key' request['Authorization'] = 'Bearer your-app-token' request['appId'] = 'your-app-id' request['Content-Type'] = 'application/json' request.body = { data: { type: 'payments', attributes: { paymentType: 'tokenv3', merchantId: 'merchant_123456', token: { tokenId: token_id, holder: 'John Doe', expiry: '0229', useAVS: true }, transaction: { amount: '2500', currency: 'USD', invoice: 'INV-2024-001' }, billingAddress: { line1: '123 Main Street', city: 'San Francisco', state: 'CA', zip: '94102', country: 'USA' } } } }.to_json response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http| http.request(request) end if response.code == '201' data = JSON.parse(response.body) payment_id = data['data']['id'] auth_code = data['data']['attributes']['transaction']['authCode'] puts "Payment ID: #{payment_id}" puts "Auth Code: #{auth_code}" data else raise "Error creating payment: #{response.body}" end end # Use with token from embedded checkout create_token_payment('tok_abc123xyz789') ``` ## AVS Result Codes The `avsResult` field contains Address Verification System codes: | Code | Description | | ---- | ----------------------------------------- | | Y | Street address and ZIP code match | | A | Street address matches, ZIP code does not | | Z | ZIP code matches, street address does not | | N | Neither street address nor ZIP code match | | U | Address information unavailable | | R | Retry - System unavailable | | S | Service not supported | | T | AVS not supported for this card type | ## Error Responses ```json 400 Bad Request theme={null} { "errors": [ { "status": "400", "title": "Bad Request", "detail": "Invalid token format", "source": { "pointer": "/data/attributes/token/tokenId" } } ] } ``` ```json 402 Payment Required theme={null} { "errors": [ { "status": "402", "title": "Payment Failed", "detail": "Card declined - insufficient funds" } ] } ``` ```json 422 Unprocessable Entity theme={null} { "errors": [ { "status": "422", "title": "Unprocessable Entity", "detail": "AVS verification failed - ZIP code mismatch" } ] } ``` ## Common Error Scenarios **Error:** 400 Bad Request **Solution:** Ensure the tokenId is valid and was recently generated from the embedded checkout. Tokens may have a limited lifespan. **Error:** 422 Unprocessable Entity **Solution:** When `useAVS` is true, ensure the billing address ZIP code matches the card's billing ZIP. You can disable AVS by setting `useAVS` to false, but this may increase fraud risk. **Error:** 402 Payment Required **Solution:** The card issuer declined the transaction. Common reasons include insufficient funds, expired card, or fraud prevention. Ask the customer to contact their bank or use a different payment method. **Error:** 400 Bad Request **Solution:** Ensure expiry is in MMYY format (4 digits, no separators). Example: "0229" for February 2029. ## Important Notes **Token Security:** Tokens should only be used once. Do not reuse tokens across multiple payment attempts. **AVS Recommendations:** Enabling AVS (`useAVS: true`) provides additional fraud protection but may decline legitimate transactions if address information doesn't match. Consider your risk tolerance when configuring this setting. **Embedded Checkout Required:** Contact Digitzs support to integrate the embedded checkout into your application before using this endpoint. The checkout handles secure card data collection and tokenization. ## Best Practices 1. **Use Idempotency Keys:** Include `requestId` to prevent duplicate charges if requests are retried 2. **Collect Complete Addresses:** Provide full billing address information for better AVS verification 3. **Handle Declines Gracefully:** Display user-friendly error messages and offer alternative payment methods 4. **Store Payment IDs:** Save the returned payment ID for reconciliation and potential refunds 5. **Implement Retry Logic:** Handle transient errors with exponential backoff 6. **Monitor AVS Results:** Track AVS result codes to identify potential fraud patterns ## Understanding Transaction Fees The response includes detailed fee breakdown: * **gross:** Total amount charged to the customer * **fee:** Fixed transaction fee (typically \$0.30) * **rate:** Percentage fee (typically 2.9%) * **grossMinusNet:** Total fees charged (fee + percentage of gross) * **net:** Amount deposited to merchant account (gross - grossMinusNet) ## Next Steps Retrieve full details of a completed payment Learn how to split payment proceeds across multiple accounts # Get Payment by ID Source: https://digitzs.mintlify.app/api-reference/payments/get-by-id GET /payments/{id} Retrieve detailed information about a specific payment transaction ## Endpoint ``` GET https://api.digitzs.com/payments/{id} ``` ## Overview Use this endpoint to retrieve complete details of a specific payment transaction, including transaction status, amounts, fees, and any associated split information. ## Authentication | Header | Value | Required | | --------------- | ------------------- | -------- | | `x-api-key` | Your API key | Yes | | `Authorization` | `Bearer {appToken}` | Yes | | `appId` | Your application ID | Yes | ## Path Parameters The unique payment transaction ID ## Response ### Success Response (200 OK) Container for payment data Resource type - `"payments"` Payment transaction ID Type of payment (e.g., "card", "ACH") Merchant account identifier ISO 8601 timestamp of when payment was created Payment status (pending, completed, failed, refunded, voided) Response code from processor Transaction status message Transaction amount in cents Currency code Invoice reference number Authorization code (card payments) AVS verification result (card payments) Gross transaction amount Net amount after fees Fixed processing fee Percentage rate applied Array of split transactions (if applicable) Secondary merchant ID Split amount in cents Split status ### Example Response - Card Payment ```json theme={null} { "links": { "self": "https://api.digitzs.com/payments/pay_abc123xyz" }, "data": { "type": "payments", "id": "pay_abc123xyz", "attributes": { "paymentType": "card", "merchantId": "merchant_123456", "createdAt": "2024-01-15T10:30:00Z", "status": "completed", "transaction": { "code": "0", "message": "Success", "amount": "2500", "currency": "USD", "invoice": "INV-2024-001", "authCode": "A11111", "avsResult": "Y", "gross": "2500", "net": "2399", "grossMinusNet": "101", "fee": "30", "rate": "2.90" } } } } ``` ### Example Response - Split Payment ```json theme={null} { "links": { "self": "https://api.digitzs.com/payments/pay_split_abc123" }, "data": { "type": "payments", "id": "pay_split_abc123", "attributes": { "paymentType": "card", "merchantId": "merchant_primary_123", "status": "completed", "transaction": { "amount": "500", "gross": "500", "net": "365", "invoice": "INV-2024-002" }, "splits": [ { "merchantId": "merchant_platform_456", "amount": "100", "status": "completed" } ] } } } ``` ### Example Response - ACH Payment ```json theme={null} { "data": { "type": "payments", "id": "pay_ach_xyz789", "attributes": { "paymentType": "ACH", "merchantId": "merchant_123456", "status": "pending", "transaction": { "code": "0", "message": "Pending", "amount": "3635", "currency": "USD", "invoice": "INV-ACH-001" }, "bank": { "accountType": "checking", "last4": "7890" } } } } ``` ## Code Examples ```bash cURL theme={null} curl -X GET https://api.digitzs.com/payments/pay_abc123xyz \ -H "x-api-key: your-api-key" \ -H "Authorization: Bearer your-app-token" \ -H "appId: your-app-id" ``` ```javascript JavaScript theme={null} const axios = require('axios'); async function getPayment(paymentId) { const response = await axios.get( `https://api.digitzs.com/payments/${paymentId}`, { headers: { 'x-api-key': 'your-api-key', 'Authorization': 'Bearer your-app-token', 'appId': 'your-app-id' } } ); console.log('Payment Status:', response.data.data.attributes.status); console.log('Amount:', response.data.data.attributes.transaction.amount); return response.data; } getPayment('pay_abc123xyz'); ``` ```python Python theme={null} import requests def get_payment(payment_id): url = f"https://api.digitzs.com/payments/{payment_id}" headers = { "x-api-key": "your-api-key", "Authorization": "Bearer your-app-token", "appId": "your-app-id" } response = requests.get(url, headers=headers) response.raise_for_status() data = response.json()["data"] print(f"Status: {data['attributes']['status']}") print(f"Amount: ${float(data['attributes']['transaction']['amount'])/100:.2f}") return response.json() get_payment("pay_abc123xyz") ``` ```php PHP theme={null} ``` ```ruby Ruby theme={null} require 'net/http' require 'json' require 'uri' def get_payment(payment_id) uri = URI("https://api.digitzs.com/payments/#{payment_id}") request = Net::HTTP::Get.new(uri) request['x-api-key'] = 'your-api-key' request['Authorization'] = 'Bearer your-app-token' request['appId'] = 'your-app-id' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http| http.request(request) end if response.code == '200' data = JSON.parse(response.body)['data'] puts "Status: #{data['attributes']['status']}" puts "Amount: $#{data['attributes']['transaction']['amount'].to_f / 100}" JSON.parse(response.body) else raise "Error: #{response.body}" end end get_payment('pay_abc123xyz') ``` ## Payment Status Values | Status | Description | | ---------------- | ------------------------------------------- | | `pending` | Payment is being processed (common for ACH) | | `completed` | Payment successfully processed and settled | | `failed` | Payment failed or was declined | | `refunded` | Payment has been refunded | | `voided` | Payment was voided (same-day cancellation) | | `partial_refund` | Payment has been partially refunded | ## Error Responses ```json 404 Not Found theme={null} { "errors": [ { "status": "404", "title": "Not Found", "detail": "Payment not found" } ] } ``` ```json 403 Forbidden theme={null} { "errors": [ { "status": "403", "title": "Forbidden", "detail": "Not authorized to access this payment" } ] } ``` ## Use Cases Use this endpoint to verify transaction details match your records and reconcile payments with your accounting system. Retrieve payment details when customers inquire about their transactions or report issues. Check payment status and amount before processing refunds to ensure accuracy. Monitor distribution of split payments across multiple merchant accounts. ## Best Practices 1. **Cache Appropriately:** Cache payment details but refresh for status updates 2. **Handle ACH Delays:** ACH payments remain "pending" for 3-5 business days 3. **Monitor Split Details:** For split payments, verify amounts distributed correctly 4. **Store Payment IDs:** Always save payment IDs for future reference and support 5. **Use Webhooks:** Consider implementing webhooks for real-time status updates instead of polling ## Next Steps Check only the status of a payment (lighter endpoint) Retrieve multiple payments for a merchant # Get Payment Status Source: https://digitzs.mintlify.app/api-reference/payments/get-status GET /payments/status/{id} Retrieve the current status of a payment transaction ## Endpoint ``` GET https://api.digitzs.com/payments/status/{id} ``` ## Overview Use this lightweight endpoint to quickly check the status of a payment transaction without retrieving all transaction details. This endpoint returns less data than GET /payments/{id}, making it ideal for status polling or when you only need to know if a payment succeeded. ## Authentication | Header | Value | Required | | --------------- | ------------------- | -------- | | `x-api-key` | Your API key | Yes | | `Authorization` | `Bearer {appToken}` | Yes | | `appId` | Your application ID | Yes | ## Path Parameters The unique payment transaction ID ## Response ### Success Response (200 OK) ```json theme={null} { "links": { "self": "https://api.digitzs.com/payments/status/pay_abc123xyz" }, "data": { "type": "payments", "id": "pay_abc123xyz", "attributes": { "status": "completed", "paymentType": "card", "amount": "2500", "currency": "USD", "createdAt": "2024-01-15T10:30:00Z", "updatedAt": "2024-01-15T10:30:05Z" } } } ``` Current payment status: `pending`, `completed`, `failed`, `refunded`, `voided`, or `partial_refund` Transaction amount in cents ISO 8601 timestamp of payment creation ISO 8601 timestamp of last status update ## Code Examples ```bash cURL theme={null} curl -X GET https://api.digitzs.com/payments/status/pay_abc123xyz \ -H "x-api-key: your-api-key" \ -H "Authorization: Bearer your-app-token" \ -H "appId: your-app-id" ``` ```javascript JavaScript theme={null} const axios = require('axios'); async function getPaymentStatus(paymentId) { const response = await axios.get( `https://api.digitzs.com/payments/status/${paymentId}`, { headers: { 'x-api-key': 'your-api-key', 'Authorization': 'Bearer your-app-token', 'appId': 'your-app-id' } } ); const status = response.data.data.attributes.status; console.log(`Payment ${paymentId} status:`, status); return status; } getPaymentStatus('pay_abc123xyz'); ``` ```python Python theme={null} import requests def get_payment_status(payment_id): url = f"https://api.digitzs.com/payments/status/{payment_id}" headers = { "x-api-key": "your-api-key", "Authorization": "Bearer your-app-token", "appId": "your-app-id" } response = requests.get(url, headers=headers) response.raise_for_status() status = response.json()["data"]["attributes"]["status"] print(f"Payment {payment_id} status: {status}") return status get_payment_status("pay_abc123xyz") ``` ```php PHP theme={null} ``` ```ruby Ruby theme={null} require 'net/http' require 'json' def get_payment_status(payment_id) uri = URI("https://api.digitzs.com/payments/status/#{payment_id}") request = Net::HTTP::Get.new(uri) request['x-api-key'] = 'your-api-key' request['Authorization'] = 'Bearer your-app-token' request['appId'] = 'your-app-id' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http| http.request(request) end data = JSON.parse(response.body) status = data['data']['attributes']['status'] puts "Payment status: #{status}" status end get_payment_status('pay_abc123xyz') ``` ## Status Values | Status | Description | Next Actions | | ---------------- | ------------------------------------ | -------------------------------------------------- | | `pending` | Payment processing (typical for ACH) | Wait for settlement | | `completed` | Successfully processed | No action needed | | `failed` | Payment failed or declined | Review error, retry with different payment method | | `refunded` | Fully refunded | No further refunds possible | | `voided` | Transaction cancelled same-day | No action needed | | `partial_refund` | Partially refunded | Additional refunds possible up to remaining amount | ## Polling Best Practices **Frequency:** Check every 30-60 minutes during business hours **Duration:** ACH payments take 3-5 business days to settle **Better Alternative:** Implement webhooks for real-time status updates **Frequency:** Check once immediately after creation, then hourly if needed **Duration:** Card payments typically complete within seconds **Timeout:** If pending after 5 minutes, likely an issue - investigate For repeated status checks: 1. First check: Immediate 2. Second check: 30 seconds 3. Third check: 1 minute 4. Fourth check: 2 minutes 5. Continue doubling up to maximum interval ## Error Responses ```json 404 Not Found theme={null} { "errors": [ { "status": "404", "title": "Not Found", "detail": "Payment not found" } ] } ``` ## Common Use Cases 1. **Status Polling:** Regularly check ACH payment status until settled 2. **Payment Confirmation:** Verify payment completed before fulfilling orders 3. **Dashboard Updates:** Display real-time payment status in admin interfaces 4. **Webhook Verification:** Confirm status received via webhook matches current state ## Performance Considerations **Lighter Payload:** This endpoint returns significantly less data than GET /payments/{id}, making it faster and more efficient for status checks. **Rate Limiting:** Avoid excessive polling. Implement reasonable intervals or use webhooks instead. ## Next Steps Retrieve complete payment information including fees and splits View all payments for a merchant # List Payments Source: https://digitzs.mintlify.app/api-reference/payments/list GET /payments Retrieve a list of payment transactions for a merchant ## Endpoint ``` GET https://api.digitzs.com/payments ``` ## Overview Use this endpoint to retrieve a paginated list of payment transactions for a specific merchant account. ## Authentication | Header | Value | Required | | --------------- | ------------------- | -------- | | `x-api-key` | Your API key | Yes | | `Authorization` | `Bearer {appToken}` | Yes | | `appId` | Your application ID | Yes | ## Query Parameters Merchant ID to retrieve payments for Number of results per page (default: 25, max: 100) Number of results to skip for pagination (default: 0) Filter payments created after this date (ISO 8601 format) Filter payments created before this date (ISO 8601 format) Filter by payment status: `pending`, `completed`, `failed`, `refunded`, `voided` ## Response ### Success Response (200 OK) ```json theme={null} { "links": { "self": "https://api.digitzs.com/payments?id=merchant_123456&limit=25", "next": "https://api.digitzs.com/payments?id=merchant_123456&limit=25&offset=25" }, "data": [ { "type": "payments", "id": "pay_abc123", "attributes": { "paymentType": "card", "status": "completed", "createdAt": "2024-01-15T10:30:00Z", "transaction": { "amount": "2500", "currency": "USD", "invoice": "INV-001", "gross": "2500", "net": "2399" } } }, { "type": "payments", "id": "pay_xyz789", "attributes": { "paymentType": "ACH", "status": "pending", "createdAt": "2024-01-15T09:00:00Z", "transaction": { "amount": "10000", "currency": "USD", "invoice": "INV-002" } } } ], "meta": { "total": 156, "limit": 25, "offset": 0, "hasMore": true } } ``` Array of payment objects (see GET /payments/{id} for full object structure) Pagination metadata Total number of payments matching the query Number of results per page Current pagination offset Whether more results are available ## Code Examples ```bash cURL theme={null} curl -X GET "https://api.digitzs.com/payments?id=merchant_123456&limit=25" \ -H "x-api-key: your-api-key" \ -H "Authorization: Bearer your-app-token" \ -H "appId: your-app-id" ``` ```javascript JavaScript theme={null} const axios = require('axios'); async function listPayments(merchantId, options = {}) { const params = new URLSearchParams({ id: merchantId, limit: options.limit || 25, offset: options.offset || 0, ...options.filters }); const response = await axios.get( `https://api.digitzs.com/payments?${params}`, { headers: { 'x-api-key': 'your-api-key', 'Authorization': 'Bearer your-app-token', 'appId': 'your-app-id' } } ); console.log(`Retrieved ${response.data.data.length} payments`); console.log(`Total: ${response.data.meta.total}`); return response.data; } // Get first page listPayments('merchant_123456'); // Get completed payments from specific date range listPayments('merchant_123456', { limit: 50, filters: { status: 'completed', startDate: '2024-01-01', endDate: '2024-01-31' } }); ``` ```python Python theme={null} import requests from urllib.parse import urlencode def list_payments(merchant_id, limit=25, offset=0, **filters): url = "https://api.digitzs.com/payments" params = { "id": merchant_id, "limit": limit, "offset": offset, **filters } headers = { "x-api-key": "your-api-key", "Authorization": "Bearer your-app-token", "appId": "your-app-id" } response = requests.get(url, headers=headers, params=params) response.raise_for_status() data = response.json() print(f"Retrieved {len(data['data'])} payments") print(f"Total: {data['meta']['total']}") return data # Get first page list_payments("merchant_123456") # Get completed payments from January 2024 list_payments( "merchant_123456", limit=50, status="completed", startDate="2024-01-01", endDate="2024-01-31" ) ``` ```php PHP theme={null} $merchantId, 'limit' => 25, 'offset' => 0 ], $options); $url = "https://api.digitzs.com/payments?" . http_build_query($params); $headers = [ "x-api-key: your-api-key", "Authorization: Bearer your-app-token", "appId: your-app-id" ]; $ch = curl_init($url); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); $data = json_decode($response, true); echo "Retrieved " . count($data["data"]) . " payments\n"; echo "Total: " . $data["meta"]["total"] . "\n"; return $data; } // Get first page listPayments("merchant_123456"); // Get completed payments from January 2024 listPayments("merchant_123456", [ 'limit' => 50, 'status' => 'completed', 'startDate' => '2024-01-01', 'endDate' => '2024-01-31' ]); ?> ``` ```ruby Ruby theme={null} require 'net/http' require 'json' require 'uri' def list_payments(merchant_id, options = {}) params = { id: merchant_id, limit: options[:limit] || 25, offset: options[:offset] || 0 }.merge(options[:filters] || {}) uri = URI('https://api.digitzs.com/payments') uri.query = URI.encode_www_form(params) request = Net::HTTP::Get.new(uri) request['x-api-key'] = 'your-api-key' request['Authorization'] = 'Bearer your-app-token' request['appId'] = 'your-app-id' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http| http.request(request) end data = JSON.parse(response.body) puts "Retrieved #{data['data'].length} payments" puts "Total: #{data['meta']['total']}" data end # Get first page list_payments('merchant_123456') # Get completed payments from January 2024 list_payments('merchant_123456', { limit: 50, filters: { status: 'completed', startDate: '2024-01-01', endDate: '2024-01-31' } }) ``` ## Pagination Example ```javascript theme={null} async function getAllPayments(merchantId) { let allPayments = []; let offset = 0; const limit = 100; // Max per request let hasMore = true; while (hasMore) { const response = await listPayments(merchantId, { limit, offset }); allPayments = allPayments.concat(response.data); hasMore = response.meta.hasMore; offset += limit; console.log(`Fetched ${allPayments.length} of ${response.meta.total} payments`); } return allPayments; } ``` ## Filtering Best Practices Always specify both startDate and endDate for better performance: ``` ?startDate=2024-01-01&endDate=2024-01-31 ``` Filter by status to reduce response size: ``` ?status=completed&startDate=2024-01-01 ``` Use maximum limit (100) to minimize API calls when retrieving large datasets: ``` ?limit=100&offset=0 ``` ## Error Responses ```json 400 Bad Request theme={null} { "errors": [ { "status": "400", "title": "Bad Request", "detail": "Invalid merchant ID" } ] } ``` ```json 403 Forbidden theme={null} { "errors": [ { "status": "403", "title": "Forbidden", "detail": "Not authorized to access this merchant's payments" } ] } ``` ## Common Use Cases 1. **Transaction History:** Display payment history in merchant dashboard 2. **Reporting:** Generate financial reports for specific date ranges 3. **Reconciliation:** Match payments with bank deposits 4. **Analytics:** Analyze payment trends and patterns 5. **Customer Support:** Search for specific transactions by invoice or date ## Performance Tips **Optimize Queries:** Use date ranges and status filters to reduce result set size and improve response times. **Caching:** Consider caching results for completed payments as they won't change (except for potential refunds). ## Next Steps View complete details for a specific payment Process a new payment transaction # Payment Endpoints Source: https://digitzs.mintlify.app/api-reference/payments/overview Process payments, manage refunds, and retrieve transaction data ## Overview The Payment endpoints enable you to accept online and mobile payments, process refunds, and retrieve transaction information. Digitzs supports card payments, ACH transfers, and split payments for marketplace applications. All payment amounts must be specified in cents (smallest currency unit). For example, \$10.00 = 1000 cents. ## Payment Types Accept credit and debit card payments with instant authorization Process bank transfers via the Automated Clearing House network Automatically distribute funds between merchants and your platform ## Available Endpoints ### Create and Process Process a credit or debit card payment `POST /payments` Process an ACH bank transfer `POST /payments` ### Split Payments Split payment between multiple recipients `POST /payments` Add another split to an existing payment `POST /payments` ### Refunds and Voids Refund a completed payment or void a pending one `POST /payments` Refund a portion of a split payment `POST /payments` ### Retrieve Information Retrieve payment details `GET /payments/{id}` Check payment processing status `GET /payments/status/{id}` Get all payments for a merchant `GET /payments` ## Quick Start ### Process a Card Payment ```bash theme={null} curl -X POST https://api.digitzs.com/payments \ -H "Authorization: Bearer your-app-token" \ -H "x-api-key: your-api-key" \ -H "appId: your-app-id" \ -H "Content-Type: application/json" \ -d '{ "data": { "type": "payments", "attributes": { "paymentType": "card", "merchantId": "merchant-123", "paymentMethod": { "token": "payment-method-token" }, "transaction": { "amount": "1000", "currency": "USD", "invoice": "INV-001" } } } }' ``` ### Process an ACH Payment ```bash theme={null} curl -X POST https://api.digitzs.com/payments \ -H "Authorization: Bearer your-app-token" \ -H "x-api-key: your-api-key" \ -H "appId: your-app-id" \ -H "Content-Type: application/json" \ -d '{ "data": { "type": "payments", "attributes": { "paymentType": "ACH", "merchantId": "merchant-123", "StandardEntryClassCode": "WEB", "bank": { "bankName": "Wells Fargo", "accountType": "checking", "accountName": "John Doe", "accountNumber": "1234567", "routingNumber": "026009593" }, "transaction": { "amount": "1000", "currency": "USD", "invoice": "INV-001" } } } }' ``` ## Payment Flow ```mermaid theme={null} sequenceDiagram participant Customer participant App as Your Application participant API as Digitzs API participant Processor as Payment Processor participant Merchant Customer->>App: Initiate Payment App->>API: POST /payments API->>Processor: Process Payment Processor-->>API: Authorization Response API-->>App: Payment Created (201) App-->>Customer: Payment Confirmation Note over Processor,Merchant: Settlement (1-2 business days) Processor->>Merchant: Funds Deposited ``` ## Common Use Cases Process a one-time payment from a customer to a merchant using a card or ACH. **Best for:** E-commerce checkouts, subscription billing, invoices Distribute payment between merchant and platform fee automatically. **Best for:** Marketplaces, platforms, booking services **Example:** $100 sale = $90 to merchant + \$10 platform fee Split payment among multiple recipients (merchant, platform, referral partner). **Best for:** Multi-vendor platforms, affiliate programs **Example:** $100 sale = $85 merchant + $10 platform + $5 affiliate Return funds to customer for canceled orders or disputes. **Void:** Cancel payment before settlement **Refund:** Return funds after settlement ## Payment Method Tokens For security, card details should be tokenized before sending to the API. Digitzs provides a secure tokenization service: Use the Digitzs payment form or tokenization SDK to securely collect and tokenize payment methods on the client side. ## Transaction States | State | Description | | ------------ | --------------------------------------- | | `pending` | Payment initiated but not yet processed | | `authorized` | Payment authorized but not captured | | `completed` | Payment successfully processed | | `failed` | Payment failed to process | | `refunded` | Payment refunded to customer | | `voided` | Payment canceled before settlement | ## Testing ### Test Card Numbers | Card Number | Result | | ------------------ | ------------------ | | `4111111111111111` | Successful charge | | `4000000000000002` | Card declined | | `4000000000009995` | Insufficient funds | | `4000000000000069` | Expired card | ### Test ACH Accounts Use any valid routing number with these account numbers: | Account Number | Result | | -------------- | ------------------ | | `1234567` | Successful payment | | `9876543` | Insufficient funds | ## Best Practices Use `requestId` (UUID v4) to prevent duplicate charges Always check response codes and handle errors gracefully Validate amounts on client side before submitting Verify payment status before fulfilling orders ## Security Considerations **Never store raw card data.** Always use tokenized payment methods and comply with PCI DSS requirements. * Use HTTPS for all API requests * Tokenize payment methods on the client side * Implement fraud detection and velocity checks * Log all payment transactions for audit trails * Monitor for suspicious activity patterns ## Next Steps Create a merchant account to receive payments Add payment collection to your application Use test cards to verify your integration Switch to production credentials and start processing real payments ## Additional Resources Handle payment errors properly Manage merchant accounts # Refund Split Payment Source: https://digitzs.mintlify.app/api-reference/payments/refund-split POST /payments Refund the split portion of a payment ## Endpoint ``` POST https://api.digitzs.com/payments ``` ## Overview Use this endpoint to refund the split portion of a payment. This reverses the split amount that was distributed to a secondary merchant account. This endpoint only refunds the split amount, not the entire transaction. To refund the full payment, use both this endpoint and the regular refund endpoint. ## Authentication | Header | Value | Required | | --------------- | ------------------- | -------- | | `x-api-key` | Your API key | Yes | | `Authorization` | `Bearer {appToken}` | Yes | | `appId` | Your application ID | Yes | | `Content-Type` | `application/json` | Yes | ## Request Body Must be `"payments"` Must be `"refundSplit"` The payment ID of the original split transaction Transaction details Amount to refund from the split in cents Currency code (must match original) ### Example Request ```json theme={null} { "data": { "type": "payments", "attributes": { "paymentType": "refundSplit", "parentPaymentId": "pay_split_abc123", "transaction": { "amount": "100", "currency": "USD" } } } } ``` ## Response ```json theme={null} { "links": { "self": "https://api.digitzs.com/payments" }, "data": { "type": "payments", "id": "pay_refund_split_xyz", "attributes": { "paymentType": "refundSplit", "transaction": { "code": "0", "message": "Success", "amount": "100", "currency": "USD" } } } } ``` ## Code Examples ```bash cURL theme={null} curl -X POST https://api.digitzs.com/payments \ -H "x-api-key: your-api-key" \ -H "Authorization: Bearer your-app-token" \ -H "appId: your-app-id" \ -H "Content-Type: application/json" \ -d '{ "data": { "type": "payments", "attributes": { "paymentType": "refundSplit", "parentPaymentId": "pay_split_abc123", "transaction": { "amount": "100", "currency": "USD" } } } }' ``` ```javascript JavaScript theme={null} const axios = require('axios'); async function refundSplit(paymentId, amount) { const response = await axios.post( 'https://api.digitzs.com/payments', { data: { type: 'payments', attributes: { paymentType: 'refundSplit', parentPaymentId: paymentId, transaction: { amount: amount, currency: 'USD' } } } }, { headers: { 'x-api-key': 'your-api-key', 'Authorization': 'Bearer your-app-token', 'appId': 'your-app-id' } } ); return response.data; } ``` ```python Python theme={null} import requests def refund_split(payment_id, amount): url = "https://api.digitzs.com/payments" payload = { "data": { "type": "payments", "attributes": { "paymentType": "refundSplit", "parentPaymentId": payment_id, "transaction": { "amount": amount, "currency": "USD" } } } } headers = { "x-api-key": "your-api-key", "Authorization": "Bearer your-app-token", "appId": "your-app-id" } response = requests.post(url, headers=headers, json=payload) return response.json() ``` ```php PHP theme={null} [ "type" => "payments", "attributes" => [ "paymentType" => "refundSplit", "parentPaymentId" => $paymentId, "transaction" => [ "amount" => $amount, "currency" => "USD" ] ] ] ]); $ch = curl_init("https://api.digitzs.com/payments"); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "x-api-key: your-api-key", "Authorization: Bearer your-app-token", "appId: your-app-id" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); return json_decode(curl_exec($ch), true); } ?> ``` ```ruby Ruby theme={null} require 'net/http' require 'json' def refund_split(payment_id, amount) uri = URI('https://api.digitzs.com/payments') request = Net::HTTP::Post.new(uri) request['x-api-key'] = 'your-api-key' request['Authorization'] = 'Bearer your-app-token' request['appId'] = 'your-app-id' request.body = { data: { type: 'payments', attributes: { paymentType: 'refundSplit', parentPaymentId: payment_id, transaction: { amount: amount, currency: 'USD' } } } }.to_json response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http| http.request(request) end JSON.parse(response.body) end ``` ## Important Notes **Split Only:** This endpoint refunds only the split amount. To refund the entire transaction, you must also refund the primary payment separately. **Full Refund Process:** For complete refunds of split payments: 1) Refund the split using this endpoint, 2) Refund the primary payment using the regular refund endpoint. ## Next Steps Refund the primary portion of a split payment # Refund or Void Payment Source: https://digitzs.mintlify.app/api-reference/payments/refund-void POST /payments Refund a completed payment or void an eligible transaction ## Endpoint ``` POST https://api.digitzs.com/payments ``` ## Overview Use this endpoint to refund a payment or void an eligible transaction. The system automatically determines whether to perform a refund or void based on the transaction timing and type. **Void vs Refund:** If the transaction is eligible to be voided, the system will perform a void instead of a refund. Voids are processed faster and don't incur additional processing fees. ## Void Eligibility Transactions can be voided under these conditions: * **Card Transactions:** Can be voided before 11:59 PM PST on the same day the transaction was processed * **ACH Transactions:** Cannot be voided through the API. Contact support for ACH transaction issues. ## Authentication | Header | Value | Required | | --------------- | ---------------------------- | -------- | | `x-api-key` | Your API key from onboarding | Yes | | `Authorization` | `Bearer {appToken}` | Yes | | `appId` | Your application ID | Yes | | `Content-Type` | `application/json` | Yes | ## Request Body Must be `"payments"` Container for payment attributes Must be `"refund"` for refund/void operations The payment ID of the original transaction to refund or void Transaction details Amount to refund in cents. Can be less than original amount for partial refunds. Currency code (must match original transaction) Optional JSON string with refund reason or additional metadata ### Example Request - Full Refund ```json theme={null} { "data": { "type": "payments", "attributes": { "paymentType": "refund", "parentPaymentId": "pay_abc123xyz", "transaction": { "amount": "2500", "currency": "USD" }, "miscData": "{\"reason\":\"customer_request\",\"notes\":\"Item damaged\"}" } } } ``` ### Example Request - Partial Refund ```json theme={null} { "data": { "type": "payments", "attributes": { "paymentType": "refund", "parentPaymentId": "pay_abc123xyz", "transaction": { "amount": "1000", "currency": "USD" }, "miscData": "{\"reason\":\"partial_return\"}" } } } ``` ## Response ### Success Response (201 Created) ```json theme={null} { "links": { "self": "https://api.digitzs.com/payments" }, "data": { "type": "payments", "id": "pay_refund_xyz789", "attributes": { "paymentType": "refund", "parentPaymentId": "pay_abc123xyz", "transaction": { "code": "0", "message": "Success", "amount": "2500", "currency": "USD", "refundType": "void" } } } } ``` Indicates whether transaction was voided (`"void"`) or refunded (`"refund"`) ## Code Examples ```bash cURL theme={null} curl -X POST https://api.digitzs.com/payments \ -H "x-api-key: your-api-key" \ -H "Authorization: Bearer your-app-token" \ -H "appId: your-app-id" \ -H "Content-Type: application/json" \ -d '{ "data": { "type": "payments", "attributes": { "paymentType": "refund", "parentPaymentId": "pay_abc123xyz", "transaction": { "amount": "2500", "currency": "USD" } } } }' ``` ```javascript JavaScript theme={null} const axios = require('axios'); async function refundPayment(paymentId, amount) { const response = await axios.post( 'https://api.digitzs.com/payments', { data: { type: 'payments', attributes: { paymentType: 'refund', parentPaymentId: paymentId, transaction: { amount: amount, currency: 'USD' } } } }, { headers: { 'x-api-key': 'your-api-key', 'Authorization': 'Bearer your-app-token', 'appId': 'your-app-id', 'Content-Type': 'application/json' } } ); const refundType = response.data.data.attributes.transaction.refundType; console.log(`${refundType === 'void' ? 'Voided' : 'Refunded'} payment:`, response.data.data.id); return response.data; } // Refund $25.00 refundPayment('pay_abc123xyz', '2500'); ``` ```python Python theme={null} import requests def refund_payment(payment_id, amount): url = "https://api.digitzs.com/payments" headers = { "x-api-key": "your-api-key", "Authorization": "Bearer your-app-token", "appId": "your-app-id", "Content-Type": "application/json" } payload = { "data": { "type": "payments", "attributes": { "paymentType": "refund", "parentPaymentId": payment_id, "transaction": { "amount": amount, "currency": "USD" } } } } response = requests.post(url, headers=headers, json=payload) response.raise_for_status() refund_type = response.json()["data"]["attributes"]["transaction"]["refundType"] refund_id = response.json()["data"]["id"] print(f"{'Voided' if refund_type == 'void' else 'Refunded'} payment: {refund_id}") return response.json() # Refund $25.00 refund_payment("pay_abc123xyz", "2500") ``` ```php PHP theme={null} [ "type" => "payments", "attributes" => [ "paymentType" => "refund", "parentPaymentId" => $paymentId, "transaction" => [ "amount" => $amount, "currency" => "USD" ] ] ] ]); $ch = curl_init($url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if ($httpCode === 201) { $data = json_decode($response, true); $refundType = $data["data"]["attributes"]["transaction"]["refundType"]; $action = $refundType === "void" ? "Voided" : "Refunded"; echo "$action payment: " . $data["data"]["id"] . "\n"; return $data; } else { throw new Exception("Error: " . $response); } } // Refund $25.00 refundPayment("pay_abc123xyz", "2500"); ?> ``` ```ruby Ruby theme={null} require 'net/http' require 'json' require 'uri' def refund_payment(payment_id, amount) uri = URI('https://api.digitzs.com/payments') request = Net::HTTP::Post.new(uri) request['x-api-key'] = 'your-api-key' request['Authorization'] = 'Bearer your-app-token' request['appId'] = 'your-app-id' request['Content-Type'] = 'application/json' request.body = { data: { type: 'payments', attributes: { paymentType: 'refund', parentPaymentId: payment_id, transaction: { amount: amount, currency: 'USD' } } } }.to_json response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http| http.request(request) end if response.code == '201' data = JSON.parse(response.body) refund_type = data['data']['attributes']['transaction']['refundType'] action = refund_type == 'void' ? 'Voided' : 'Refunded' puts "#{action} payment: #{data['data']['id']}" data else raise "Error: #{response.body}" end end # Refund $25.00 refund_payment('pay_abc123xyz', '2500') ``` ## Void vs Refund Comparison | Feature | Void | Refund | | ---------------------- | ------------------------------------- | -------------------------------------- | | **Timing** | Same day before 11:59 PM PST | Any time after settlement | | **Processing Speed** | Immediate | 3-10 business days | | **Additional Fees** | None | May incur refund processing fees | | **Fund Return** | Instantly released on customer's card | Processed as credit to customer's card | | **Transaction Record** | Transaction cancelled | New refund transaction created | ## Error Responses ```json 400 Bad Request - Invalid amount theme={null} { "errors": [ { "status": "400", "title": "Bad Request", "detail": "Refund amount exceeds original transaction amount" } ] } ``` ```json 404 Not Found theme={null} { "errors": [ { "status": "404", "title": "Not Found", "detail": "Parent payment not found" } ] } ``` ```json 422 Unprocessable Entity theme={null} { "errors": [ { "status": "422", "title": "Unprocessable Entity", "detail": "Payment has already been fully refunded" } ] } ``` ## Common Error Scenarios **Error:** 404 Not Found **Solution:** Verify the parentPaymentId is correct and the payment exists in your account. **Error:** 400 Bad Request **Solution:** Ensure the refund amount doesn't exceed the original transaction amount or the remaining refundable balance. **Error:** 422 Unprocessable Entity **Solution:** Check the payment status. If already fully refunded, no additional refunds are possible. **Error:** 422 Unprocessable Entity **Solution:** Contact Digitzs support for ACH refund processing. ACH refunds require special handling. ## Important Notes **ACH Transactions:** Do not use this endpoint for ACH transactions. Contact Digitzs support for ACH refund assistance. **Partial Refunds:** Multiple partial refunds are supported up to the original transaction amount. **Void Window:** Process refunds on the same day before 11:59 PM PST to get instant voids instead of multi-day refunds. ## Best Practices 1. **Check Timing:** If same-day, consider the void window for faster processing 2. **Track Refunds:** Monitor all refund transactions for reconciliation 3. **Document Reasons:** Use miscData to record why refunds were issued 4. **Validate Amounts:** Ensure refund amount doesn't exceed original or remaining balance 5. **Customer Communication:** Inform customers about refund processing time (instant void vs 3-10 day refund) 6. **Handle Splits:** Use the split refund endpoint for split payments ## Next Steps Learn how to refund split payments Check refund status # Authentication Source: https://digitzs.mintlify.app/authentication Learn how to authenticate and authorize your requests to the Digitzs API ## Overview The Digitzs API uses a two-step authentication process to ensure secure access to your merchant services: 1. **Authentication** - Verifying your identity 2. **Authorization** - Granting access to API resources All API requests require proper authentication headers. Tokens expire after one hour and must be refreshed. ## Before You Begin You will need the following credentials provided during onboarding: Your unique API key (`x-api-key`) Your application identifier (`appId`) ## Authentication Flow Create an app key using your API key and application ID Use the app key to generate a temporary access token Include the token in your API requests ## Step 1: Generate App Key Create an app key that will be used to generate access tokens. Creating a new app key renders the old key unusable. Store your app key securely. ### Endpoint ``` POST /auth/key ``` ### Request Headers | Header | Value | Description | | -------------- | ------------------ | -------------------------- | | `x-api-key` | Your API key | Provided during onboarding | | `Content-Type` | `application/json` | Standard REST header | ### Request Body ```json theme={null} { "data": { "type": "auth", "attributes": { "appId": "your-application-id" } } } ``` ### Request Parameters | Parameter | Type | Required | Description | | ----------------------- | ------ | -------- | --------------------------------------- | | `data` | object | Yes | Container for API data | | `data.type` | string | Yes | Must be "auth" | | `data.attributes` | object | Yes | Container for authentication attributes | | `data.attributes.appId` | string | Yes | Your application ID from onboarding | ### Response ```json theme={null} { "links": { "self": "https://api.digitzs.com/auth/key" }, "data": { "type": "auth", "id": "your-api-key", "attributes": { "appKey": "generated-app-key" } } } ``` ### Response Parameters | Parameter | Type | Description | | ------------------------ | ------ | ------------------------------------- | | `data.id` | string | Your API key (same as request header) | | `data.attributes.appKey` | string | Generated app key for token creation | ### Code Examples ```javascript Node.js theme={null} const axios = require('axios'); const createAppKey = async () => { try { const response = await axios.post( 'https://api.digitzs.com/auth/key', { data: { type: 'auth', attributes: { appId: 'your-application-id' } } }, { headers: { 'x-api-key': 'your-api-key', 'Content-Type': 'application/json' } } ); const appKey = response.data.data.attributes.appKey; console.log('App Key:', appKey); return appKey; } catch (error) { console.error('Error creating app key:', error.response.data); } }; ``` ```python Python theme={null} import requests import json def create_app_key(): url = "https://api.digitzs.com/auth/key" headers = { "x-api-key": "your-api-key", "Content-Type": "application/json" } payload = { "data": { "type": "auth", "attributes": { "appId": "your-application-id" } } } response = requests.post(url, headers=headers, json=payload) if response.status_code == 201: app_key = response.json()["data"]["attributes"]["appKey"] print(f"App Key: {app_key}") return app_key else: print(f"Error: {response.status_code} - {response.text}") create_app_key() ``` ```php PHP theme={null} [ "type" => "auth", "attributes" => [ "appId" => "your-application-id" ] ] ]); $ch = curl_init($url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if ($httpCode === 201) { $data = json_decode($response, true); $appKey = $data["data"]["attributes"]["appKey"]; echo "App Key: " . $appKey . "\n"; return $appKey; } } createAppKey(); ?> ``` ```ruby Ruby theme={null} require 'net/http' require 'json' require 'uri' def create_app_key uri = URI('https://api.digitzs.com/auth/key') request = Net::HTTP::Post.new(uri) request['x-api-key'] = 'your-api-key' request['Content-Type'] = 'application/json' request.body = { data: { type: 'auth', attributes: { appId: 'your-application-id' } } }.to_json response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http| http.request(request) end if response.code == '201' data = JSON.parse(response.body) app_key = data['data']['attributes']['appKey'] puts "App Key: #{app_key}" app_key end end create_app_key ``` ## Step 2: Create App Token Generate a temporary access token using your app key. This token is required for all subsequent API calls. **Tokens expire after one hour.** You must generate a new token when the previous one expires. ### Endpoint ``` POST /auth/token ``` ### Request Headers | Header | Value | Description | | -------------- | ------------------ | -------------------------- | | `x-api-key` | Your API key | Provided during onboarding | | `Content-Type` | `application/json` | Standard REST header | ### Request Body ```json theme={null} { "data": { "type": "auth", "attributes": { "appKey": "your-app-key-from-step-1" } } } ``` ### Request Parameters | Parameter | Type | Required | Description | | ------------------------ | ------ | -------- | --------------------------------------- | | `data` | object | Yes | Container for API data | | `data.type` | string | Yes | Must be "auth" | | `data.attributes` | object | Yes | Container for authentication attributes | | `data.attributes.appKey` | string | Yes | The app key from Step 1 | ### Response ```json theme={null} { "links": { "self": "https://api.digitzs.com/auth/token" }, "data": { "type": "auth", "id": "your-api-key", "attributes": { "appToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." } } } ``` ### Response Parameters | Parameter | Type | Description | | -------------------------- | ------ | ----------------------------------------------- | | `data.id` | string | Your API key | | `data.attributes.appToken` | string | The access token to use in Authorization header | ### Code Examples ```javascript Node.js theme={null} const axios = require('axios'); const createAppToken = async (appKey) => { try { const response = await axios.post( 'https://api.digitzs.com/auth/token', { data: { type: 'auth', attributes: { appKey: appKey } } }, { headers: { 'x-api-key': 'your-api-key', 'Content-Type': 'application/json' } } ); const appToken = response.data.data.attributes.appToken; console.log('App Token:', appToken); return appToken; } catch (error) { console.error('Error creating app token:', error.response.data); } }; ``` ```python Python theme={null} import requests import json def create_app_token(app_key): url = "https://api.digitzs.com/auth/token" headers = { "x-api-key": "your-api-key", "Content-Type": "application/json" } payload = { "data": { "type": "auth", "attributes": { "appKey": app_key } } } response = requests.post(url, headers=headers, json=payload) if response.status_code == 201: app_token = response.json()["data"]["attributes"]["appToken"] print(f"App Token: {app_token}") return app_token else: print(f"Error: {response.status_code} - {response.text}") app_token = create_app_token("your-app-key") ``` ```php PHP theme={null} [ "type" => "auth", "attributes" => [ "appKey" => $appKey ] ] ]); $ch = curl_init($url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if ($httpCode === 201) { $data = json_decode($response, true); $appToken = $data["data"]["attributes"]["appToken"]; echo "App Token: " . $appToken . "\n"; return $appToken; } } $appToken = createAppToken("your-app-key"); ?> ``` ```ruby Ruby theme={null} require 'net/http' require 'json' require 'uri' def create_app_token(app_key) uri = URI('https://api.digitzs.com/auth/token') request = Net::HTTP::Post.new(uri) request['x-api-key'] = 'your-api-key' request['Content-Type'] = 'application/json' request.body = { data: { type: 'auth', attributes: { appKey: app_key } } }.to_json response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http| http.request(request) end if response.code == '201' data = JSON.parse(response.body) app_token = data['data']['attributes']['appToken'] puts "App Token: #{app_token}" app_token end end app_token = create_app_token('your-app-key') ``` ## Step 3: Making Authenticated Requests Once you have an app token, include it in all API requests using the required headers. ### Required Headers for API Calls | Header | Value | Description | | --------------- | ------------------- | --------------------------------------- | | `Authorization` | `Bearer {appToken}` | Your access token with "Bearer " prefix | | `x-api-key` | Your API key | Your API key from onboarding | | `appId` | Your application ID | Your application ID from onboarding | | `Content-Type` | `application/json` | Standard REST header | The `Authorization` header value **must** be formatted as `Bearer {token}` with: * A capital "B" in "Bearer" * A space between "Bearer" and your token ### Example Authenticated Request ```javascript Node.js theme={null} const axios = require('axios'); const makeAuthenticatedRequest = async (appToken) => { try { const response = await axios.get( 'https://api.digitzs.com/merchants', { headers: { 'Authorization': `Bearer ${appToken}`, 'x-api-key': 'your-api-key', 'appId': 'your-application-id', 'Content-Type': 'application/json' } } ); console.log('Response:', response.data); return response.data; } catch (error) { console.error('Error:', error.response.data); } }; ``` ```python Python theme={null} import requests def make_authenticated_request(app_token): url = "https://api.digitzs.com/merchants" headers = { "Authorization": f"Bearer {app_token}", "x-api-key": "your-api-key", "appId": "your-application-id", "Content-Type": "application/json" } response = requests.get(url, headers=headers) if response.status_code == 200: print("Response:", response.json()) return response.json() else: print(f"Error: {response.status_code} - {response.text}") make_authenticated_request("your-app-token") ``` ```php PHP theme={null} ``` ```ruby Ruby theme={null} require 'net/http' require 'json' require 'uri' def make_authenticated_request(app_token) uri = URI('https://api.digitzs.com/merchants') request = Net::HTTP::Get.new(uri) request['Authorization'] = "Bearer #{app_token}" request['x-api-key'] = 'your-api-key' request['appId'] = 'your-application-id' request['Content-Type'] = 'application/json' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http| http.request(request) end if response.code == '200' data = JSON.parse(response.body) puts data data end end make_authenticated_request('your-app-token') ``` ## Token Management ### Token Expiration App tokens expire after **one hour** from creation. When a token expires, you will receive a `401 Unauthorized` error. ### Refreshing Tokens To refresh an expired token, simply call the `/auth/token` endpoint again with your app key. You do not need to regenerate the app key unless you want to invalidate all existing tokens. ### Best Practices Store your API key and app key securely using environment variables or secret management services Automatically refresh tokens when you receive a 401 error Cache tokens and reuse them until they expire to reduce API calls Track token creation time and proactively refresh before expiration ## Complete Authentication Example Here's a complete example that handles the full authentication flow: ```javascript Node.js theme={null} const axios = require('axios'); class DigitzsAuth { constructor(apiKey, appId) { this.apiKey = apiKey; this.appId = appId; this.appKey = null; this.appToken = null; this.tokenExpiry = null; this.baseURL = 'https://api.digitzs.com'; } async initialize() { this.appKey = await this.createAppKey(); await this.refreshToken(); } async createAppKey() { const response = await axios.post( `${this.baseURL}/auth/key`, { data: { type: 'auth', attributes: { appId: this.appId } } }, { headers: { 'x-api-key': this.apiKey, 'Content-Type': 'application/json' } } ); return response.data.data.attributes.appKey; } async refreshToken() { const response = await axios.post( `${this.baseURL}/auth/token`, { data: { type: 'auth', attributes: { appKey: this.appKey } } }, { headers: { 'x-api-key': this.apiKey, 'Content-Type': 'application/json' } } ); this.appToken = response.data.data.attributes.appToken; this.tokenExpiry = Date.now() + (55 * 60 * 1000); // 55 minutes } async getHeaders() { // Check if token needs refresh (5 min buffer) if (!this.appToken || Date.now() >= this.tokenExpiry) { await this.refreshToken(); } return { 'Authorization': `Bearer ${this.appToken}`, 'x-api-key': this.apiKey, 'appId': this.appId, 'Content-Type': 'application/json' }; } async request(method, endpoint, data = null) { const headers = await this.getHeaders(); const config = { method, url: `${this.baseURL}${endpoint}`, headers }; if (data) { config.data = data; } try { const response = await axios(config); return response.data; } catch (error) { if (error.response?.status === 401) { // Token expired, refresh and retry await this.refreshToken(); headers.Authorization = `Bearer ${this.appToken}`; config.headers = headers; const retryResponse = await axios(config); return retryResponse.data; } throw error; } } } // Usage (async () => { const auth = new DigitzsAuth('your-api-key', 'your-app-id'); await auth.initialize(); // Now you can make requests const merchants = await auth.request('GET', '/merchants'); console.log(merchants); })(); ``` ```python Python theme={null} import requests import time from datetime import datetime, timedelta class DigitzsAuth: def __init__(self, api_key, app_id): self.api_key = api_key self.app_id = app_id self.app_key = None self.app_token = None self.token_expiry = None self.base_url = 'https://api.digitzs.com' def initialize(self): self.app_key = self.create_app_key() self.refresh_token() def create_app_key(self): url = f"{self.base_url}/auth/key" headers = { "x-api-key": self.api_key, "Content-Type": "application/json" } payload = { "data": { "type": "auth", "attributes": { "appId": self.app_id } } } response = requests.post(url, headers=headers, json=payload) response.raise_for_status() return response.json()["data"]["attributes"]["appKey"] def refresh_token(self): url = f"{self.base_url}/auth/token" headers = { "x-api-key": self.api_key, "Content-Type": "application/json" } payload = { "data": { "type": "auth", "attributes": { "appKey": self.app_key } } } response = requests.post(url, headers=headers, json=payload) response.raise_for_status() self.app_token = response.json()["data"]["attributes"]["appToken"] self.token_expiry = datetime.now() + timedelta(minutes=55) def get_headers(self): # Check if token needs refresh (5 min buffer) if not self.app_token or datetime.now() >= self.token_expiry: self.refresh_token() return { "Authorization": f"Bearer {self.app_token}", "x-api-key": self.api_key, "appId": self.app_id, "Content-Type": "application/json" } def request(self, method, endpoint, data=None): headers = self.get_headers() url = f"{self.base_url}{endpoint}" try: response = requests.request(method, url, headers=headers, json=data) response.raise_for_status() return response.json() except requests.exceptions.HTTPError as e: if e.response.status_code == 401: # Token expired, refresh and retry self.refresh_token() headers = self.get_headers() response = requests.request(method, url, headers=headers, json=data) response.raise_for_status() return response.json() raise # Usage auth = DigitzsAuth('your-api-key', 'your-app-id') auth.initialize() # Now you can make requests merchants = auth.request('GET', '/merchants') print(merchants) ``` ## Troubleshooting This error occurs when: * Your token has expired (tokens last 1 hour) * The Authorization header is not properly formatted * Your API key or app ID is incorrect **Solution:** Generate a new token and ensure the Authorization header uses the format `Bearer {token}` with a capital "B" and a space. This error indicates: * Your account is not authorized to access the requested resource * Your API key has been revoked or suspended **Solution:** Contact Digitzs support to verify your account status and permissions. If you receive an error when creating a token: * Your app key may have been regenerated * The app key was not properly stored from Step 1 **Solution:** Regenerate the app key using `/auth/key` and try again. All authenticated requests require three headers: * `Authorization: Bearer {token}` * `x-api-key: {your-api-key}` * `appId: {your-app-id}` **Solution:** Ensure all three headers are included in every request. ## Security Best Practices Never commit API keys or tokens to version control or expose them in client-side code Store credentials in environment variables or secure secret management systems Periodically regenerate your app keys to maintain security Always make requests over HTTPS to encrypt data in transit ## Next Steps Now that you understand authentication, you're ready to start using the API: Set up merchant accounts Start accepting payments Handle errors properly # Error Codes Source: https://digitzs.mintlify.app/error-codes Understanding HTTP status codes and error responses from the Digitzs API ## Overview The Digitzs API uses standard HTTP status codes to indicate the success or failure of API requests. When an error occurs, the API returns a status code that helps you understand what went wrong and how to fix it. Status codes follow the Internet Engineering Task Force (IETF) Request for Comments (RFCs) standards. ## Status Code Categories HTTP status codes are organized into five categories based on the first digit: The request was received, continuing process The request was successfully received, understood, and accepted Further action is necessary to complete the request The request contains bad syntax or cannot be fulfilled The server failed to fulfill an apparently valid request ## HTTP Status Codes ### Success Codes (2xx) The request was successful and the server returned the requested data. **When you'll see it:** * Successfully retrieving merchant data * Successfully retrieving payment information * Successfully listing resources ```json theme={null} { "links": { "self": "https://api.digitzs.com/merchants" }, "data": { "type": "merchants", "id": "merchant-123", "attributes": { ... } } } ``` The request was successful and a new resource was created. **When you'll see it:** * Creating a new merchant account * Processing a new payment * Generating authentication tokens ```json theme={null} { "links": { "self": "https://api.digitzs.com/payments" }, "data": { "type": "payments", "id": "payment-456", "attributes": { ... } } } ``` ### Client Error Codes (4xx) The server cannot process the request due to invalid syntax or missing required parameters. **Common causes:** * Missing required fields in request body * Invalid data format (e.g., non-numeric amount) * Malformed JSON * Invalid parameter values **How to fix:** * Verify all required fields are included * Check data types match the API specification * Validate JSON syntax * Review the error message for specific field issues ```json theme={null} { "errors": [{ "status": "400", "title": "Bad Request", "detail": "The amount field is required" }] } ``` Authentication is required or has failed. The request lacks valid authentication credentials. **Common causes:** * Missing Authorization header * Expired app token (tokens expire after 1 hour) * Invalid or malformed token * Missing x-api-key header **How to fix:** * Generate a new app token using `/auth/token` * Ensure Authorization header format is `Bearer {token}` with capital "B" * Verify your API key is correct * Include all required authentication headers ```json theme={null} { "errors": [{ "status": "401", "title": "Unauthorized", "detail": "An authorization header is required" }] } ``` Reserved for future use. This status code is not currently used by the Digitzs API. The server understood the request but refuses to authorize it. **Common causes:** * Account is not authorized to access the resource * API key has been revoked or suspended * Insufficient permissions for the requested operation * Attempting to access another merchant's data **How to fix:** * Contact Digitzs support to verify account status * Check that you're accessing resources you own * Verify your account permissions ```json theme={null} { "errors": [{ "status": "403", "title": "Forbidden", "detail": "The account is not authorized" }] } ``` The requested resource could not be found on the server. **Common causes:** * Invalid resource ID (merchant ID, payment ID, etc.) * Resource has been deleted * Incorrect API endpoint URL * Typo in the request path **How to fix:** * Verify the resource ID exists and is correct * Check the endpoint URL for typos * Ensure you're using the correct HTTP method * Confirm the resource hasn't been deleted ```json theme={null} { "errors": [{ "status": "404", "title": "Not Found", "detail": "The resource cannot be found" }] } ``` The server timed out waiting for the request. **Common causes:** * Slow network connection * Large request payload * Server processing delays **How to fix:** * Retry the request * Check your network connection * Reduce request payload size if possible * Implement retry logic with exponential backoff ```json theme={null} { "errors": [{ "status": "408", "title": "Request Timeout", "detail": "The server timed out" }] } ``` The request conflicts with the current state of the server. **Common causes:** * Attempting to create a duplicate resource * Race condition with concurrent requests * Editing conflict with another user's changes **How to fix:** * Check if the resource already exists * Implement optimistic locking if handling concurrent updates * Retry the request with updated data ```json theme={null} { "errors": [{ "status": "409", "title": "Conflict", "detail": "There is an editing conflict" }] } ``` The user has sent too many requests in a given amount of time (rate limiting). **Common causes:** * Exceeding API rate limits * Making too many requests in a short time period * Not implementing proper request throttling **How to fix:** * Implement exponential backoff * Add delays between requests * Cache responses when possible * Contact support if you need higher rate limits ```json theme={null} { "errors": [{ "status": "429", "title": "Too Many Requests", "detail": "The user has sent too many requests" }] } ``` ### Server Error Codes (5xx) The server encountered an unexpected condition that prevented it from fulfilling the request. **Common causes:** * Unexpected server-side error * Database connection issues * Unhandled exception in server code **How to fix:** * Retry the request after a short delay * If the error persists, contact Digitzs support * Check Digitzs status page for known issues ```json theme={null} { "errors": [{ "status": "500", "title": "Internal Server Error", "detail": "There was an unexpected error" }] } ``` The server does not recognize the request method or lacks the ability to fulfill it. **Common causes:** * Using an unsupported HTTP method * Calling an endpoint that doesn't support the method * Feature not yet implemented **How to fix:** * Verify you're using the correct HTTP method (GET, POST, PUT, DELETE) * Check the API documentation for supported methods * Ensure the endpoint supports the requested operation ```json theme={null} { "errors": [{ "status": "501", "title": "Not Implemented", "detail": "The request method not recognized" }] } ``` The server received an invalid response from an upstream server. **Common causes:** * Payment processor connection issues * Third-party service unavailable * Network problems between servers **How to fix:** * Retry the request * Wait a few moments and try again * If the error persists, contact Digitzs support ```json theme={null} { "errors": [{ "status": "502", "title": "Bad Gateway", "detail": "The response is invalid" }] } ``` The server is currently unable to handle the request due to temporary overload or maintenance. **Common causes:** * Scheduled maintenance * Server overload * Temporary service disruption **How to fix:** * Wait and retry the request * Check Digitzs status page * Implement retry logic with exponential backoff ```json theme={null} { "errors": [{ "status": "503", "title": "Service Unavailable", "detail": "The server is currently unavailable" }] } ``` The server did not receive a timely response from an upstream server. **Common causes:** * Payment processor timeout * Long-running operation exceeded timeout * Network latency issues **How to fix:** * Retry the request * Check payment status before retrying payment operations * Contact support if timeouts persist ```json theme={null} { "errors": [{ "status": "504", "title": "Gateway Timeout", "detail": "A timely response was not received" }] } ``` ## Error Response Format All error responses from the Digitzs API follow a consistent JSON format: ```json theme={null} { "errors": [ { "status": "400", "title": "Bad Request", "detail": "The amount field is required", "source": { "pointer": "/data/attributes/transaction/amount" } } ] } ``` ### Error Object Fields | Field | Type | Description | | ---------------- | ------ | ---------------------------------------------------------- | | `status` | string | HTTP status code as a string | | `title` | string | Short, human-readable summary of the error | | `detail` | string | Detailed explanation of the specific error | | `source` | object | Optional pointer to the source of the error in the request | | `source.pointer` | string | JSON Pointer to the field that caused the error | ## Handling Errors ### Best Practices Log error responses with full details for debugging and monitoring Retry transient errors (5xx, 408, 429) with exponential backoff Read the error detail field for specific information about what went wrong Display user-friendly error messages instead of raw error responses ### Example Error Handling ```javascript Node.js theme={null} const axios = require('axios'); async function makeAPIRequest(config) { try { const response = await axios(config); return response.data; } catch (error) { if (error.response) { const status = error.response.status; const errorData = error.response.data; // Handle specific error codes switch (status) { case 401: console.error('Authentication failed. Refreshing token...'); // Refresh token and retry break; case 404: console.error('Resource not found:', errorData.errors[0].detail); throw new Error('Resource not found'); case 429: console.error('Rate limit exceeded. Retrying after delay...'); await delay(5000); return makeAPIRequest(config); // Retry case 500: case 502: case 503: case 504: console.error('Server error. Retrying...'); await delay(2000); return makeAPIRequest(config); // Retry default: console.error('API Error:', errorData); throw error; } } else { // Network error or no response console.error('Network error:', error.message); throw error; } } } function delay(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } ``` ```python Python theme={null} import requests import time from requests.exceptions import RequestException def make_api_request(method, url, **kwargs): max_retries = 3 retry_delay = 2 for attempt in range(max_retries): try: response = requests.request(method, url, **kwargs) response.raise_for_status() return response.json() except requests.exceptions.HTTPError as e: status_code = e.response.status_code error_data = e.response.json() # Handle specific error codes if status_code == 401: print("Authentication failed. Refreshing token...") # Refresh token and retry break elif status_code == 404: error_detail = error_data['errors'][0]['detail'] print(f"Resource not found: {error_detail}") raise Exception("Resource not found") elif status_code == 429: print("Rate limit exceeded. Retrying after delay...") time.sleep(5) continue elif status_code in [500, 502, 503, 504]: if attempt < max_retries - 1: print(f"Server error. Retrying (attempt {attempt + 1})...") time.sleep(retry_delay * (attempt + 1)) continue else: print("Max retries reached for server error") raise else: print(f"API Error: {error_data}") raise except RequestException as e: print(f"Network error: {str(e)}") if attempt < max_retries - 1: time.sleep(retry_delay) continue raise # Usage try: data = make_api_request('GET', 'https://api.digitzs.com/merchants') print(data) except Exception as e: print(f"Request failed: {str(e)}") ``` ## Quick Reference Table | Status Code | Meaning | Action Required | | ----------- | --------------------- | ----------------------------- | | 200 | OK | Request successful | | 201 | Created | Resource created successfully | | 400 | Bad Request | Fix request parameters | | 401 | Unauthorized | Refresh authentication token | | 403 | Forbidden | Check account permissions | | 404 | Not Found | Verify resource ID | | 408 | Request Timeout | Retry the request | | 409 | Conflict | Resolve resource conflict | | 429 | Too Many Requests | Implement rate limiting | | 500 | Internal Server Error | Retry or contact support | | 501 | Not Implemented | Check HTTP method | | 502 | Bad Gateway | Retry the request | | 503 | Service Unavailable | Wait and retry | | 504 | Gateway Timeout | Retry the request | ## Preventing Common Errors * Implement automatic token refresh before expiration * Cache tokens and track their expiration time * Use the correct Authorization header format: `Bearer {token}` * Include all required headers: `Authorization`, `x-api-key`, and `appId` * Validate all input data before sending requests * Use the correct data types (strings, numbers, etc.) * Include all required fields * Test with the API documentation examples * Implement request throttling in your application * Cache responses when possible * Use batch operations instead of individual requests * Monitor your request rate * Implement exponential backoff for retries * Set reasonable timeout values * Log errors for monitoring * Have a fallback strategy for critical operations ## Need Help? If you encounter persistent errors or need assistance troubleshooting, our support team is here to help. ## Additional Resources Learn how to properly authenticate your requests Explore detailed endpoint documentation # Digitzs API Source: https://digitzs.mintlify.app/index A quick, painless, secure, profitable way to build merchant services into your app The Digitzs API provides a quick, painless, secure, profitable way to build merchant services into your app. Click [here](https://digitzs.com/wp-content/uploads/2019/04/API-User-Manual.pdf) to learn more about the Digitzs API, and [here](https://digitzs.com/wp-content/uploads/2019/07/Digitzs-Quick-Start-Guide.pdf) for the Digitzs Quick Start Guide. ## Merchant Services Your users can open a merchant account in real time—without ever leaving your site—and process transactions immediately. You earn revenue on every sale. **No Abandonment** Account creation, payment processing, and transaction reporting all happen inside your app. Better UX = Higher Conversions **No Waiting** Accounts are created in real-time and merchants can accept payments immediately. No more waiting around for approvals. **No Receivables** Automatically split the proceeds from any sale to collect your platform or marketplace fees. No more invoicing. Get your piece of the pie today. **No Nonsense** Merchants pay a flat rate of 2.9% + 30¢ per transaction. No surprise fees. No gimmicks. Predictable costs make life easier. **Instant Funding** Merchants can get funds instantly when a customer pays with a qualified debit card. Restrictions apply. Reserves required. **Lifetime revenue** Payments are now a profit center. Earn income every time a transaction is processed. Making money while you sleep is always nice. ## Headers As a part of authentication into the Digitzs API, there are different headers that are required to successfully call functions. They are as listed below. **x-api-key** This is your API Key, provided during on-boarding **Authorization** This is your app token, generated by calling /auth/token (as described below). This token expires every hour. **NOTE:** the value needs `Bearer` prepended to your app token. This is with a capital "B" and a space between Bearer and your token. **appId** This is your application ID, provided during on-boarding. ## Errors Status codes are issued by a server in response to a client's request made to the server. They include codes from [Internet Engineering Task Force](https://www.ietf.org/) (IETF) Request for Comments (RFCs), other specifications, and some additional codes used in some common applications of the Hypertext Transfer Protocol (HTTP). There are five status code categories. The first digit of the status code defines the class of response. The last two digits do not have any class or categorization role. 1 – Informational. The request was received, continuing process. 2 – Successful. The request was successfully received, understood, and accepted. 3 – Redirection. There is further action necessary in order to complete the request. 4 – Client Error. The request contains bad syntax or cannot be fulfilled. 5 – Server Error. The server failed to fulfill an apparently valid request. Click [here](https://digitzs.com/wp-content/uploads/2019/04/API-User-Manual.pdf) to learn more about the Digitzs API. | HTTP Error Codes | Meaning | | --------------------------- | ------------------------------------ | | 200 - OK | The request was successful. | | 400 - Bad Request | The requested item does not exist. | | 401 - Unauthorized | An authorization header is required. | | 402 - Payment Required | Reserved for future use. | | 403 - Forbidden | The account is not authorized. | | 404 - Not Found | The resource cannot be found. | | 408 - Request Timeout | The server timed out. | | 409 - Conflict | Three is an editing conflict. | | 429 - Too Many Requests | The user has sent too many requests. | | 500 - Internal Server Error | There was an unexpected error. | | 501 - Not Implemented | The request method not recognized. | | 502 - Bad Gateway | The response is invalid. | | 503 - Service Unavailable | The server is currently unavailable. | | 504 - Gateway Timeout | A timely response was not received. | # Quickstart Guide Source: https://digitzs.mintlify.app/quickstart Get up and running with the Digitzs API in under 10 minutes ## Welcome This quickstart guide will walk you through making your first API call to the Digitzs API. By the end of this guide, you'll have authenticated with the API, created a merchant account, and processed a test payment. This guide uses test credentials and test card numbers. No real money will be processed. ## Before You Begin You'll need the following credentials provided during onboarding: Your unique `x-api-key` Your `appId` Ensure you're using test credentials ## Step 1: Generate Authentication Tokens First, generate the necessary authentication tokens to make API calls. ### 1.1 Create App Key ```bash cURL theme={null} curl -X POST https://api.digitzs.com/auth/key \ -H "x-api-key: YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "data": { "type": "auth", "attributes": { "appId": "YOUR_APP_ID" } } }' ``` ```javascript JavaScript theme={null} const axios = require('axios'); const API_KEY = 'YOUR_API_KEY'; const APP_ID = 'YOUR_APP_ID'; async function createAppKey() { const response = await axios.post( 'https://api.digitzs.com/auth/key', { data: { type: 'auth', attributes: { appId: APP_ID } } }, { headers: { 'x-api-key': API_KEY, 'Content-Type': 'application/json' } } ); return response.data.data.attributes.appKey; } const appKey = await createAppKey(); console.log('App Key:', appKey); ``` ```python Python theme={null} import requests API_KEY = 'YOUR_API_KEY' APP_ID = 'YOUR_APP_ID' def create_app_key(): response = requests.post( 'https://api.digitzs.com/auth/key', headers={ 'x-api-key': API_KEY, 'Content-Type': 'application/json' }, json={ 'data': { 'type': 'auth', 'attributes': { 'appId': APP_ID } } } ) response.raise_for_status() return response.json()['data']['attributes']['appKey'] app_key = create_app_key() print(f'App Key: {app_key}') ``` **Response:** ```json theme={null} { "data": { "type": "auth", "id": "YOUR_API_KEY", "attributes": { "appKey": "generated-app-key-abc123" } } } ``` Save the `appKey` from the response. You'll need it for the next step. ### 1.2 Create App Token Use the app key to generate an access token: ```bash cURL theme={null} curl -X POST https://api.digitzs.com/auth/token \ -H "x-api-key: YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "data": { "type": "auth", "attributes": { "appKey": "YOUR_APP_KEY_FROM_STEP_1" } } }' ``` ```javascript JavaScript theme={null} async function createAppToken(appKey) { const response = await axios.post( 'https://api.digitzs.com/auth/token', { data: { type: 'auth', attributes: { appKey } } }, { headers: { 'x-api-key': API_KEY, 'Content-Type': 'application/json' } } ); return response.data.data.attributes.appToken; } const appToken = await createAppToken(appKey); console.log('App Token:', appToken); ``` ```python Python theme={null} def create_app_token(app_key): response = requests.post( 'https://api.digitzs.com/auth/token', headers={ 'x-api-key': API_KEY, 'Content-Type': 'application/json' }, json={ 'data': { 'type': 'auth', 'attributes': { 'appKey': app_key } } } ) response.raise_for_status() return response.json()['data']['attributes']['appToken'] app_token = create_app_token(app_key) print(f'App Token: {app_token}') ``` **Response:** ```json theme={null} { "data": { "type": "auth", "id": "YOUR_API_KEY", "attributes": { "appToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." } } } ``` App tokens expire after 1 hour. Implement token refresh logic in your application. ## Step 2: List Merchants Check existing merchants in your account: ```bash theme={null} curl -X GET https://api.digitzs.com/merchants \ -H "Authorization: Bearer YOUR_APP_TOKEN" \ -H "x-api-key: YOUR_API_KEY" \ -H "appId: YOUR_APP_ID" ``` ## Test Cards Use these test card numbers in test mode: | Card Number | Result | | ------------------ | ------------------ | | `4111111111111111` | Successful charge | | `4000000000000002` | Card declined | | `4000000000009995` | Insufficient funds | Use any future date for expiration and any 3-digit CVV for test cards. ## What's Next? Congratulations! You've successfully authenticated with the Digitzs API. ### Next Steps Set up merchant accounts Accept card and ACH payments Handle errors properly Learn advanced authentication ## Need Help? Our team is here to help with any questions or issues