Token Credit Card API

Overview

Welcome to PagSeguro Direct API with Credit Card for non-PCI merchants reference guide.
This document contains the basic concepts and technical details to pay for transactions using our Direct API for the countries for which we have available. It also has practical examples of requests and pertinent notes on how our API works.

Concepts and Terms

List of key definitions and standards that developers may need to successfully integrate.

TermConcept
APIApplication Programming Interface (API) is a way to allow third parties to use your application's resources.
RESTRepresentational State Transfer (REST) ​​is a style of software architecture for API services.
HTTPSHypertext Transfer Protocol Secure (HTTPS) is the secure version of HTTP, which is the main protocol used to send data between a web browser and a website. HTTPS is encrypted to increase data transfer security.
cURLcURL is a computer software tool for transferring data using various network protocols.
JSONJavaScript Object Notation (JSON) is a lightweight data interchange format.
TLDTop-Level Domain is the last segment of your domain name, that element located after the last dot. Since it is at the end of the address, it is also known as the domain suffix.
SandboxSafe dummy domain beyond production, suitable for a smooth integration experience.
MerchantPerson or organization that provides work or supplies goods for a particular niche.
StoreStore or commercial establishment used in the integration.
CustomerPerson or Company that makes the payment, for work performed or goods received.

Considerations

Direct API uses REST architecture, and the protocol used is HTTPS.
PagSeguro's API uses the Basic Authentication. The API's requests and response bodies are in JSON.

On-boarding

The merchant who wants to transact with PagSeguro must contact our sales team through the website: international.pagseguro.com/talk-to-us.

Credentials

To carry out the authentication process, the Merchant needs the credentials (Merchant ID and Password) made available in its registration with PagSeguro, through the page: myaccount.international.pagseguro.com.

Environments

Test environment available to assist in the integration development and simulate transaction requests and status changes available on the platform. Attention: the environment only simulates the creation of a transaction.

Sandbox

All transactions generated in the sandbox environment can be manipulated manually by developers to simulate the possible situations that PagSeguro returns through the site: billing-partner.boacompra.com.

In the Sandbox Environment section we explain how to perform status changes and receive notifications on the sandbox environment.

🚧

Base URL for Sandbox

https://api.sandbox.international.pagseguro.com

Production

The environment is used to create transactions in real-time. All transactions generated in this environment will be processed by PagSeguro.

📘

Base URL for Production

https://api.international.pagseguro.com

Authentication

All requests made to the PagSeguro APIs must be authenticated. PagSeguro Direct’s API uses the Basic Authentication approach. That means the Merchant must send the HTTP requests with the Authorization header.

The Authorization header must contain the word Basic followed by a space and a base64-encoded string with merchant_id:secret_key.

For example:

Authorization: Basic MTIzNDozN2IzNmUxNy1lZGIyLTRkNjAtOWFmZC05MTA2MmJlYmY1ZTQ=

Because base64 is easily decoded, PagSeguro Direct’s API only accepts requests throughout HTTPS/SSL/TLS

Once the Merchant’s On-boarding is concluded, the Merchant’s Developers will have a credential pair (merchant_id and secret_key) to use in the requests. Anyone in possession of the credential pair will be able to create transactions with PagSeguro.

Be sure to keep both, merchant_id and secret_key, in a safe and private place. Do not share it in client-side applications or public repositories.

The code snippet below shows an Authorization header’s example:

<php
$key = '1234';
$secret = '37b36e17-edb2-4d60-9afd-91062bebf5e4';
$encoded = base64_encode(sprintf('%s:%s', $key, $secret));
$header = sprintf('Authorization: Basic %s', $encoded);

echo $header;

// Authorization: Basic MTIzNDozN2IzNmUxNy1lZGIyLTRkNjAtOWFmZC05MTA2MmJlYmY1ZTQ=
String key = "1234";
String secret = "37b36e17-edb2-4d60-9afd-91062bebf5e4";

String encoded = Base64.getEncoder().encodeToString((key + ":" + secret).getBytes());
String header = "Authorization: Basic " + encoded;

System.out.println(header);

//Authorization: Basic MTIzNDozN2IzNmUxNy1lZGIyLTRkNjAtOWFmZC05MTA2MmJlYmY1ZTQ=
require "base64"

