### Setup and Start NextJS Project Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/README.md Commands to install dependencies and start the NextJS development server. ```bash cd "SmartFields Starter Projects/NextJS" npm install npm run dev # Runs on http://localhost:3000 ``` -------------------------------- ### Setup and Start React Project Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/README.md Commands to install dependencies and start the React development server. ```bash cd "SmartFields Starter Projects/React" npm install npm start # Runs on http://localhost:3000 ``` -------------------------------- ### Setup and Run Django Project Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/README.md Commands to install requirements and start the Django development server. ```bash cd "SmartFields Starter Projects/Django" pip install -r requirements.txt python manage.py runserver ``` -------------------------------- ### Setup JavaScript/Node.js Express Project Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/README.md Commands to install dependencies and start the Express server. ```bash cd "Signatures/Javascript Payouts Payins" npm install npm start # Runs on http://localhost:3000 ``` -------------------------------- ### Install Dependencies Source: https://github.com/dlocal/starter-code-examples/blob/main/Signatures/Javascript Payouts Payins/README.md Run this command to install the necessary project dependencies. ```bash npm install ``` -------------------------------- ### Complete Usage Example Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/api-reference-go.md A full implementation example demonstrating the complete flow from payload creation to HTTP request execution. ```go package main import ( "bytes" "crypto/hmac" "crypto/sha256" "encoding/json" "fmt" "io/ioutil" "net/http" "time" "github.com/google/uuid" ) type Payer struct { Name string `json:"name"` Email string `json:"email"` Document string `json:"document"` UserReference string `json:"user_reference"` } type Card struct { HolderName string `json:"holder_name"` Number string `json:"number"` CVV string `json:"cvv"` ExpirationMonth int `json:"expiration_month"` ExpirationYear int `json:"expiration_year"` } func main() { apiURL := "https://sandbox.dlocal.com/secure_payments" timestamp := time.Now().UTC().Format("2006-01-02T15:04:05.999Z") login := "your-login" transKey := "your-trans-key" secretKey := "your-secret-key" payer := Payer{ Name: "John Doe", Email: "john@example.com", Document: "12345678900", UserReference: "user123", } card := Card{ HolderName: "John Doe", Number: "4111111111111111", CVV: "123", ExpirationMonth: 12, ExpirationYear: 2025, } requestPayload := map[string]interface{}{ "amount": 120.00, "currency": "USD", "country": "BR", "payment_method_id": "CARD", "payment_method_flow": "DIRECT", "payer": payer, "card": card, "order_id": uuid.New().String(), "notification_url": "http://merchant.com/notifications", } body, _ := json.Marshal(requestPayload) concatenatedData := fmt.Sprintf("%s%s%s", login, timestamp, body) keyBytes := []byte(secretKey) hashBytes := hmac.New(sha256.New, keyBytes) hashBytes.Write([]byte(concatenatedData)) signature := hashBytes.Sum(nil) headers := map[string]string{ "X-Date": timestamp, "X-Login": login, "X-Trans-Key": transKey, "Authorization": fmt.Sprintf("V2-HMAC-SHA256, Signature: %x", signature), "Content-Type": "application/json", } client := http.Client{} req, _ := http.NewRequest("POST", apiURL, bytes.NewBuffer(body)) for key, value := range headers { req.Header.Set(key, value) } response, _ := client.Do(req) defer response.Body.Close() responseBody, _ := ioutil.ReadAll(response.Body) if response.StatusCode == http.StatusOK { fmt.Println("Payment request successful!") fmt.Println("Response:", string(responseBody)) } else { fmt.Printf("Payment request failed. Status: %d\n", response.StatusCode) } } ``` -------------------------------- ### Install Maven Dependencies Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/configuration.md Execute the installation command to build the project. ```bash mvn clean install ``` -------------------------------- ### Install Django Source: https://github.com/dlocal/starter-code-examples/blob/main/SmartFields Starter Projects/Django/README.md Install the Django framework using pip. ```bash pip install Django ``` -------------------------------- ### Full Usage Example Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/api-reference-python.md Complete implementation example including signature generation and request execution. ```python from datetime import datetime from uuid import uuid4 import requests import json import hmac import hashlib def generate_hmac_sha256_signature(payload, secret_key): key_bytes = bytes(secret_key, 'utf-8') payload_bytes = bytes(payload, 'utf-8') return hmac.new(key_bytes, payload_bytes, hashlib.sha256).hexdigest() api_url = "https://sandbox.dlocal.com/api_curl/cashout_api/request_cashout" login = "your-login" trans_key = "your-trans-key" secret_key = "your-secret-key" timestamp = datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ") external_id = str(uuid4()) request_payload = { "login": login, "pass": trans_key, "external_id": external_id, "document_id": "12354875", "document_type": "PASS", "beneficiary_name": "JUAN", "beneficiary_lastname": "RUIZ", "country": "DO", "bank_code": "1", "bank_account": "1234567891", "account_type": "S", "amount": "119148.00", "currency": "DOP", "notification_url": "https://thisisawebsite.net/payments", "type": "json" } request_payload_json = json.dumps(request_payload) signature = generate_hmac_sha256_signature(request_payload_json, secret_key) headers = { "X-Date": timestamp, "X-Login": login, "X-Trans-Key": trans_key, "payload-signature": signature } response = requests.post(api_url, json=request_payload, headers=headers) print(response.json()) ``` -------------------------------- ### Setup and Execution Commands Source: https://github.com/dlocal/starter-code-examples/blob/main/Signatures/C Commands to clone the repository, restore dependencies, and run the C# application. ```bash git clone https://github.com/tam-dlocal/dLocal-Starter-Code-Examples.git cd "dLocal-Starter-Code-Examples/Signatures/C# Payins" ``` ```bash dotnet restore ``` ```bash dotnet run ``` -------------------------------- ### Usage example for addFields Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/api-reference-smartfields-react.md Example showing how to configure and call the addFields function to initialize the library. ```javascript const config = { url: 'https://checkout.dlocal.com/fields/smartfields.js', api_key: 'pk_test_...', country: 'BR' }; addFields(() => { console.log('SmartFields library loaded'); }, config); ``` -------------------------------- ### Install Go Dependencies Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/configuration.md Commands to download and tidy Go modules. ```bash go mod download go mod tidy ``` -------------------------------- ### Install Dependencies Source: https://github.com/dlocal/starter-code-examples/blob/main/Signatures/Python Payouts Payins/README.md Install the required Python packages listed in the requirements file. ```bash python -m pip install -r requirements.txt ``` -------------------------------- ### Clone and Navigate to Repository Source: https://github.com/dlocal/starter-code-examples/blob/main/Signatures/Python Payouts Payins/README.md Initial steps to download the project and enter the specific directory for Python examples. ```bash git clone https://github.com/tam-dlocal/dLocal-Starter-Code-Examples.git cd "dLocal-Starter-Code-Examples/Signatures/Python-Payouts-Payins" ``` -------------------------------- ### Define Go Module Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/configuration.md Example go.mod file for the project. ```text module dlocal-go-example go 1.21 require github.com/google/uuid v1.5.0 ``` -------------------------------- ### Run development server Source: https://github.com/dlocal/starter-code-examples/blob/main/SmartFields Starter Projects/React/README.md Starts the application in development mode and opens it in the browser. ```bash npm start ``` -------------------------------- ### Clone and Navigate to Repository Source: https://github.com/dlocal/starter-code-examples/blob/main/Signatures/C Commands to clone the starter code repository and enter the specific directory for the C# Payouts example. ```bash git clone https://github.com/tam-dlocal/dLocal-Starter-Code-Examples.git cd "dLocal-Starter-Code-Examples/Signatures/C# Payouts" ``` -------------------------------- ### Signature Calculation Example Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/endpoints.md Example values and result for the signature calculation process. ```text login = "merchant123" X-Date = "2024-01-15T10:30:45.123Z" body = '{"amount":120.00,"currency":"USD","country":"BR",...}' concatenated = "merchant1232024-01-15T10:30:45.123Z{...}" signature = HMAC-SHA256(concatenated, secret_key).hex() // Result: "a1b2c3d4e5f6..." Authorization: V2-HMAC-SHA256, Signature: a1b2c3d4e5f6... ``` -------------------------------- ### HMAC Signature Usage Example Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/api-reference-go.md Example demonstrating how to call the signature generation function with a payload and secret key. ```go payload := `{"amount":"100.00","currency":"USD"}` secret := "my-secret-key" sig := generateHMACSHA256Signature(payload, secret) fmt.Println(sig) // e.g., 'a1b2c3d4e5f6...' ``` -------------------------------- ### Run the Development Server Source: https://github.com/dlocal/starter-code-examples/blob/main/SmartFields Starter Projects/Django/README.md Start the local Django development server to view the application. ```bash python manage.py runserver ``` -------------------------------- ### Payment Request Example Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/types.md A complete JSON example of a Payment Request including Payer and Card details. ```json { "amount": 120.00, "currency": "USD", "country": "BR", "payment_method_id": "CARD", "payment_method_flow": "DIRECT", "payer": { "name": "John Doe", "email": "john@example.com", "document": "12345678900", "user_reference": "user_123" }, "card": { "holder_name": "John Doe", "number": "4111111111111111", "cvv": "123", "expiration_month": 12, "expiration_year": 2025 }, "order_id": "123e4567-e89b-12d3-a456-426614174000", "notification_url": "https://merchant.com/webhook" } ``` -------------------------------- ### SignatureCalculator Usage Example Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/api-reference-csharp.md Demonstrates how to invoke the SignatureCalculator function with required parameters. ```csharp string signature = SignatureCalculator( login, // "your-login" timestamp, // "2024-01-15T10:30:45.123Z" secretKey, // "your-secret-key" requestPayload // JSON string ); ``` -------------------------------- ### Install NuGet Dependencies Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/configuration.md Install required packages using the PowerShell package manager console. ```powershell Install-Package Newtonsoft.Json Install-Package RestSharp ``` -------------------------------- ### Install UUID dependency Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/api-reference-go.md Command to install the required Google UUID package for Go projects. ```bash go get github.com/google/uuid ``` -------------------------------- ### Run the Next.js development server Source: https://github.com/dlocal/starter-code-examples/blob/main/SmartFields Starter Projects/NextJS/README.md Commands to start the local development environment using various package managers. ```bash npm run dev # or yarn dev # or pnpm dev ``` -------------------------------- ### Configure Notification URL Source: https://github.com/dlocal/starter-code-examples/blob/main/Signatures/Javascript Payouts Payins/README.md Example of setting the notification URL in the project configuration. ```json "notification_url": "https://f0cf-179-48-116-200.ngrok-free.app/notifications" } ``` -------------------------------- ### Payouts Endpoint Example Body Source: https://github.com/dlocal/starter-code-examples/blob/main/Signatures/Javascript Payouts Payins/README.md Example JSON payload for the POST /payouts endpoint. ```json { "external_id": "#RANDOMALPHANUMERIC:9", "document_id": "769237836", "document_type": "RUT", "beneficiary_name": "Dlocal Chile", "beneficiary_lastname": "SPA", "country": "CL", "bank_code": "39", "bank_account": "0213880962", "account_type": "C", "amount": "100", "currency": "CLP", "type": "json", "purpose": "EPFAMT" } ``` -------------------------------- ### Payment Request Example Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/api-reference-payins-javascript.md Example of constructing a payment request object and sending it to the local Express endpoint using Axios. ```javascript const axios = require('axios'); const paymentRequest = { amount: 120.00, currency: 'USD', country: 'BR', payment_method_id: 'CARD', payment_method_flow: 'DIRECT', payer: { name: 'Thiago Gabriel', email: 'thiago@example.com', document: '07674084973', user_reference: '12345' }, card: { holder_name: 'Thiago Gabriel', number: '4111111111111111', cvv: '123', expiration_month: 10, expiration_year: 2040 }, order_id: '123e4567-e89b-12d3-a456-426614174000', notification_url: 'http://merchant.com/notifications' }; const response = await axios.post( 'http://localhost:3000/payins', paymentRequest ); console.log('Success:', response.data); // Output: { message: 'Payment request successful', response: {...} } ``` -------------------------------- ### Payins Endpoint Example Body Source: https://github.com/dlocal/starter-code-examples/blob/main/Signatures/Javascript Payouts Payins/README.md Example JSON payload for the POST /payins endpoint. ```json { "amount": "100", "currency": "USD", "country": "BR", "payment_method_id": "PQ", "payment_method_flow": "REDIRECT", "payer": { "name": "Thiago Gabriel", "email": "thiago@example.com", "document": "53033315550", "user_reference": "12345", "address": { "state": "Rio de Janeiro", "city": "Volta Redonda", "zip_code": "27275-595", "street": "Servidao B-1", "number": "1106" }, "ip": "2001:0db8:0000:0000:0000:ff00:0042:8329", "device_id": "2fg3d4gf234" }, "order_id": "14124" } ``` -------------------------------- ### Client-side Payout Request Example Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/api-reference-payouts-javascript.md Example of sending a payout request to the local server endpoint using Axios. ```javascript const axios = require('axios'); const payoutRequest = { external_id: '123e4567-e89b-12d3-a456-426614174000', document_id: '12354875', document_type: 'PASS', beneficiary_name: 'JUAN', beneficiary_lastname: 'RUIZ', country: 'DO', bank_code: '1', bank_account: '1234567891', account_type: 'S', amount: '119148.00', currency: 'DOP', comments: 'Payout for order #12345' }; // POST to your server's /payouts endpoint const response = await axios.post('http://localhost:3000/payouts', payoutRequest); console.log(response.data); ``` -------------------------------- ### CSV output format example Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/api-reference-notifications-javascript.md Shows the expected format of the CSV file where notifications are logged. ```csv Payment Id,Payment Status,Payment Method,Order Id,Creation Date,Updated Date PAY-123456789,COMPLETED,CARD,123e4567-e89b-12d3-a456-426614174000,2024-01-15T10:30:45Z,2024-01-15T10:30:46.123Z PAY-123456790,FAILED,BANK_TRANSFER,456e7890-f1a2-34b5-c678-901234567890,2024-01-15T10:31:00Z,2024-01-15T10:31:01.456Z ``` -------------------------------- ### Complete Payout Request Example Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/api-reference-go.md Demonstrates the full flow of generating an HMAC-SHA256 signature, setting required headers, and executing a POST request to the dLocal API. ```go package main import ( "bytes" "crypto/hmac" "crypto/sha256" "encoding/json" "fmt" "io/ioutil" "net/http" "time" "github.com/google/uuid" ) func generateHMACSHA256Signature(payload, secretKey string) string { keyBytes := []byte(secretKey) payloadBytes := []byte(payload) hash := hmac.New(sha256.New, keyBytes) hash.Write(payloadBytes) signature := hash.Sum(nil) return fmt.Sprintf("%x", signature) } func main() { apiURL := "https://sandbox.dlocal.com/api_curl/cashout_api/request_cashout" timestamp := time.Now().UTC().Format("2006-01-02T15:04:05Z") login := "your-login" transKey := "your-trans-key" secretKey := "your-secret-key" externalID := uuid.New().String() requestPayload := map[string]interface{}{ "login": login, "pass": transKey, "external_id": externalID, "document_id": "12354875", "document_type": "PASS", "beneficiary_name": "JUAN", "beneficiary_lastname": "RUIZ", "country": "DO", "bank_code": "1", "bank_account": "1234567891", "account_type": "S", "amount": "119148.00", "currency": "DOP", "notification_url": "https://thisisawebsite.net/payments", "type": "json", } requestPayloadJSON, _ := json.Marshal(requestPayload) signature := generateHMACSHA256Signature(string(requestPayloadJSON), secretKey) headers := map[string]string{ "X-Date": timestamp, "X-Login": login, "X-Trans-Key": transKey, "Payload-Signature": signature, "Content-Type": "application/json", } client := http.Client{} req, _ := http.NewRequest("POST", apiURL, bytes.NewBuffer(requestPayloadJSON)) for key, value := range headers { req.Header.Set(key, value) } response, _ := client.Do(req) defer response.Body.Close() responseBody, _ := ioutil.ReadAll(response.Body) if response.StatusCode == http.StatusOK { fmt.Println("Payout request successful!") fmt.Println("Response:", string(responseBody)) } else { fmt.Printf("Payout request failed. Status: %d\n", response.StatusCode) } } ``` -------------------------------- ### Card Object Example Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/types.md A sample JSON representation of a Card object. ```json { "holder_name": "John Doe", "number": "4111111111111111", "cvv": "123", "expiration_month": 12, "expiration_year": 2025 } ``` -------------------------------- ### Usage Example for HMAC Signature Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/api-reference-java.md Demonstrates how to invoke the signature generation method with sample data and a secret key. ```java String data = "merchant123" + "2024-01-15T10:30:45.000+00:00" + "{\"amount\":120.00}"; String secretKey = "your-secret-key"; String signature = generateHMACSHA256Signature(data, secretKey); System.out.println(signature); // e.g., "a1b2c3d4e5f6..." ``` -------------------------------- ### Construct API Query URLs Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/api-reference-payment-methods-javascript.md Example of building a full API URL by appending country query parameters to the base endpoint. ```javascript const apiURL = 'https://api-certs.dlocal.com/payments-methods?country'; // Later: const fullURL = `${apiURL}=${requestPayload.country}`; ``` -------------------------------- ### Example Notification Payload Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/types.md A sample JSON object for a payment status notification. ```json { "id": "PAY-123456789", "status": "COMPLETED", "payment_method_id": "CARD", "order_id": "order-uuid-123", "created_date": "2024-01-15T10:30:45Z", "amount": 120.00, "currency": "USD" } ``` -------------------------------- ### Example Payout Request Payload Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/types.md A sample JSON object for a payout request. ```json { "login": "merchant123", "pass": "trans_key_123", "external_id": "payout-uuid-123", "document_id": "12354875", "document_type": "PASS", "beneficiary_name": "Juan", "beneficiary_lastname": "Ruiz", "country": "DO", "bank_code": "001", "bank_account": "1234567891", "account_type": "S", "amount": "119148.00", "currency": "DOP", "comments": "Monthly payout", "extra_info": { "internal_ref": "payout-001" }, "notification_url": "https://merchant.com/payout-webhook", "type": "json" } ``` -------------------------------- ### Usage Example for HMAC-SHA256 Signature Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/api-reference-python.md Shows how to call the signature generation function with a sample JSON payload. ```python payload_json = '{"amount":"100.00","currency":"USD"}' secret = "my-secret-key" sig = generate_hmac_sha256_signature(payload_json, secret) print(sig) # e.g., 'a1b2c3d4e5f6...' ``` -------------------------------- ### Clone the repository Source: https://github.com/dlocal/starter-code-examples/blob/main/SmartFields Starter Projects/Django/README.md Use this command to download the starter project from GitHub. ```bash git clone https://github.com/tam-dlocal/dLocal-Starter-Code-Examples.git ``` -------------------------------- ### Project Directory Structure Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/README.md Overview of the starter-code-examples repository organization. ```text starter-code-examples/ ├── Signatures/ │ ├── C# Payins/ │ ├── C# Payouts/ │ ├── Go Payouts Payins/ │ ├── Java Payins/ │ ├── Java Payouts/ │ ├── Javascript Payouts Payins/ │ └── Python Payouts Payins/ ├── SmartFields Starter Projects/ │ ├── Django/ │ ├── NextJS/ │ └── React/ └── README.md ``` -------------------------------- ### Navigate to the project directory Source: https://github.com/dlocal/starter-code-examples/blob/main/SmartFields Starter Projects/Django/README.md Change the current working directory to the Django starter project folder. ```bash cd "SmartFields Starter Projects/Django" ``` -------------------------------- ### Build and Run C# Project Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/README.md Commands to build and execute the .NET application. ```bash cd "Signatures/C# Payins/C# Payins" dotnet build dotnet run ``` -------------------------------- ### Configuration management with environment variables Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/api-reference-go.md Retrieve configuration values using environment variables. ```go login := os.Getenv("DLOCAL_LOGIN") ``` -------------------------------- ### Payer Object Example Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/types.md A sample JSON representation of a Payer object. ```json { "name": "John Doe", "email": "john@example.com", "document": "12345678900", "user_reference": "user_123" } ``` -------------------------------- ### Clone and Run Payouts Project Source: https://github.com/dlocal/starter-code-examples/blob/main/Signatures/Go Payouts Payins/README.md Commands to set up and execute the Payouts Go project. ```bash git clone https://github.com/hlatki01/Go-Payouts-Payins.git ``` ```bash cd Go-Payouts-Payins ``` ```bash go run payouts.go ``` -------------------------------- ### Build for production Source: https://github.com/dlocal/starter-code-examples/blob/main/SmartFields Starter Projects/React/README.md Bundles the application into the build folder with production optimizations. ```bash npm run build ``` -------------------------------- ### Clone and Run Payins Project Source: https://github.com/dlocal/starter-code-examples/blob/main/Signatures/Go Payouts Payins/README.md Commands to set up and execute the Payins Go project. ```bash git clone https://github.com/tam-dlocal/dLocal-Starter-Code-Examples.git ``` ```bash cd "dLocal-Starter-Code-Examples/Signatures/Go Payouts Payins" ``` ```bash go run payins.go ``` -------------------------------- ### Run Go Payouts and Payins Project Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/README.md Commands to download dependencies and run the Go modules. ```bash cd "Signatures/Go Payouts Payins" go mod download go run payins.go go run payouts.go ``` -------------------------------- ### Define Main Entry Point Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/api-reference-java.md The main method signature for executing the payment request flow. ```java public static void main(String[] args) ``` -------------------------------- ### Construct and Send HTTP Request Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/api-reference-go.md Sets request headers and executes the POST request using the standard HTTP client. ```go import ( "bytes" "io" "net/http" ) headers := map[string]string{ "X-Date": timestamp, "X-Login": login, "X-Trans-Key": transKey, "Payload-Signature": signature, "Content-Type": "application/json", } client := http.Client{} req, err := http.NewRequest("POST", apiURL, bytes.NewBuffer(requestPayloadJSON)) if err != nil { handleError("Error creating request:", err) return } for key, value := range headers { req.Header.Set(key, value) } response, err := client.Do(req) if err != nil { handleError("Error sending request:", err) return } defer response.Body.Close() ``` -------------------------------- ### Configure HTTPS Agent with Certificates Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/api-reference-certificate-auth-javascript.md Loads private keys and certificates from the file system to initialize an HTTPS agent. ```javascript const fs = require('fs'); const https = require('https'); const sslOptions = { key: fs.readFileSync('./misc/private-key.pem'), cert: fs.readFileSync('./misc/server.crt.pem'), }; const agent = new https.Agent({ key: sslOptions.key, cert: sslOptions.cert }); ``` -------------------------------- ### GET /payments-methods Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/endpoints.md Retrieves available payment methods, requiring V2 HMAC authentication and mTLS. ```APIDOC ## GET /payments-methods ### Description Retrieves payment methods. ### Method GET ### Endpoint /payments-methods ### Authentication V2 HMAC and mTLS (Client certificate required) ``` -------------------------------- ### GET /payments-methods Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/endpoints.md Retrieve available payment methods for a specific country using the dLocal API. ```APIDOC ## GET /payments-methods ### Description Retrieve available payment methods for a country. This endpoint requires client certificate authentication and an HMAC signature. ### Method GET ### Endpoint https://api-certs.dlocal.com/payments-methods ### Parameters #### Query Parameters - **country** (string) - Required - 2-letter country code (BR, MX, AR, etc.) ### Response #### Success Response (200) - **id** (string) - Unique method identifier - **name** (string) - Display name - **description** (string) - Human-readable description - **countries** (array) - Supported country codes - **enabled** (boolean) - Whether currently active - **icon_url** (string) - URL to method icon image #### Response Example [ { "id": "CARD", "name": "Credit Card", "description": "Visa, Mastercard, Amex", "countries": ["BR", "MX", "AR"], "enabled": true, "icon_url": "https://cdn.dlocal.com/payment-icons/card.png" } ] ``` -------------------------------- ### Restore and Run Application Source: https://github.com/dlocal/starter-code-examples/blob/main/Signatures/C Commands to restore required NuGet packages and execute the C# console application. ```bash dotnet restore ``` ```bash dotnet run ``` -------------------------------- ### Initialize Python Configuration Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/configuration.md Loads environment variables using python-dotenv and maps them to an API_CONFIG dictionary. ```python import os from dotenv import load_dotenv load_dotenv() DLOCAL_LOGIN = os.getenv('DLOCAL_LOGIN', 'x') DLOCAL_TRANS_KEY = os.getenv('DLOCAL_TRANS_KEY', 'x') DLOCAL_SECRET_KEY = os.getenv('DLOCAL_SECRET_KEY', 'x') DLOCAL_API_URL = os.getenv('DLOCAL_API_URL', 'https://sandbox.dlocal.com') API_CONFIG = { 'payins_url': f'{DLOCAL_API_URL}/secure_payments', 'payouts_url': f'{DLOCAL_API_URL}/api_curl/cashout_api/request_cashout', 'cert_url': 'https://api-certs.dlocal.com', } ``` -------------------------------- ### GET /payments-methods Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/README.md Lists available payment methods for a specific country using V2 HMAC and mTLS. ```APIDOC ## GET /payments-methods ### Description List available methods. ### Method GET ### Endpoint /payments-methods?country=XX ### Parameters #### Query Parameters - **country** (string) - Required - The country code to filter payment methods. ### Authentication V2 HMAC + mTLS ``` -------------------------------- ### Run Payins and Payouts programs Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/api-reference-go.md Commands to execute the payins and payouts Go programs. ```bash go run payins.go ``` ```bash go run payouts.go ``` -------------------------------- ### Compile and Run Java Application Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/api-reference-java.md Commands to compile the source code and execute the application with the required classpath. ```bash javac -cp gson-2.10.1.jar src/main/java/com/example/PayinsRequest.java ``` ```bash java -cp .:gson-2.10.1.jar com.example.PayinsRequest ``` -------------------------------- ### Signature Calculation Logic Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/api-reference-payment-methods-javascript.md Logic for computing the HMAC signature for GET requests, which excludes the request body. ```javascript // No request body for GET requests concatenatedData = login + timestamp // Signature computed from login and timestamp only ``` -------------------------------- ### Load Configuration in Express Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/configuration.md Initialize configuration object using environment variables with fallback defaults. ```javascript require('dotenv').config(); const config = { dlocal: { login: process.env.DLOCAL_LOGIN || 'x', transKey: process.env.DLOCAL_TRANS_KEY || 'x', secretKey: process.env.DLOCAL_SECRET_KEY || 'x', apiUrl: process.env.DLOCAL_API_URL || 'https://sandbox.dlocal.com', certApiUrl: process.env.DLOCAL_CERT_API_URL || 'https://api-certs.dlocal.com', }, server: { port: process.env.PORT || 3000, nodeEnv: process.env.NODE_ENV || 'development', }, }; module.exports = config; ``` -------------------------------- ### Generate Unique Order ID Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/api-reference-csharp.md Generates a new GUID to serve as a unique identifier for the payment request. ```csharp string orderId = Guid.NewGuid().ToString(); ``` -------------------------------- ### Initialize dLocal instance Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/api-reference-smartfields-react.md Sets up the dLocal instance and configures the fields with specific fonts and locale settings. ```javascript const dlocalInstance = dlocal(smartFieldsConfig.api_key); setDlocalInstance(dlocalInstance); const smartfieldsInstance = dlocalInstance.fields({ fonts: [{ cssSrc: "https://rsms.me/inter/inter-ui.css", }], locale: "es", country: smartFieldsConfig.country, }); ``` -------------------------------- ### Payment Methods Response Format Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/api-reference-payment-methods-javascript.md Example JSON response structure returned by the API upon a successful request. ```json { "message": "Payment request successful", "response": [ { "id": "CARD", "name": "Credit Card", "countries": ["BR", "MX", "AR"], "enabled": true }, { "id": "BANK_TRANSFER", "name": "Bank Transfer", "countries": ["BR"], "enabled": true } ] } ``` -------------------------------- ### Main Function Declaration Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/api-reference-go.md The primary entry point for executing a payin request. ```go func main() ``` -------------------------------- ### Example webhook notification payload Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/api-reference-notifications-javascript.md Represents the structure of the JSON payload sent by dLocal when a payment status changes. ```javascript const notificationPayload = { id: 'PAY-123456789', status: 'COMPLETED', payment_method_id: 'CARD', order_id: '123e4567-e89b-12d3-a456-426614174000', created_date: '2024-01-15T10:30:45Z' }; ``` -------------------------------- ### Calculate Signature for Payment Methods Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/api-reference-payment-methods-javascript.md Use this signature calculation method for GET requests where no request body is included. ```javascript concatenatedData = `${login}${timestamp}`; // body is NOT included ``` -------------------------------- ### Define C# Configuration Class Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/configuration.md Create a class to map the JSON configuration settings. ```csharp using System; public class DLocalSettings { public string Login { get; set; } public string TransKey { get; set; } public string SecretKey { get; set; } public string ApiUrl { get; set; } public bool Sandbox { get; set; } public int Timeout { get; set; } = 30; } ``` -------------------------------- ### Script entry point Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/api-reference-python.md Standard Python entry point to execute the main function. ```python if __name__ == "__main__": main() ``` -------------------------------- ### Complete Payment Request Implementation in C# Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/api-reference-csharp.md Demonstrates the full flow of generating a request signature, configuring HTTP headers, and executing a POST request to the dLocal API. ```csharp using System; using System.Net.Http; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; class Program { static async Task Main() { string apiUrl = "https://sandbox.dlocal.com/secure_payments"; string timestamp = DateTimeOffset.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss.fffZ"); string login = "your-login"; string transKey = "your-trans-key"; string secretKey = "your-secret-key"; string orderId = Guid.NewGuid().ToString(); string requestPayload = $@" {{ ""amount"": 120.00, ""currency"": ""USD"", ""country"": ""BR"", ""payment_method_id"": ""CARD"", ""payment_method_flow"": ""DIRECT"", ""payer"": {{ ""name"": ""John Doe"", ""email"": ""john@example.com"", ""document"": ""12345678900"", ""user_reference"": ""user123"" }}, ""card"": {{ ""holder_name"": ""John Doe"", ""number"": ""4111111111111111"", ""cvv"": ""123"", ""expiration_month"": 12, ""expiration_year"": 2025 }}, ""order_id"": ""{orderId}"", ""notification_url"": ""http://merchant.com/notifications"" }}"; string signature = SignatureCalculator(login, timestamp, secretKey, requestPayload); using (var client = new HttpClient()) { client.DefaultRequestHeaders.Clear(); client.DefaultRequestHeaders.Add("X-Date", timestamp); client.DefaultRequestHeaders.Add("X-Login", login); client.DefaultRequestHeaders.Add("X-Trans-Key", transKey); client.DefaultRequestHeaders.TryAddWithoutValidation( "Authorization", $"V2-HMAC-SHA256, Signature: {signature}" ); var content = new StringContent( requestPayload, Encoding.UTF8, "application/json" ); var response = await client.PostAsync(apiUrl, content); if (response.IsSuccessStatusCode) { Console.WriteLine("Payment request successful!"); string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine($"Response: {responseBody}"); } else { Console.WriteLine($"Payment request failed. Status: {response.StatusCode}"); } } } static string SignatureCalculator(string x_Login, string x_Date, string secretKey, string body) { string concatenatedData = x_Login + x_Date + body; byte[] data = Encoding.UTF8.GetBytes(concatenatedData); byte[] keyBytes = Encoding.UTF8.GetBytes(secretKey); using (var hmacsha256 = new HMACSHA256(keyBytes)) { byte[] hashBytes = hmacsha256.ComputeHash(data); StringBuilder signatureBuilder = new StringBuilder(); foreach (byte b in hashBytes) { signatureBuilder.Append(b.ToString("x2")); } return signatureBuilder.ToString(); } } } ``` -------------------------------- ### Invoke Payment Methods API Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/api-reference-payment-methods-javascript.md Example usage of the local Express route to fetch payment methods for a specific country using Axios. ```javascript const axios = require('axios'); const request = { country: 'BR' }; const response = await axios.post( 'http://localhost:3000/payins-certificate-auth-get-payments', request ); console.log('Available payment methods:'); response.data.response.forEach(method => { console.log(`- ${method.name} (${method.id})`); }); ``` -------------------------------- ### Configure Java System Properties Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/configuration.md Pass credentials as command-line arguments when executing the Java application. ```bash java -Ddlocal.login=merchant_login \ -Ddlocal.trans_key=transaction_key \ -Ddlocal.secret_key=secret_key \ com.example.PayinsRequest ``` -------------------------------- ### HMAC-SHA256 Signature Implementation and Usage Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/api-reference-payouts-javascript.md Full implementation of the signature generation function using Node.js crypto and an example of its usage with a JSON payload. ```javascript const crypto = require('crypto'); function generateHmacSha256Signature(payload, secretKey) { const hmac = crypto.createHmac('sha256', secretKey); hmac.update(payload); return hmac.digest('hex'); } const payload = JSON.stringify({ amount: '100.00' }); const signature = generateHmacSha256Signature(payload, 'my-secret-key'); console.log(signature); // Output: hex string like 'a1b2c3d4e5f6...' ``` -------------------------------- ### GET /payment-methods Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/api-reference-payment-methods-javascript.md Retrieves a list of available payment methods for a specified country. This request requires mTLS and a signature calculated using the login and timestamp. ```APIDOC ## GET /payment-methods ### Description Retrieves the list of available payment methods for a given country. This endpoint requires mTLS and a signature generated from the login and timestamp. ### Method GET ### Endpoint /payment-methods ### Query Parameters - **country** (string) - Required - The country code (e.g., BR, MX, AR) for which to list payment methods. ### Response #### Success Response (200) - **id** (string) - Payment method identifier. - **name** (string) - Display name of the payment method. - **countries** (array) - List of countries where the method is available. - **enabled** (boolean) - Whether the method is currently enabled. - **icon_url** (string) - Optional: URL to the method icon. - **description** (string) - Optional: Method description. ``` -------------------------------- ### Run test suite Source: https://github.com/dlocal/starter-code-examples/blob/main/SmartFields Starter Projects/React/README.md Launches the test runner in interactive watch mode. ```bash npm test ``` -------------------------------- ### Prepare HTTP Request Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/api-reference-java.md Configures the HttpURLConnection with necessary headers and authentication credentials. ```java import java.net.HttpURLConnection; import java.net.URL; URL url = new URL(apiUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("X-Date", timestamp); connection.setRequestProperty("X-Login", login); connection.setRequestProperty("X-Trans-Key", transKey); connection.setRequestProperty("Authorization", "V2-HMAC-SHA256, Signature: " + signature); connection.setRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); ``` -------------------------------- ### Compile and Run Java Payins Request Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/README.md Commands to compile the Java source with the Gson dependency and execute the main class. ```bash cd "Signatures/Java Payins" javac -cp gson-2.10.1.jar src/main/java/com/example/PayinsRequest.java java -cp .:gson-2.10.1.jar com.example.PayinsRequest ``` -------------------------------- ### Configure HttpClient Headers in C# Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/api-reference-csharp.md Demonstrates clearing existing headers and adding new ones. Use TryAddWithoutValidation for Authorization headers to bypass standard validation rules. ```csharp client.DefaultRequestHeaders.Clear(); client.DefaultRequestHeaders.Add("Key", "Value"); client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", value); ``` -------------------------------- ### Execute a Secure Payment Request in Python Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/api-reference-python.md Demonstrates the full flow of creating a payment request, including timestamp generation, HMAC-SHA256 signature calculation, and header configuration. ```python from datetime import datetime from uuid import uuid4 import requests import json import hmac import hashlib api_url = "https://sandbox.dlocal.com/secure_payments" login = "your-login" trans_key = "your-trans-key" secret_key = "your-secret-key" timestamp = datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z" request_payload = { "amount": 120.00, "currency": "USD", "country": "BR", "payment_method_id": "CARD", "payment_method_flow": "DIRECT", "payer": { "name": "John Doe", "email": "john@example.com", "document": "12345678900", "user_reference": "user123" }, "card": { "holder_name": "John Doe", "number": "4111111111111111", "cvv": "123", "expiration_month": 12, "expiration_year": 2025 }, "order_id": str(uuid4()), "notification_url": "http://merchant.com/notifications" } body = json.dumps(request_payload) concatenated_data = f"{login}{timestamp}{body}" key_bytes = secret_key.encode("utf-8") hash_bytes = hmac.new(key_bytes, concatenated_data.encode("utf-8"), hashlib.sha256).hexdigest() headers = { "X-Date": timestamp, "X-Login": login, "X-Trans-Key": trans_key, "Authorization": f"V2-HMAC-SHA256, Signature: {hash_bytes}" } response = requests.post(api_url, json=request_payload, headers=headers) print(response.json()) ``` -------------------------------- ### Load C# Configuration Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/configuration.md Use the ConfigurationBuilder to load settings from the JSON file into the application. ```csharp using Microsoft.Extensions.Configuration; var configuration = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .Build(); var dLocalSection = configuration.GetSection("DLocal"); var settings = dLocalSection.Get(); ``` -------------------------------- ### Set File Permissions for Security Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/configuration.md Apply these permissions to ensure sensitive certificate and configuration files are not accessible by unauthorized users. ```bash # Certificate files chmod 600 ./misc/private-key.pem chmod 644 ./misc/server.crt.pem # Configuration files chmod 600 .env chmod 600 appsettings.json ``` -------------------------------- ### Define Requirements Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/configuration.md List of required Python packages for the project. ```text Django==5.0 python-dotenv==1.0.0 requests==2.31.0 ``` -------------------------------- ### Configure API Environment URL Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/configuration.md Use this pattern to dynamically switch between sandbox and production base URLs based on the current environment. ```javascript const apiUrl = process.env.NODE_ENV === 'production' ? 'https://api.dlocal.com' : 'https://sandbox.dlocal.com'; ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/configuration.md Store sensitive credentials and API URLs in a .env file or environment variables. ```bash DLOCAL_LOGIN=merchant_login_credential DLOCAL_TRANS_KEY=transaction_key_credential DLOCAL_SECRET_KEY=secret_key_for_hmac DLOCAL_API_URL=https://sandbox.dlocal.com DLOCAL_CERT_API_URL=https://api-certs.dlocal.com PORT=3000 ``` -------------------------------- ### Customize UI Based on Country-Specific Methods Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/api-reference-payment-methods-javascript.md Demonstrates how to retrieve payment methods to conditionally adjust the user interface for different regions. ```javascript const methods = await getPaymentMethods('BR'); // Brazilian users might see bank transfer options // Mexican users might see different options // Customize form based on available methods ``` -------------------------------- ### Configure Production Credentials Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/api-reference-python.md Retrieve sensitive credentials from environment variables instead of hardcoding them. ```python # Use environment variables or config files import os login = os.getenv('DLOCAL_LOGIN') trans_key = os.getenv('DLOCAL_TRANS_KEY') secret_key = os.getenv('DLOCAL_SECRET_KEY') api_url = os.getenv('DLOCAL_API_URL') ``` -------------------------------- ### loadFields(smartFieldsConfig, hideIcon, setDlocalInstance, setFields, setLoading, setEmpty, setComplete, setErrors, setHasBrand) Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/api-reference-smartfields-react.md Initializes the SmartFields instance and creates the necessary card input fields for payment processing. ```APIDOC ## loadFields ### Description Initializes the SmartFields instance and creates field objects for card input (PAN, CVV, Expiration). It handles the configuration, field creation, event listener registration, and mounting to DOM containers. ### Parameters - **smartFieldsConfig** (object) - Required - Configuration object containing api_key and country. - **hideIcon** (boolean) - Required - Flag to hide payment brand icons. - **setDlocalInstance** (function) - Required - Callback to store the dlocal instance. - **setFields** (function) - Required - Callback to store field object references. - **setLoading** (function) - Required - Callback to update loading state. - **setEmpty** (function) - Required - Callback to track empty field states. - **setComplete** (function) - Required - Callback to track field completion status. - **setErrors** (function) - Required - Callback to track field validation errors. - **setHasBrand** (function) - Required - Callback to track card brand detection. ### Usage Example ```javascript loadFields( { api_key: "your_api_key", country: "BR" }, false, setDlocalInstance, setFields, setLoading, setEmpty, setComplete, setErrors, setHasBrand ); ``` ``` -------------------------------- ### Configure SSL Certificate Options Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/api-reference-payment-methods-javascript.md SSL configuration object requiring local paths to the private key and client certificate files. ```javascript const sslOptions = { key: fs.readFileSync('./misc/private-key.pem'), cert: fs.readFileSync('./misc/server.crt.pem'), }; ``` -------------------------------- ### Configure HttpClient Headers Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/api-reference-csharp.md Sets required authentication headers including X-Date, X-Login, X-Trans-Key, and the Authorization signature. ```csharp using (var client = new HttpClient()) { client.DefaultRequestHeaders.Clear(); // Add authentication headers client.DefaultRequestHeaders.Add("X-Date", timestamp); client.DefaultRequestHeaders.Add("X-Login", login); client.DefaultRequestHeaders.Add("X-Trans-Key", transKey); client.DefaultRequestHeaders.TryAddWithoutValidation( "Authorization", $"V2-HMAC-SHA256, Signature: {signature}" ); } ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/dlocal/starter-code-examples/blob/main/_autodocs/README.md Set these variables in your environment to authenticate and connect to the dLocal API. ```bash DLOCAL_LOGIN=merchant_login_credential DLOCAL_TRANS_KEY=transaction_key_credential DLOCAL_SECRET_KEY=secret_key_for_hmac DLOCAL_API_URL=https://sandbox.dlocal.com NODE_ENV=development ```