### Install Django Source: https://github.com/dlocal/starter-code-examples/blob/main/SmartFields Starter Projects/Django/README.md This command installs the Django web framework using pip, a package installer for Python. ```bash pip install Django ``` -------------------------------- ### React SmartFields Starter Project Source: https://github.com/dlocal/starter-code-examples/blob/main/README.md A starter project for React applications to integrate dLocal SmartFields. It includes a step-by-step guide for an easy setup process. ```javascript // Placeholder for React SmartFields integration code. // This would typically involve creating React components to render SmartFields // and handling form submissions to interact with dLocal APIs. // Example: components/PaymentForm.js // import React, { useState } from 'react'; // function PaymentForm() { // const [paymentDetails, setPaymentDetails] = useState({}); // const handleSmartFieldsChange = (data) => { // setPaymentDetails(data); // }; // const handleSubmit = async (e) => { // e.preventDefault(); // // Send paymentDetails to your backend API for processing with dLocal // // const response = await fetch('/api/process-payment', { ... }); // }; // return ( //
// {/* Render dLocal SmartFields component here */} // {/* */} // //
// ); // } // export default PaymentForm; ``` -------------------------------- ### Start React App Development Server Source: https://github.com/dlocal/starter-code-examples/blob/main/SmartFields Starter Projects/React/README.md Runs the React application in development mode, allowing for live reloading and console error reporting. It opens the app at http://localhost:3000. ```bash npm start ``` -------------------------------- ### Build React App for Production Source: https://github.com/dlocal/starter-code-examples/blob/main/SmartFields Starter Projects/React/README.md Bundles the React application for production, optimizing it for performance and minifying the code. The output is placed in the 'build' folder and is ready for deployment. ```bash npm run build ``` -------------------------------- ### Run Next.js Development Server Source: https://github.com/dlocal/starter-code-examples/blob/main/SmartFields Starter Projects/NextJS/README.md Commands to start the Next.js development server using npm, yarn, or pnpm. This allows for local development and testing of the Next.js application. ```bash npm run dev ``` ```bash yarn dev ``` ```bash pnpm dev ``` -------------------------------- ### NextJS SmartFields Starter Project Source: https://github.com/dlocal/starter-code-examples/blob/main/README.md An example NextJS project demonstrating the integration of dLocal SmartFields. This starter project allows for quick setup and implementation. ```javascript // Placeholder for NextJS SmartFields integration code. // This would typically involve creating API routes, React components, // and fetching data to integrate with dLocal SmartFields. // Example: pages/api/process-payment.js // export default async function handler(req, res) { // if (req.method === 'POST') { // // Process data from SmartFields and make API calls to dLocal // // ... // res.status(200).json({ message: 'Payment processed' }); // } // } // Example: components/PaymentForm.js // import React, { useState } from 'react'; // function PaymentForm() { // const [formData, setFormData] = useState({}); // const handleSubmit = async (e) => { // e.preventDefault(); // // Send formData to your NextJS API route // // const response = await fetch('/api/process-payment', { ... }); // }; // return ( //
// {/* SmartFields elements will be rendered here */} // //
// ); // } // export default PaymentForm; ``` -------------------------------- ### Run Django Development Server Source: https://github.com/dlocal/starter-code-examples/blob/main/SmartFields Starter Projects/Django/README.md This command starts the Django development server, allowing you to test the SmartFields checkout application locally. ```bash python manage.py runserver ``` -------------------------------- ### Go Payouts and Payins Signature Generation Source: https://github.com/dlocal/starter-code-examples/blob/main/README.md Provides an example in Go for creating the HMACSHA256 signature and making a POST request to the dLocal API. This guide covers the necessary steps for handling both payouts and payins. ```go // Example Go code for generating HMACSHA256 signature and sending POST request to dLocal API // import ( // "crypto/hmac" // "crypto/sha256" // "encoding/hex" // "fmt" // "io/ioutil" // "net/http" // "strconv" // "time" // ) // func GenerateSignature(secret, message string) string { // hmac := hmac.New(sha256.New, []byte(secret)) // hmac.Write([]byte(message)) // return hex.EncodeToString(hmac.Sum(nil)) // } // func SendApiRequest(url, apiKey, secret, requestBody string) (string, error) { // timestamp := strconv.FormatInt(time.Now().Unix(), 10) // messageToSign := apiKey + timestamp + requestBody // signature := GenerateSignature(secret, messageToSign) // client := &http.Client{} // req, err := http.NewRequest("POST", url, bytes.NewBuffer([]byte(requestBody))) // if err != nil { // return "", err // } // req.Header.Set("X-DLocal-API-Key", apiKey) // req.Header.Set("X-DLocal-Timestamp", timestamp) // req.Header.Set("X-DLocal-Signature", signature) // req.Header.Set("Content-Type", "application/json") // resp, err := client.Do(req) // if err != nil { // return "", err // } // defer resp.Body.Close() // body, err := ioutil.ReadAll(resp.Body) // if err != nil { // return "", err // } // if resp.StatusCode != http.StatusOK { // return "", fmt.Errorf("API request failed with status code: %d, body: %s", resp.StatusCode, string(body)) // } // return string(body), nil // } ``` -------------------------------- ### Clone DLocal Starter Code Examples Repository Source: https://github.com/dlocal/starter-code-examples/blob/main/SmartFields Starter Projects/Django/README.md This command clones the DLocal Starter Code Examples repository from GitHub, which contains various payment integration examples. ```bash git clone https://github.com/tam-dlocal/dLocal-Starter-Code-Examples.git ``` -------------------------------- ### Eject Create React App Configuration Source: https://github.com/dlocal/starter-code-examples/blob/main/SmartFields Starter Projects/React/README.md This is a one-way operation that removes the single build dependency from the project, copying all configuration files (webpack, Babel, ESLint, etc.) into the project for full control. Use with caution as it cannot be undone. ```bash npm run eject ``` -------------------------------- ### Run React App Tests Source: https://github.com/dlocal/starter-code-examples/blob/main/SmartFields Starter Projects/React/README.md Launches the test runner in an interactive watch mode, facilitating continuous testing during development. Refer to the Create React App documentation for more details on running tests. ```bash npm test ``` -------------------------------- ### Javascript Payouts and Payins Signature Generation Source: https://github.com/dlocal/starter-code-examples/blob/main/README.md Offers guide and code samples in Javascript for creating the HMACSHA256 signature and making POST requests to the dLocal API. This is applicable for both payouts and payins. ```javascript // Example Javascript code for generating HMACSHA256 signature and sending POST request to dLocal API // const crypto = require('crypto'); // function generateSignature(secret, message) { // return crypto.createHmac('sha256', secret).update(message).digest('hex'); // } // async function sendApiRequest(url, apiKey, secret, requestBody) { // const timestamp = Math.floor(Date.now() / 1000).toString(); // const messageToSign = apiKey + timestamp + requestBody; // const signature = generateSignature(secret, messageToSign); // const response = await fetch(url, { // method: 'POST', // headers: { // 'Content-Type': 'application/json', // 'X-DLocal-API-Key': apiKey, // 'X-DLocal-Timestamp': timestamp, // 'X-DLocal-Signature': signature // }, // body: requestBody // }); // if (!response.ok) { // throw new Error(`API request failed with status ${response.status}`); // } // return await response.json(); // } ``` -------------------------------- ### Navigate to Django SmartFields Project Directory Source: https://github.com/dlocal/starter-code-examples/blob/main/SmartFields Starter Projects/Django/README.md This command changes the current directory to the Django SmartFields project within the cloned repository. ```bash cd "SmartFields Starter Projects/Django" ``` -------------------------------- ### Django SmartFields Starter Project Source: https://github.com/dlocal/starter-code-examples/blob/main/README.md A starter project in Django designed for integrating dLocal SmartFields into your web application. It provides a foundation for a smooth integration process. ```python # Placeholder for Django SmartFields integration code. # This would typically involve setting up a Django app, # defining models, views, and templates to interact with dLocal SmartFields. # Example: urls.py # from django.urls import path # from . import views # urlpatterns = [ # path('process-payment/', views.process_payment, name='process_payment'), # ] # Example: views.py # from django.shortcuts import render # import requests # import json # def process_payment(request): # if request.method == 'POST': # # Process data from SmartFields and make API calls to dLocal # # ... # pass # return render(request, 'payment_form.html') ``` -------------------------------- ### Next.js API Route Example Source: https://github.com/dlocal/starter-code-examples/blob/main/SmartFields Starter Projects/NextJS/README.md An example of an API route handler in Next.js. This file is located in the 'pages/api' directory and is mapped to a specific URL endpoint. ```javascript export default function handler(req, res) { res.status(200).json({ name: 'John Doe' }); } ``` -------------------------------- ### Python Payouts and Payins Signature Generation Source: https://github.com/dlocal/starter-code-examples/blob/main/README.md A Python implementation for generating the required HMACSHA256 signature and sending POST requests to the dLocal API. This covers both payout and payin functionalities. ```python # Example Python code for generating HMACSHA256 signature and sending POST request to dLocal API # import hmac # import hashlib # import requests # import time # def generate_signature(secret, message): # return hmac.new(secret.encode('utf-8'), message.encode('utf-8'), hashlib.sha256).hexdigest() # def send_api_request(url, api_key, secret, request_body): # timestamp = str(int(time.time())) # message_to_sign = api_key + timestamp + request_body # signature = generate_signature(secret, message_to_sign) # headers = { # 'X-DLocal-API-Key': api_key, # 'X-DLocal-Timestamp': timestamp, # 'X-DLocal-Signature': signature, # 'Content-Type': 'application/json' # } # response = requests.post(url, headers=headers, data=request_body) # response.raise_for_status() # Raise an exception for bad status codes # return response.json() ``` -------------------------------- ### Initialize DLocal SmartFields and Mount Fields Source: https://github.com/dlocal/starter-code-examples/blob/main/SmartFields Starter Projects/Django/smartapp/templates/index.html This snippet initializes the DLocal SDK with an API key and creates individual SmartField components for PAN (card number), CVV, and expiration date. It then mounts these fields to their respective HTML elements and sets up event listeners for when each field is ready. ```JavaScript function loader(show) { document.getElementById("loader-example-2").style.visibility = show ? "visible" : "hidden"; } const dlocalInstance = dlocal('YOUR_API_KEY'); const fields = dlocalInstance.fields({ locale: 'en', country: 'BR' }); const pan = fields.create('pan', { style: { base: { fontSize: "16px", fontFamily: "Quicksand, Open Sans, Segoe UI, sans-serif", lineHeight: '18px', color: "#666", '::placeholder': { color: "#c1c1c1" }, iconColor: "#c1c1c1" }, autofilled: { color: "#000000" } }, placeholder: "4111 1111 1111 1111" }); const ccv = fields.create('cvv', { style: { base: { fontSize: "16px", fontFamily: "Quicksand, Open Sans, Segoe UI, sans-serif", lineHeight: '18px', fontSmoothing: 'antialiased', color: "#666", '::placeholder': { color: "#c1c1c1" }, iconColor: "#c1c1c1" }, focus: { '::placeholder': { color: "#adbfd3" } } }, placeholder: "123" }); const expiration = fields.create('expiration', { style: { base: { fontSize: "16px", fontFamily: "Quicksand, Open Sans, Segoe UI, sans-serif", lineHeight: '18px', fontSmoothing: 'antialiased', color: "#666", '::placeholder': { color: "#c1c1c1" }, iconColor: "#c1c1c1" }, autofilled: { color: "#000000" } }, placeholder: "MM/YY" }); const cardHolderInput = document.getElementById('cardHolder'); pan.mount(document.getElementById('panField')); expiration.mount(document.getElementById('expirationField')); ccv.mount(document.getElementById('cvvField')); let isPanReady = false; pan.on('ready', function (event) { isPanReady = true; if (isPanReady && isExpirationReady && isCVVReady) { loader(false); } }); let isExpirationReady = false; expiration.on('ready', function (event) { isExpirationReady = true; if (isPanReady && isExpirationReady && isCVVReady) { loader(false); } }); let isCVVReady = false; ccv.on('ready', function (event) { isCVVReady = true; if (isPanReady && isExpirationReady && isCVVReady) { loader(false); } }); ``` -------------------------------- ### C# Payins and Payouts Signature Generation Source: https://github.com/dlocal/starter-code-examples/blob/main/README.md Demonstrates how to generate the HMACSHA256 signature required for dLocal API requests and send a POST request using C# for both payin and payout operations. This involves understanding the request payload and signature construction. ```csharp // Example C# code for generating HMACSHA256 signature and sending POST request to dLocal API // using System.Security.Cryptography; // using System.Text; // using System.Net.Http; public static class DLocalSignatureHelper { public static string GenerateSignature(string secret, string message) { var key = Encoding.UTF8.GetBytes(secret); using (var hmac = new HMACSHA256(key)) { var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(message)); return BitConverter.ToString(hash).Replace("-", "").ToLower(); } } public static async Task SendApiRequest(string url, string apiKey, string secret, string requestBody) { var timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString(); var messageToSign = apiKey + timestamp + requestBody; var signature = GenerateSignature(secret, messageToSign); using (var client = new HttpClient()) { var request = new HttpRequestMessage(HttpMethod.Post, url); request.Headers.Add("X-DLocal-API-Key", apiKey); request.Headers.Add("X-DLocal-Timestamp", timestamp); request.Headers.Add("X-DLocal-Signature", signature); request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json"); var response = await client.SendAsync(request); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsStringAsync(); } } } ``` -------------------------------- ### SmartFields Checkout CSS Styling Source: https://github.com/dlocal/starter-code-examples/blob/main/SmartFields Starter Projects/Django/smartapp/templates/index.html This CSS provides styling for the SmartFields checkout page. It defines styles for the body, header, footer, content area, headings, form elements (inputs, buttons), and specific styles for placeholders and field containers to ensure a visually appealing and user-friendly interface. ```CSS body { font-family: 'Quicksand' !important; margin: 0; padding: 0; box-sizing: border-box; background-color: #f8f8f8; } header, footer { background-color: #2196F3; color: white; text-align: center; padding: 1em; } #content { max-width: 600px; margin: 20px auto; padding: 20px; border: 1px solid #ccc; border-radius: 5px; background-color: #fff; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); margin-top: 85px !important; } h2 { color: #2196F3; } form { display: flex; flex-direction: column; gap: 10px; align-items: center; } label { font-size: 14px; color: #333; margin-top: 5px; } input, button { padding: 10px; font-size: 16px; width: 100%; box-sizing: border-box; border: 1px solid #ccc; border-radius: 5px; } input { margin-bottom: 10px; } button { background-color: #2196F3; color: white; cursor: pointer; transition: background-color 0.3s ease; } button:hover { background-color: #1565C0; } #cardHolder { border: 0; line-height: 18px; color: #666 } #cardHolder::placeholder { border: 0; line-height: 18px; color: #c1c1c1 } .field-container :first-child { display: inline-block; width: 253px; vertical-align: top; margin-right: 3.5px; height: 30px; margin-bottom: 20px; } ``` -------------------------------- ### Handle Form Submission and Create Token Source: https://github.com/dlocal/starter-code-examples/blob/main/SmartFields Starter Projects/Django/smartapp/templates/index.html This JavaScript code handles the form submission event. It prevents the default form submission, validates the cardholder name, and then uses the DLocal instance to create a payment token by passing the PAN, expiration, and CVV fields along with the cardholder's name. The resulting token is logged to the console. ```JavaScript document.getElementById('checkoutForm').addEventListener('submit', async function (event) { event.preventDefault(); if (!cardHolderInput.value) { alert('Nome inválido') } console.log(cardHolderInput.value); console.log(typeof cardHolderInput.value); const result = await dlocalInstance.createToken(pan, expiration, ccv, { name: `${cardHolderInput.value}` }) console.log(result); }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.