key = '1234'
secret = '37b36e17-edb2-4d60-9afd-91062bebf5e4'

encoded = Base64.encode64(key + ':' + secret)
header = 'Authorization: Basic ' + encoded

puts header

// Authorization: Basic MTIzNDozN2IzNmUxNy1lZGIyLTRkNjAtOWFmZC05MTA2MmJlYmY1ZTQ=
import base64

key = "1234"
secret = "37b36e17-edb2-4d60-9afd-91062bebf5e4"
key_secret = key + ":" + secret

encoded = key_secret.encode("ascii")
header = "Authorization: Basic " + base64.b64encode(encoded).decode()

print(header)

// Authorization: Basic MTIzNDozN2IzNmUxNy1lZGIyLTRkNjAtOWFmZC05MTA2MmJlYmY1ZTQ=

Direct API

Sequence Flow

  1. Merchant → PagSeguro: The merchant loads the PagSeguro JS into the website's browse
  2. Customer → Merchant: The customer fills in the payment details and completes the purchase on the merchant's website, then the merchant calls the 'generateCardToken' method via the script and generates a secure token to transact the customer's card details.
  3. Merchant → PagSeguro: Merchant Server validates the customer data and submits the transaction data to PagSeguro
  4. PagSeguro → Merchant: PagSeguro processes the request and returns transaction data to the Merchant Server
  5. Merchant → Customer: Merchant Server returns the transaction data to Customer

Environments

Production

📘

Direct API URL for Production

https://api.international.pagseguro.com/v3/transactions
Method: POST

Sandbox

🚧

Direct API URL for Sandbox

https://api.sandbox.international.pagseguro.com/v3/transactions
Method: POST

Request

To create a Direct API request with PagSeguro, the following objects will be used: integration, order, charge and payer.

  • To perform authentication, use the default authentication method defined in Authentication Section
  • Use the Content-Type header with the value "application/json".

Integration

The “integration” object contains integration data referring to the Merchant Store.
The available parameters are:

ParameterDescriptionTypeValidationMandatory
integrationThe object that contains the integration data for the transaction.Object-Yes
integration.referenceTransaction reference code in the merchant's store.StringMin. 4, Max. 64 - Pattern: ^([A-Za-z0-9-_])+$Yes
integration.notification_urlURL (must bind ports 80 or 443) used to send transaction status changes notifications by HTTP.StringA valid URL, Max. 200Yes
integration.languageThe language that will be used when communicating with buyers. For example, it is the language of emails.StringSee Language ValidationYes

Language Validation

List of translations available for PagSeguro:

LanguageLocate
en_USEnglish
es_ESSpanish
pt_BRBrazilian Portuguese
pt_PTPortugal Portuguese
tr_TRTurkish

Order

The “order” object contains the value and list of products that the Customer purchased from the Merchant store.
The available parameters are:

ParameterDescriptionTypeValidationMandatory
orderThe object that contains the order data for the transaction.Object-Yes
order.currencyCurrency for charging the transaction (ISO 4217).StringSee Currency ValidationYes
order.items[]Set of items related to billing.ArrayMin. 1, Max. 100Yes
order.items[].quantityItem quantity.IntegerMin. 1Yes
order.items[].descriptionItem description.StringMax. 180 - See Item Description ValidationYes
order.items[].unit_pricePrice per unit.FloatMin. 0.01 - Zero to two decimal places accepted. See more Item Unit Price ValidationYes

Currency Validation

List of currencies available for PagSeguro:

ISO CodeCurrency
BRLBrazilian Real (Brazil)
CLPChilean Peso (Chile)
COPColombian Peso (Colombia)
MXNMexican Peso (Mexico)
PENNuevo Sol (Peru)

Item Description Validation

Rules for validating the item description:

  • Minimum 1 character;
  • The maximum length of 180 characters;
  • Accepted characters: A to Z, uppercase, lowercase letters, and/or numbers;

Item Unit Price Validation

Our API is designed to receive amounts starting from 0.01, but each country and each payment method has a minimum and maximum total amount accepted, so we recommend that the values are those indicated below:

