---
updatedAt: 2025-06-10T21:36:47.000Z
agentTools:
  projectIndex: https://www.payretailers.dev/llms.txt
---

# Create Transaction

```python Python
import requests
import json
import base64

# Your PayRetailers API credentials
subscription_key = 'your_subscription_key'
username = 'your_username'
password = 'your_password'

# Encode credentials in Base64
credentials = f"{username}:{password}"
encoded_credentials = base64.b64encode(credentials.encode()).decode()

# Transaction data
transaction_data = {
    "paymentMethodTagName": "CREDIT_CARD",
    "amount": "10000",  # Amount in the smallest currency unit (e.g., for $100.00, use 10000)
    "currency": "MXN",  # Currency code
    "description": "Payment description",
    "trackingId": "UIDFromYourEnd",
    "notificationUrl": "https://your-notification-url.com",
    "returnUrl": "https://your-return-url.com",
    "customer": {
        "firstName": "John",
        "lastName": "Doe",
        "email": "john.doe@example.com",
        "personalID": "TEST123456ABCDEF12",
        "country": "MX",
        "city": "Ciudad de México",
        "zip": "06010",
        "address": "123 Main St"
    }
}

# API endpoint
url = "https://api-sandbox.payretailers.com/payments/v2/transactions"

# Headers
headers = {
    "Ocp-Apim-Subscription-Key": subscription_key,
    "Authorization": f"Basic {encoded_credentials}",
    "Content-Type": "application/json"
}

# Make the request
response = requests.post(url, headers=headers, data=json.dumps(transaction_data))

# Check the response
if response.status_code == 200:
    print("Transaction created successfully!")
    print("Response:", response.json())
else:
    print("Failed to create transaction.")
    print("Status Code:", response.status_code)
    print("Response:", response.json())
```

```java Java
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class PayRetailersTransaction {

    public static void main(String[] args) {
        // Your PayRetailers API credentials
        String subscriptionKey = "your_subscription_key";
        String username = "your_username";
        String password = "your_password";

        // Encode credentials in Base64
        String credentials = username + ":" + password;
        String encodedCredentials = Base64.getEncoder().encodeToString(credentials.getBytes(StandardCharsets.UTF_8));

        // Transaction data
        String jsonTransactionData = "{"
                + "\"paymentMethodTagName\": \"CREDIT_CARD\","
                + "\"amount\": \"10000\","
                + "\"currency\": \"MXN\","
                + "\"description\": \"Payment description\","
                + "\"trackingId\": \"UIDFromYourEnd\","
                + "\"notificationUrl\": \"https://your-notification-url.com\","
                + "\"returnUrl\": \"https://your-return-url.com\","
                + "\"customer\": {"
                + "\"firstName\": \"John\","
                + "\"lastName\": \"Doe\","
                + "\"email\": \"john.doe@example.com\","
                + "\"personalID\": \"TEST123456ABCDEF12\","
                + "\"country\": \"MX\","
                + "\"city\": \"Ciudad de México\","
                + "\"zip\": \"06010\","
                + "\"address\": \"123 Main St\""
                + "}"
                + "}";

        // API endpoint
        String url = "https://api-sandbox.payretailers.com/payments/v2/transactions";

        // Create HTTP client and POST request
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("Ocp-Apim-Subscription-Key", subscriptionKey);
            httpPost.setHeader("Authorization", "Basic " + encodedCredentials);
            httpPost.setHeader("Content-Type", "application/json");
            httpPost.setEntity(new StringEntity(jsonTransactionData));

            // Execute the request
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                // Check the response
                String responseBody = EntityUtils.toString(response.getEntity());
                if (response.getStatusLine().getStatusCode() == 200) {
                    System.out.println("Transaction created successfully!");
                    System.out.println("Response: " + responseBody);
                } else {
                    System.out.println("Failed to create transaction.");
                    System.out.println("Status Code: " + response.getStatusLine().getStatusCode());
                    System.out.println("Response: " + responseBody);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
```

```csharp C#
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json; // Make sure to install Newtonsoft.Json via NuGet

class Program
{
    static async Task Main(string[] args)
    {
        // Replace with your actual credentials
        string username = "your_username";
        string password = "your_password";
        string subscriptionKey = "your_subscription_key";

        // Encode credentials in Base64
        string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{username}:{password}"));

        // Set the API endpoint
        string url = "https://api-sandbox.payretailers.com/payments/v2/transactions";

        using (HttpClient client = new HttpClient())
        {
            // Set the headers
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);
            client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // Set Accept header

            // Create the transaction payload
            var payload = new
            {
                paymentMethodTagName = "CREDIT_CARD", // Example payment method
                amount = "10000", // Amount in cents (e.g., 100.00 would be 10000)
                currency = "MXN", // Currency code
                description = "Payment description",
                trackingId = "UIDFromYourEnd", // Example tracking ID
                language = "ES",
                notificationUrl = "https://payment-form.payretailers.com/notification",
                returnUrl = "https://payment-form.payretailers.com/return",
                customer = new
                {
                    firstName = "John",
                    lastName = "Doe",
                    email = "test@payretailers.com",
                    personalId = "TEST123456ABCDEF12",
                    country = "MX",
                    city = "Ciudad de México",
                    zip = "06010",
                    address = "República de Perú 177",
                    phone = "5299999999999"
                }
            };

            // Serialize payload to JSON
            string jsonPayload = JsonConvert.SerializeObject(payload);

            // Make the POST request to create a transaction
            HttpResponseMessage response = await client.PostAsync(url, new StringContent(jsonPayload, Encoding.UTF8, "application/json"));

            // Check if the request was successful
            if (response.IsSuccessStatusCode)
            {
                string jsonResponse = await response.Content.ReadAsStringAsync();
                Console.WriteLine("Transaction created successfully!");
              	Console.WriteLine("Response: " + jsonResponse);
            }
            else
            {
                Console.WriteLine("Error: " + response.StatusCode + " - " + await response.Content.ReadAsStringAsync());
            }
        }
    }
}
```

