# Pagsmile JavaScript

## Pagsmile Payment Gateway Integration Guide

This guide provides step-by-step instructions for integrating Pagsmile into your website for seamless payment processing. Pagsmile offers robust features and security measures to ensure smooth transactions for your customers.

### Prerequisites

1. **Pagsmile Account**: Ensure you have signed up for a Pagsmile account. You will need your `app_id` and `public_key` provided by Pagsmile.
2. **Environment**: Access to your website's HTML and JavaScript files for integration.

### Step 1: HTML Form Structure

Below is the basic HTML code to create the credit card input fields.

```html
  <div>    
    <ul>
      <li>
        <label>Card holder name:</label>
        <input type="text" id="card-name" placeholder="Card holder" autocomplete="off" />
      </li>
      <li>
        <label>Credit card number:</label>
        <input type="text" id="card-number" placeholder="XXXX XXXX XXXX XXXX" />
      </li>
      <li>
        <label>Expiration year:</label>
        <input id="exp-year" type="text" placeholder="2028" autocomplete="off" />
      </li>
      <li>
        <label>Expiration month:</label>
        <input id="exp-month" type="text" placeholder="12" autocomplete="off"/>
      </li>
      <li>
        <label>Security code:</label>
        <input id="card-cvv" type="text" placeholder="123" autocomplete="off" />
      </li>
   </ul>
   <input type="button" id="submit-pay" value="Pay!" />
 </div>   
```

### Step 2: Include Pagsmile Script

Add the Pagsmile JavaScript library to the `<head>` section of your HTML file. This script is necessary to initialize and interact with the Pagsmile API.

```HTML
<head>
  <!-- Other head content -->
  <script src="https://res.pagsmile.com/lib/js/pagsmile.min.js"></script>
</head>
```

### Step 3: Initialize Pagsmile

After the page loads and the Pagsmile script has loaded, initialize Pagsmile with your credentials (`app_id` and `public_key`) other mandatory parameters. This step prepares Pagsmile for handling payment transactions securely.

### Step 4: Handle Payment Form Submission

Use createOrder method of returned clientinstance and initialize payment upon user submission. Check [Brazil](/payin/submit-a-payin/brazil/creditcard.md), [Mexico](/payin/submit-a-payin/mexico/creditcard.md), [Peru](/payin/submit-a-payin/peru/creditcard.md), [Ecuador](/payin/submit-a-payin/ecuador/creditcard.md), [Egypt](/payin/submit-a-payin/egypt/creditcard.md), [Saudi Arabia](/payin/submit-a-payin/saudi-arabia/creditcard.md), [Kuwait](/payin/submit-a-payin/kuwait/creditcard.md), [Qatar](/payin/submit-a-payin/qatar/creditcard.md), [Nigeria](/payin/submit-a-payin/nigeria/debitcard.md), [Europe](/payin/submit-a-payin/europe/creditcard.md), or [North America](/payin/submit-a-payin/north-america/creditcard.md). Once you get <mark style="background-color:yellow;">status: "success"</mark> query transaction status with help of related backend endpoints.

#### *setPublishableKey* Optional Parameters

**pre\_auth**: `boolean` (optional) Whether pre-authorization is enabled. When set to `true`, pre-authorization is enabled for payments. Defaults to `false`.**form\_id**: `string` (conditional, required for Mexico) The ID of the form element to be used for payment processing. This parameter is required for transactions in Mexico.

**form\_id**: `string` (conditional, required for Mexico) The ID of the form element to be used for payment processing. This parameter is required for transactions in Mexico.

#### *createOrder* Optional Parameters

**installments**: `object` (optional) Parameter should be provided if there is installment information is returned by [Installment Detail Query](https://docs.pagsmile.com/payin/tools/installment-detail-query) endpoint.

**phone:** `string` (optional) Mobile phone number

**email:** `string` (optional) Personal email address

**postal\_code:** `string` (optional) Postal code of residential address

**payer\_id:** `string` (optional) Personal identification number (CPF for Brazil)

**address**: `Object` (optional) An optional address object that specifies the country associated with the payment.

* **country\_code**: `string` (optional) A 3-letter ISO country code that specifies the country associated with the payment (e.g., `"SWE"` for Sweden). If not provided, this field will be omitted.

```Plain
createOrder({ 
   installments: { stage: 3 },  
   address: { country_code: "SWE"},
   phone: "5575991435892",
   email: "test@gmail.com",
   postal_code: "12345678",
   payer_id: "12345678900", 
})
```

```HTML
<script>
  document.addEventListener('DOMContentLoaded', function() {
    Pagsmile.setPublishableKey({
      app_id: "1649*********8673",
      public_key: "Pagsmile_pk_86fc***************************************************",
      env: "sandbox", // Change to "prod" in live environment
      region_code: "EUP", //BRA for Brazil, EUP for Europe, USA for Noth America
      prepay_id: "cjExNDB5dUZhK1lkLzgzMjhSUkpFdk13YVloaEZ5T09OVG5WdEcxdmNIaz0=-06168a6c",
      fields: {
         card_name: {
             id_selector: "card-name",
          },
          card_number: {
            id_selector: "card-number",
          },
          expiration_month: {
            id_selector: "exp-month",
          },
          expiration_year: {
            id_selector: "exp-year",
          },
          cvv: {
            id_selector: "card-cvv",
          },
      },
    }).then((clientInstance) => {
          // successfully initiated
          document.getElementById("submit-pay").addEventListener("click", function (e) {
            clientInstance
              .createOrder()
              .then((res) => {
                console.log("res: ", res); 
                // {
                //   status: "success",
                //   query: true,       // query transaction status through API endpoint /trade/query
                // }
              })
              .catch((err) => {
                console.log("Error: ", err);
              });
          });
        })   
    .catch((err) => {
      console.log("Initializing Pagsmile Error: ", err);
    });
  });
</script>
```

### Step 4: Testing and Deployment

1. **Sandbox Mode**: During development and testing, use `env: "sandbox"`. Verify that payments process correctly and error handling works as expected.
2. **Production Mode**: Before deploying to production, change the `env` setting to `"prod"`.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.pagsmile.com/payin/tools/pagsmile-javascript.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