CountryPayment MethodMinimum Total AmountMaximum Total AmountISO Code CurrencyAccepted Brands
BrazilAll credit card brands1.0040000.00BRLAmerican Express, Diners, MasterCard, Visa, Elo, Hipercard
ChileAll credit card brands0.011000000.00CLPAmerican Express, Diners, MasterCard, Visa
ColombiaAll credit card brands0.0138000000.00COPAmerican Express, Diners, MasterCard, Visa
MexicoAll credit card brands0.0174000.00MXNAmerican Express, Diners, MasterCard, Visa
PeruAll credit card brands0.0134000.00PENAmerican Express, Diners, MasterCard, Visa

Charge

The “charge” object contains the payment information to generate the transaction.
The available parameters are:

ParameterDescriptionTypeValidationMandatory
chargeThe object that contains the payment data for the transaction.Object-Yes
charge.countryCountry of origin of the transaction.StringSee Country ValidationYes
charge.typeRepresents the type of payment method.StringCREDIT_CARDYes
charge.credit_cardThe object contains credit card data specific to payment.Object-Yes
charge.credit_card.tokenCredit card token generated by PagSeguro's JSStringSee JS Credit Card Token GeneratorYes
charge.credit_card.holder_nameThe cardholder's name on the payer's credit cardStringMin. 2, Max. 26 - See Cardholder's Name ValidationYes

Country Validation

List of countries and their respective currencies accepted by PagSeguro:

ISOCountryCurrency Accepted
BRBrazilBRL
CLChileCLP
COColombiaCOP
MXMexicoMXN
PEPeruPEN

JS Credit Card Token Generator

PagSeguro provides a JavaScript library for you to securely collect your customer's credit card details without sensitive credit card data reaching your server. When the customer enters the details of the card on your site, the script collects the sensitive data and creates an encrypted version that you can securely transmit to PagSeguro.

This script is minified and the InternationalPagSeguro.CardToken object will be used in the integration and can be added before the tag to avoid loading problems on the current page.
After creating an instance of CardToken, you must call the generate() function to actually create the card token. The result of the function is a promise (more about Promises here)

It is very important to use this script from our CDN, to maintain the compatibility with PagSeguro Payment API.

<script src="https://stc.international.pagseguro.com/v3/international.pagseguro.min.js"></script>

Credit Card Object

The 'generateCardToken' method generates a security token with the credit card details entered in the merchant's website and stores the information on the PagSeguro servers in accordance with PCI-DSS compliance standards.

PropertyDescriptionTypeValidationMandatory
numberPayer's credit card number.StringOnly numbers. Min. 12, Max. 19Yes
cvcPayer's credit card card security code.StringOnly numbers. Min. 3, Max. 4Yes
expiration_monthPayer's credit card expiration month.StringAccepted values: 01, 02, 03, 04, 05, 06, 07, 08, 09, 10, 11, 12Yes
expiration_yearPayer's credit card expiration year.String4 DigitsYes
holder_nameThe cardholder's name on the payer's credit cardStringMin. 2, Max. 26 - See Cardholder's Name ValidationYes

Full Example

Here you will find a detailed and explained example of a HTML file implementing our javascript file.

<!DOCTYPE html>

<html>

<head>
    <meta charset="utf-8">

    <title>PagSeguro Direct API Test</title>

     <!--
         To include the PagSeguro JS in your payment page, you must insert a script tag with the JS file URL
         Script loaded with a dynamic parameter (?p=999999) value to invalidate the browser cache. 
     -->
    <script type="text/javascript" src="https://stc.international.pagseguro.com/v3/international.pagseguro.min.js?p=999999"></script>

    <!-- 
        You MUST instance the payment object ASAP after add the javascript on page,
        it will prevent loading time issues in the flow. 
    -->
    <script type="text/javascript">
        var cardToken = new InternationalPagSeguro.CardToken();
    </script>
</head>

<body>
    <a href="javascript:generateCardToken()" target="_self">Click here to Generate the Card Token</a>

    <script type="text/javascript">
        function generateCardToken() {
            // Example credit card data and format
            let card = {
                number: '5555666677778884',
                cvc: '123',
                expiration_month: '02',
                expiration_year: '2026',
                holder_name: 'Jonh Doe'
            };

            // Use the content returned in the Promise to fill the token field in the API request
            cardToken.generate(card).then(cardToken => {
                console.info(cardToken);
            }).catch(err => console.log(err));
        }
    </script>