```python cURL
# Replace with your actual credentials
username="your_username"
password="your_password"
subscription_key="your_subscription_key"

# Encode credentials in Base64
encoded_credentials=$(echo -n "$username:$password" | base64)

# Create the JSON payload for the transaction
payload=$(cat <<EOF
{
    "paymentMethodTagName": "CREDIT_CARD",  # Example payment method
    "amount": "10000",                      # Amount in cents (e.g., 100.00 would be 10000)
    "currency": "MXN",                      # Currency code
    "description": "Payment description",
    "trackingId": "UIDFromYourEnd",        # Example tracking ID
    "language": "ES",
    "notificationUrl": "https://payment-form.payretailers.com/notification",
    "returnUrl": "https://payment-form.payretailers.com/return",
    "customer": {
        "firstName": "John",
        "lastName": "Doe",
        "email": "test@payretailers.com",
        "personalId": "TEST123456ABCDEF12",
        "country": "MX",
        "city": "Ciudad de México",
        "zip": "06010",
        "address": "República de Perú 177",
        "phone": "5299999999999"
    }
}
EOF
)

# Set the API endpoint
url="https://api-sandbox.payretailers.com/payments/v2/transactions"
# Make the POST request to create the transaction
curl -X POST "$url" \
-H "Authorization: Basic $encoded_credentials" \
-H "Ocp-Apim-Subscription-Key: $subscription_key" \
-H "Content-Type: application/json" \
-d "$payload"
```

```json Response Example
Transaction created successfully!
Response:
{
  "uid": "105433d8-74584-40b1-8f0e-3d543bbc0648",
  "type": "payment",
  "status": "PENDING",
  "message": null,
  "trackingId": "10010000A100028",
  "amount": 1768,
  "currency": "USD",
  "description": "Payment Test",
  "createdAt": "2023-03-13T12:16:17.6633918Z",
  "updatedAt": "2023-03-13T12:16:17.6633918Z",
  "pspTransactionId": "840480",
  "isValidPaymentMethod": null,
  "customer": {
    "firstName": "John",
    "lastName": "Doe",
    "middleName": "",
    "country": "BR",
    "city": "Sao Paulo",
    "zip": "",
    "address": "R. Sao Joaquim, 596",
    "phone": "5511999999999",
    "deviceId": "",
    "ip": "81.47.160.151",
    "personalId": "00113562600",
    "uniqueCustomerIdentifier": null,
    "accountCreationDate": null,
    "accountCreationCountry": null,
    "email": "test@payretailers.com"
  },
  "form": {
    "action": "https://api.gateway.payretailers.com/v2/public/transactions/gateway/105433d8-74584-40b1-8f0e-3d543bbc0648",
    "method": "GET"
  },
  "paymentMethod": {
    "id": "20421d39-5236-5421-9d0a-a9453279c98f",
    "name": "TEST",
    "type": "Online"
  },
  "billing": {
    "currency": "BRL",
    "amount": 10000
  },
  "conversionInfo": null
}
```

# Import necessary libraries

<!-- python@1-3 -->
<!-- java@1-9 -->
<!-- csharp@1-6 -->

Creating a new transaction requires handling requests and json objects. Base64 is necessary to hash the credentials

# Handle authentication

<!-- python@6-12 -->
<!-- java@11-21 -->
<!-- csharp@8-18 -->
<!-- python@2-7 -->

Insert your subscription key as well as your shop id and secret. Hash the credentials using Base64

# Add the body of the request

<!-- python@15-33 -->
<!-- java@24-42 -->
<!-- csharp@31-53 -->
<!-- python@10-33 -->

Create the body with the necessary data described in our API reference.

# Add the URL and headers

<!-- python@36-43 -->
<!-- java@45-53 -->
<!-- csharp@21-28 -->
<!-- python@36-42 -->

Add your endpoint URL and the headers including the subscription key and hashed credentials

# Submit the request

<!-- python@46-55 -->
<!-- java@47-72 -->
<!-- csharp@59-73 -->

Now submit the request and handle the response, including the exceptions in case of an error.