# Authenticate your session

Generate a session token for Hosted Fields by sending a POST request to the Processing Terminals hosted-fields-sessions endpoint using a Bearer token.

An AI skill is available for this guide, get it on the [Skills Marketplace (GitHub)](https://github.com/payroc/skills).

To authenticate your access to the Payroc gateway, include a

session token

every time you run the Hosted Fields script on a webpage.

<a id="before-you-begin"></a>
## Before you begin

- Make sure you have your API key for both the test environment and the production environment.
- Make sure that your integration can handle errors. If a request is unsuccessful, we return an error that follows the [RFC 7807 format](https://datatracker.ietf.org/doc/html/rfc7807). For more information about errors, go to [Errors](/api/errors).

<a id="integration-steps"></a>
## Integration steps

**Step 1.**	Generate a Bearer token.  
**Step 2.**	Generate a session token from the Bearer token.

<a id="step-1-generate-a-bearer-token"></a>
## Step 1. Generate a Bearer token

[Authenticate your requests](/api/authentication) to generate a Bearer token.

<a id="step-2-generate-a-session-token-from-the-bearer-token"></a>
## Step 2. Generate a session token from the Bearer token

You must use our Hosted Fields Sessions endpoint to generate a new session token each time you initialize Hosted Fields. A session token expires after 10 minutes.

When you generate a session token, you need to specify the version of the Hosted Fields JavaScript library that you are using. Include the version number in the libVersion parameter in the body of your request.

| Environment | Version |
| --- | --- |
| Test | 1.7.0.261457 |
| Production | 1.7.0.261471 |

<a id="request"></a>
### Request

To generate a session token, send a POST request to our Processing Terminals endpoint.

| Environment | URL |
| --- | --- |
| Test | [https://api.uat.payroc.com/v1/processing-terminals/\{processingTerminalId\}/hosted-fields-sessions](https://api.uat.payroc.com/v1/processing-terminals/%7BprocessingTerminalId%7D/hosted-fields-sessions) |
| Production | [https://api.payroc.com/v1/processing-terminals/\{processingTerminalId\}/hosted-fields-sessions](https://api.payroc.com/v1/processing-terminals/%7BprocessingTerminalId%7D/hosted-fields-sessions) |

Include the following headers in your request:

- **Content-Type:** Include `application/json` as the value for this parameter.
- **Authorization:** Include your Bearer token in this parameter.
- **Idempotency-Key:** Include a UUID v4 to make the request idempotent.

To create the body of your request, use the following parameters:

<a id="schema-requestbody"></a>
### Schema (`request.body`)

[Request body schema for `POST /processing-terminals/{processingTerminalId}/hosted-fields-sessions`](/api/create-session)

<a id="example-request"></a>
### Example request

<a id="request-1"></a>
### Request

POST [https://api.payroc.com/v1/processing-terminals/\{processingTerminalId\}/hosted-fields-sessions](https://api.payroc.com/v1/processing-terminals/%7BprocessingTerminalId%7D/hosted-fields-sessions)

**`Create session`**

```curl
curl -X POST https://api.payroc.com/v1/processing-terminals/1234001/hosted-fields-sessions \
     -H "Idempotency-Key: 8e03978e-40d5-43e8-bc93-6894a57f9324" \
     -H "Authorization: Bearer <token>" \
     -H "Content-Type: application/json" \
     -d '{
  "libVersion": "1.1.0.123456",
  "scenario": "payment"
}'
```

**`Create session`**

```python
import requests

url = "https://api.payroc.com/v1/processing-terminals/1234001/hosted-fields-sessions"

payload = {
    "libVersion": "1.1.0.123456",
    "scenario": "payment"
}
headers = {
    "Idempotency-Key": "8e03978e-40d5-43e8-bc93-6894a57f9324",
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
```

**`Create session`**

```javascript
const url = 'https://api.payroc.com/v1/processing-terminals/1234001/hosted-fields-sessions';
const options = {
  method: 'POST',
  headers: {
    'Idempotency-Key': '8e03978e-40d5-43e8-bc93-6894a57f9324',
    Authorization: 'Bearer <token>',
    'Content-Type': 'application/json'
  },
  body: '{"libVersion":"1.1.0.123456","scenario":"payment"}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

**`Create session`**

```go
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://api.payroc.com/v1/processing-terminals/1234001/hosted-fields-sessions"

	payload := strings.NewReader("{\n  \"libVersion\": \"1.1.0.123456\",\n  \"scenario\": \"payment\"\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Idempotency-Key", "8e03978e-40d5-43e8-bc93-6894a57f9324")
	req.Header.Add("Authorization", "Bearer <token>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

**`Create session`**

```ruby
require 'uri'
require 'net/http'

url = URI("https://api.payroc.com/v1/processing-terminals/1234001/hosted-fields-sessions")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["Idempotency-Key"] = '8e03978e-40d5-43e8-bc93-6894a57f9324'
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"libVersion\": \"1.1.0.123456\",\n  \"scenario\": \"payment\"\n}"

response = http.request(request)
puts response.read_body
```

**`Create session`**

```java
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.payroc.com/v1/processing-terminals/1234001/hosted-fields-sessions")
  .header("Idempotency-Key", "8e03978e-40d5-43e8-bc93-6894a57f9324")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"libVersion\": \"1.1.0.123456\",\n  \"scenario\": \"payment\"\n}")
  .asString();
```

**`Create session`**

```php
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.payroc.com/v1/processing-terminals/1234001/hosted-fields-sessions', [
  'body' => '{
  "libVersion": "1.1.0.123456",
  "scenario": "payment"
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
    'Idempotency-Key' => '8e03978e-40d5-43e8-bc93-6894a57f9324',
  ],
]);

echo $response->getBody();
```

**`Create session`**

```csharp
using RestSharp;

var client = new RestClient("https://api.payroc.com/v1/processing-terminals/1234001/hosted-fields-sessions");
var request = new RestRequest(Method.POST);
request.AddHeader("Idempotency-Key", "8e03978e-40d5-43e8-bc93-6894a57f9324");
request.AddHeader("Authorization", "Bearer <token>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"libVersion\": \"1.1.0.123456\",\n  \"scenario\": \"payment\"\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

**`Create session`**

```swift
import Foundation

let headers = [
  "Idempotency-Key": "8e03978e-40d5-43e8-bc93-6894a57f9324",
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = [
  "libVersion": "1.1.0.123456",
  "scenario": "payment"
] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://api.payroc.com/v1/processing-terminals/1234001/hosted-fields-sessions")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```

<a id="response-fields"></a>
### Response fields

If your request is successful, our gateway generates a session token. The response contains the following fields:

<a id="schema-responsebody"></a>
### Schema (`response.body`)

[Response body schema for `POST /processing-terminals/{processingTerminalId}/hosted-fields-sessions`](/api/create-session)

<a id="example-response"></a>
### Example response

<a id="response-201"></a>
### Response (201)

```json
{
  "processingTerminalId": "1234001",
  "token": "abcdef1234567890abcdef1234567890",
  "expiresAt": "2025-07-02T15:30:00.123456789+02:00"
}
```