</body>

</html>

Cardholder's Name Validation

Rules for validating the cardholder’s name:

  • Minimum length of 2 characters;
  • The maximum length of 26 characters;
  • Accepted characters: A to Z, uppercase and/or lowercase letters;
  • Special characters accepted: ,.'-
  • Space characters are not accepted at the beginning and end of the string.
  • Each word must be separated by ONE space;

Payer

The “payer” object contains information about the Customer who purchased the Merchant.
The available parameters are:

ParameterDescriptionTypeValidationMandatory
payerThe object that contains the payer data for the transaction.Object-Yes
payer.emailPayer E-mail used in store.StringMax. 60 - See E-mail ValidationYes
payer.ipPayer IP used in store.StringAccepts IPv4 or IPv6Yes
payer.personThe object that contains the person's data for the transaction.Object-Yes
payer.person.namePerson's name.StringMin. 4, Max. 50 - See Name ValidationYes
payer.person.birth_datePerson's birth date.StringFormat (YYYY-mm-dd)No
payer.person.documentThe object that contains the payer identification document data for the transaction.Object- See Document ValidationYes
payer.person.document.typeDocument type.StringMin. 2, Max. 4Yes
payer.person.document.numberDocument number.StringMin. 7, Max. 18Yes
payer.person.phoneThe object that contains the phone data for the transaction.Object-Yes
payer.person.phone.country_codePhone country code.StringMin. 1, Max. 3Yes
payer.person.phone.numberPhone number.StringMin. 1, Max. 11Yes

E-mail Validation

Rules for validating the email:

  • The maximum length of 60 characters;
  • Must include TLD (ex: test@localhost is not accepted, but [email protected] is accepted);
  • Must include @ between the name and the domain.

Name Validation

Rules for validating the payer’s name:

  • The maximum length of 50 characters;
  • Minimum two words;
  • Each word must be separated by ONE space;
  • The first word must have at least 2 characters;
  • The middle and last name words must be between 1 and 40 characters;
  • Middle and last words can have only one character;
  • Accepted characters: A to Z, uppercase and/or lowercase letters;
  • Special characters accepted: àáâäãåąčćęèéêëėįìíîïłńòóôöõøùúûüųūÿýżźñçčšžÀÁÂÄÃÅĄĆČĖĘÈÉÊËÌÍÎÏĮŁŃÒÓÔÖÕØÙÚÛÜŲŪŸÝŻŹÑßÇŒÆČŠŽ∂ð/,.'&-
  • Space characters are not accepted at the beginning and end of the string.

Document Validation

Rules for validating the person’s document:

  • Accepted characters: numbers or A to Z, uppercase letters;
  • Special characters are not accepted;
  • Punctuation must be disregarded;

List of documents and numbers format accepted for PagSeguro:

CountryTypeDocument NameValidationPatternExamples
BrazilCPFCadastro de Pessoas Físicas11 Characters - Format: 999.999.999-99^[0-9]{11}$00011122233, 01234567891
ChileRUTRegistro Único Tributario8 - 9 Characters - Format: 9.999.999-9 or 99.999.999.K^[0-9]{1,2}([0-9]{3}){2}[0-9kK]$220604497, 12531902, 2012346K, 12345678k
ColômbiaCCCédula de Ciudadanía10 Characters^[0-9]{10}$1234567890, 1112223334
ColômbiaCECédula de Extranjería7 Characters^[A-Za-z]{1}[0-9]{6}$a000111, Z778899
ColômbiaTITarjeta de Identidad11 Characters^[0-9]{11}$20503644968, 01234567891
ColômbiaNITNúmero de Identificación Tributaria8 - 10 Characters - Format: 99.999.999, 999.999.999 or 999.999.999-9^[0-9]{8,10}$11111111, 123456789, 2222222222
MéxicoCURPClave Única de Registro de Población18 Characters^[A-Za-z]{4}[0-9]{6}[HMhm][A-Za-z]{5}[0-9]{2}$ABCD112233MGHIJL90, dcba001122habcde12
MéxicoRFCRegistro Federal de Contribuyentes12 - 13 Characters - Format: LLLLNNNNNNAAA^[A-ZÑ&a-zñ]{3,4}[0-9]{6}[A-Za-z0-9]{3}$GAAA750430HZ0, AGB860519G31, zbc123456pl2
PeruDNIDocumento Nacional de Identidad9 Characters - Format: 99.999.999-K^[0-9]{8}[A-Za-z0-9]{1}$123456789, 12345678A, 87654321b
PeruCECédula de Extranjería8 - 10 Characters^[A-Za-z]{2}[0-9]{6,10}$AZ000111, az000111, BB4445556, bb4445556, bc11122233, BC11122233
PeruRUCRegistro Único de Contribuyente11 Characters - Format: 99999999999^[0-9]{11}$20503644968, 01234567891

Examples

To create a credit card transaction, make a POST request as the example:

Status 201 Created

{
    "integration": {
        "reference": "REF-XXX-1234567890",
        "notification_url": "https://www.merchantwebsite.com/notify?type=transaction",
        "language": "pt_BR"
    },
    "order": {
        "currency": "BRL",
        "items": [
            {
                "quantity": 1,
                "description": "Product description",
                "unit_price": 101.10
            }
        ]
    },
    "charge": {
        "country": "BR",
        "type": "CREDIT_CARD",
        "credit_card" :{
            "token":"eyJkbmEiOiI2NzY3YzAxNDEzNGM0NTc4ODg0ZjU2MjdmYTI0ZGVhZiIsImlwIjoiMjAwLjIyMS4xMzAuNDkiLCJkZiI6ImNmYWI3MDcxMDJlZDQ4MjU4MzJhNmY2MDBhNWZjZjc2In0=",
            "holder_name": "jonh doe"
        }
    },
    "payer": {
        "email": "[email protected]",
        "ip": "192.0.2.146",
        "person": {
            "name": "Mr. Payer Full Name",
            "birth_date": "1970-01-01",
            "document": {
                "type": "CPF",
                "number": "98765432101"
            },            
            "phone": {
                "country_code": "55",
                "number": "44900000000"
            }
        }
    }
}

Response

ParameterDescriptionType
codeTransaction UUID codeString
referenceTransaction reference code in the merchant's store.String
statusStatus of the created transaction. (PENDING)String
amountThe amount charged for the transaction.Float
currencyThe currency used for billing.String
countryThe country of origin informed in the transaction.String
created_atTransaction creation date in Coordinated Universal Time (UTC)UTC DateTime

Example of a response

{
    "code": "25a58ef1-3755-476b-b2f6-e445b170a849",
    "reference": "REF-XXX-1234567890",
    "status": "PENDING",
    "amount": 101.1,
    "currency": "BRL",
    "country": "BR",
    "created_at": "2021-04-12T12:43:13Z"
}

Notification

Workflow

  1. PagSeguroMerchant: PagSeguro notifies Merchant that a transaction status has changed
  2. MerchantPagSeguro: With the transaction code received by the notification, the Merchant requests transaction information from PagSeguro
  3. PagSeguroMerchant: PagSeguro responds back with transaction information

To verify the current transaction status, the Merchant needs to use Search API to query the transaction. If PagSeguro responds to the transaction with the status COMPLETE, the Merchant needs to deliver the purchase to the End User.

Notification Request

After changing the payment status, PagSeguro sends the notification to the Merchant through the URL provided in the integration.notification_url parameter.

POST https://www.merchantwebsite.com/notify?type=transaction HTTP/1.1
Content-Type: application/json
{
    "test_mode": false,
    "notification_type": "transaction",
    "transaction_code": "9DB1FAFB-C0E6-4184-822C-8F18B3D70321"
}

Firewall and allowlist settings

❗️

If you use a firewall or allowlists, please note that to receive our notifications, you MUST allowlist the following IPs:

  • 54.233.188.209
  • 18.228.56.27

Renotification

📘

Renotification details:

If PagSeguro does not receive a satisfactory response from the Merchant (200 OK) in the first request, the notification enters a retry flow over 5 days, and the intervals of retry increase exponentially over the days. If the Merchant cannot respond within this range of days with 200 OK status code, then the notification is expired.