# Run a sale

Run a card sale on a Payroc Cloud device by submitting a payment instruction via POST to the Devices endpoint, polling for status, and retrieving the final payment result.

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

After you configure a device for Payroc Cloud, program your POS to send a payment instruction to the payment device. Your POS then checks the status of the instruction until the payment finishes, and views the details of the payment.

<a id="how-it-works"></a>
## How it works

```mermaid
sequenceDiagram
    participant POS as Your POS
    participant GW as Gateway
    participant D as Payment device

    rect rgba(0, 81, 194, 0.4)
        Note over POS,D: 1. Submit a payment instruction
        POS->>GW: POST /devices/{serialNumber}/payment-instructions
        GW->>D: Send the payment instruction
        GW-->>POS: paymentInstructionId, status = inProgress
    end

    rect rgba(0, 224, 184, 0.3)
        Note over POS,D: 2. Check the status of the payment instruction
        Note over D: Cardholder taps their card and<br />completes the payment on the device
        loop Until the status changes from inProgress
            POS->>GW: GET /payment-instructions/{paymentInstructionId}
            Note over GW: Waits up to a minute<br />for the status to change
            GW-->>POS: Current status<br />(when complete, includes a link to the payment)
        end
    end

    rect rgba(0, 224, 184, 0.3)
        Note over POS,GW: 3. View the details of the payment
        POS->>GW: GET /payments/{paymentId}
        GW-->>POS: Payment details (approved or declined)
    end

    opt Cancel while the status is inProgress
        POS->>GW: DELETE /payment-instructions/{paymentInstructionId}
        GW-->>POS: Payment instruction canceled
    end
```

1. Your POS submits a payment instruction to the device. Our gateway sends the instruction to the device and returns a `paymentInstructionId` with a status of `inProgress`.
2. The cardholder completes the payment on the device. Your POS checks the status of the payment instruction. Our gateway waits up to a minute for the status to change before it responds. If the status is still `inProgress`, your POS sends another request and keeps checking until the status changes.
3. When the payment finishes, your POS uses the link in the response to view the details of the payment and to check whether the processor approved it or declined it.

You can also cancel the payment instruction while its status is `inProgress`.

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

[Authenticate your requests](/api/authentication) before making API calls. If your request fails, see [Errors](/api/errors).

<a id="step-1-submit-a-payment-instruction"></a>
## Step 1. Submit a payment instruction

To submit a payment instruction to the device, send a POST request to the Devices endpoint.

| Environment | URL |
| --- | --- |
| Test | `https://api.uat.payroc.com/v1/devices/{serialNumber}/payment-instructions` |
| Production | `https://api.payroc.com/v1/devices/{serialNumber}/payment-instructions` |

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

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

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

[Request body schema for `POST /devices/{serialNumber}/payment-instructions`](/api/send-payment-instruction)

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

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

POST https://api.payroc.com/v1/devices/\{serialNumber\}/payment-instructions

```curl
curl -X POST https://api.payroc.com/v1/devices/1850010868/payment-instructions \
     -H "Idempotency-Key: 8e03978e-40d5-43e8-bc93-6894a57f9324" \
     -H "Authorization: Bearer <token>" \
     -H "Content-Type: application/json" \
     -d '{
  "processingTerminalId": "1234001",
  "order": {
    "orderId": "OrderRef6543",
    "amount": 4999,
    "currency": "USD"
  },
  "operator": "Jane",
  "customizationOptions": {
    "entryMethod": "deviceRead"
  },
  "autoCapture": true
}'
```

**`Payment Instruction`**

```python
import requests

url = "https://api.payroc.com/v1/devices/1850010868/payment-instructions"

payload = {
    "processingTerminalId": "1234001",
    "order": {
        "orderId": "OrderRef6543",
        "amount": 4999,
        "currency": "USD"
    },
    "operator": "Jane",
    "customizationOptions": { "entryMethod": "deviceRead" },
    "autoCapture": True
}
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())
```

**`Payment Instruction`**

```javascript
const url = 'https://api.payroc.com/v1/devices/1850010868/payment-instructions';
const options = {
  method: 'POST',
  headers: {
    'Idempotency-Key': '8e03978e-40d5-43e8-bc93-6894a57f9324',
    Authorization: 'Bearer <token>',
    'Content-Type': 'application/json'
  },
  body: '{"processingTerminalId":"1234001","order":{"orderId":"OrderRef6543","amount":4999,"currency":"USD"},"operator":"Jane","customizationOptions":{"entryMethod":"deviceRead"},"autoCapture":true}'
};

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

**`Payment Instruction`**

```go
package main

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

func main() {

	url := "https://api.payroc.com/v1/devices/1850010868/payment-instructions"

	payload := strings.NewReader("{\n  \"processingTerminalId\": \"1234001\",\n  \"order\": {\n    \"orderId\": \"OrderRef6543\",\n    \"amount\": 4999,\n    \"currency\": \"USD\"\n  },\n  \"operator\": \"Jane\",\n  \"customizationOptions\": {\n    \"entryMethod\": \"deviceRead\"\n  },\n  \"autoCapture\": true\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))

}
```

**`Payment Instruction`**

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

url = URI("https://api.payroc.com/v1/devices/1850010868/payment-instructions")

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  \"processingTerminalId\": \"1234001\",\n  \"order\": {\n    \"orderId\": \"OrderRef6543\",\n    \"amount\": 4999,\n    \"currency\": \"USD\"\n  },\n  \"operator\": \"Jane\",\n  \"customizationOptions\": {\n    \"entryMethod\": \"deviceRead\"\n  },\n  \"autoCapture\": true\n}"

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

**`Payment Instruction`**

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

HttpResponse<String> response = Unirest.post("https://api.payroc.com/v1/devices/1850010868/payment-instructions")
  .header("Idempotency-Key", "8e03978e-40d5-43e8-bc93-6894a57f9324")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"processingTerminalId\": \"1234001\",\n  \"order\": {\n    \"orderId\": \"OrderRef6543\",\n    \"amount\": 4999,\n    \"currency\": \"USD\"\n  },\n  \"operator\": \"Jane\",\n  \"customizationOptions\": {\n    \"entryMethod\": \"deviceRead\"\n  },\n  \"autoCapture\": true\n}")
  .asString();
```

**`Payment Instruction`**

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

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.payroc.com/v1/devices/1850010868/payment-instructions', [
  'body' => '{
  "processingTerminalId": "1234001",
  "order": {
    "orderId": "OrderRef6543",
    "amount": 4999,
    "currency": "USD"
  },
  "operator": "Jane",
  "customizationOptions": {
    "entryMethod": "deviceRead"
  },
  "autoCapture": true
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
    'Idempotency-Key' => '8e03978e-40d5-43e8-bc93-6894a57f9324',
  ],
]);

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

**`Payment Instruction`**

```csharp
using RestSharp;

var client = new RestClient("https://api.payroc.com/v1/devices/1850010868/payment-instructions");
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  \"processingTerminalId\": \"1234001\",\n  \"order\": {\n    \"orderId\": \"OrderRef6543\",\n    \"amount\": 4999,\n    \"currency\": \"USD\"\n  },\n  \"operator\": \"Jane\",\n  \"customizationOptions\": {\n    \"entryMethod\": \"deviceRead\"\n  },\n  \"autoCapture\": true\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

**`Payment Instruction`**

```swift
import Foundation

let headers = [
  "Idempotency-Key": "8e03978e-40d5-43e8-bc93-6894a57f9324",
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = [
  "processingTerminalId": "1234001",
  "order": [
    "orderId": "OrderRef6543",
    "amount": 4999,
    "currency": "USD"
  ],
  "operator": "Jane",
  "customizationOptions": ["entryMethod": "deviceRead"],
  "autoCapture": true
] as [String : Any]

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

let request = NSMutableURLRequest(url: NSURL(string: "https://api.payroc.com/v1/devices/1850010868/payment-instructions")! 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, we send the payment instruction to the device.

\<Note\> **Note:** The response returns a value of `inProgress` for the status field and an identifier for the instruction that you can use to check the status of the instruction. To get a link to view the details of the payment, go to Step 2.  
\</Note\>

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

[Response body schema for `POST /devices/{serialNumber}/payment-instructions`](/api/send-payment-instruction)

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

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

```json
{
  "status": "inProgress",
  "paymentInstructionId": "a37439165d134678a9100ebba3b29597",
  "link": {
    "rel": "self",
    "method": "GET",
    "href": "https://api.payroc.com/v1/payment-instructions/a37439165d134678a9100ebba3b29597"
  }
}
```

<a id="step-2-view-the-status-of-a-payment-instruction"></a>
## Step 2. View the status of a payment instruction

To check for updates to the status of the payment instruction, send a GET request to the Payment Instructions endpoint.

| Environment | URL |
| --- | --- |
| Test | `https://api.uat.payroc.com/v1/payment-instructions/{paymentInstructionId}` |
| Production | `https://api.payroc.com/v1/payment-instructions/{paymentInstructionId}` |

Before our gateway sends a response, it waits for up to a minute for the status of the instruction to change. We recommend that you keep the session open until the status of the instruction changes or the request times out.

If the status of the instruction doesn’t change, send another GET request. Our gateway waits up to a minute for the status of the instruction to change. Continue to send GET requests until the status changes.

\<Note\> **Note:** Wait until you receive a response from our gateway before you send another request. \</Note\>

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

To create your request, use the following parameters:

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

[Path parameters for `GET /payment-instructions/{paymentInstructionId}`](/api/get-payment-instruction)

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

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

GET https://api.payroc.com/v1/payment-instructions/\{paymentInstructionId\}

```curl
curl https://api.payroc.com/v1/payment-instructions/e743a9165d134678a9100ebba3b29597 \
     -H "Authorization: Bearer <token>"
```

**`Payment instruction`**

```python
import requests

url = "https://api.payroc.com/v1/payment-instructions/e743a9165d134678a9100ebba3b29597"

headers = {"Authorization": "Bearer <token>"}

response = requests.get(url, headers=headers)

print(response.json())
```

**`Payment instruction`**

```javascript
const url = 'https://api.payroc.com/v1/payment-instructions/e743a9165d134678a9100ebba3b29597';
const options = {method: 'GET', headers: {Authorization: 'Bearer <token>'}};

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

**`Payment instruction`**

```go
package main

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

func main() {

	url := "https://api.payroc.com/v1/payment-instructions/e743a9165d134678a9100ebba3b29597"

	req, _ := http.NewRequest("GET", url, nil)

	req.Header.Add("Authorization", "Bearer <token>")

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

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

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

}
```

**`Payment instruction`**

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

url = URI("https://api.payroc.com/v1/payment-instructions/e743a9165d134678a9100ebba3b29597")

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

request = Net::HTTP::Get.new(url)
request["Authorization"] = 'Bearer <token>'

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

**`Payment instruction`**

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

HttpResponse<String> response = Unirest.get("https://api.payroc.com/v1/payment-instructions/e743a9165d134678a9100ebba3b29597")
  .header("Authorization", "Bearer <token>")
  .asString();
```

**`Payment instruction`**

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

$client = new \GuzzleHttp\Client();

$response = $client->request('GET', 'https://api.payroc.com/v1/payment-instructions/e743a9165d134678a9100ebba3b29597', [
  'headers' => [
    'Authorization' => 'Bearer <token>',
  ],
]);

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

**`Payment instruction`**

```csharp
using RestSharp;

var client = new RestClient("https://api.payroc.com/v1/payment-instructions/e743a9165d134678a9100ebba3b29597");
var request = new RestRequest(Method.GET);
request.AddHeader("Authorization", "Bearer <token>");
IRestResponse response = client.Execute(request);
```

**`Payment instruction`**

```swift
import Foundation

let headers = ["Authorization": "Bearer <token>"]

let request = NSMutableURLRequest(url: NSURL(string: "https://api.payroc.com/v1/payment-instructions/e743a9165d134678a9100ebba3b29597")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers

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-1"></a>
### Response fields

If your request is successful, we return the details of the payment instruction, including HATEOAS links to check the details of the payment. Use the HATEOAS links to get the paymentId, which you need in Step 3.

If the status of the payment instruction is `inProgress`, our gateway waits up to a minute for the status to change before it returns a response.

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

[Response body schema for `GET /payment-instructions/{paymentInstructionId}`](/api/get-payment-instruction)

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

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

```json
{
  "status": "completed",
  "paymentInstructionId": "a37439165d134678a9100ebba3b29597",
  "link": {
    "rel": "payment",
    "method": "GET",
    "href": "https://api.payroc.com/v1/payments/M2MJOG6O2Y"
  }
}
```

<a id="step-3-view-the-details-of-the-payment"></a>
## Step 3. View the details of the payment

To check whether the processor approved or declined the payment, send a GET request to the Payments endpoint.

| Environment | URL |
| --- | --- |
| Test | `https://api.uat.payroc.com/v1/payments/{paymentId}` |
| Production | `https://api.payroc.com/v1/payments/{paymentId}` |

<a id="request-parameters-2"></a>
### Request parameters

To create your request, use the following parameters:

<a id="schema-requestpath-1"></a>
### Schema (`request.path`)

[Path parameters for `GET /payments/{paymentId}`](/api/get-payment)

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

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

GET https://api.payroc.com/v1/payments/\{paymentId\}

```curl
curl https://api.payroc.com/v1/payments/M2MJOG6O2Y \
     -H "Authorization: Bearer <token>"
```

**`Payment`**

```python
import requests

url = "https://api.payroc.com/v1/payments/M2MJOG6O2Y"

headers = {"Authorization": "Bearer <token>"}

response = requests.get(url, headers=headers)

print(response.json())
```

**`Payment`**

```javascript
const url = 'https://api.payroc.com/v1/payments/M2MJOG6O2Y';
const options = {method: 'GET', headers: {Authorization: 'Bearer <token>'}};

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

**`Payment`**

```go
package main

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

func main() {

	url := "https://api.payroc.com/v1/payments/M2MJOG6O2Y"

	req, _ := http.NewRequest("GET", url, nil)

	req.Header.Add("Authorization", "Bearer <token>")

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

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

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

}
```

**`Payment`**

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

url = URI("https://api.payroc.com/v1/payments/M2MJOG6O2Y")

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

request = Net::HTTP::Get.new(url)
request["Authorization"] = 'Bearer <token>'

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

**`Payment`**

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

HttpResponse<String> response = Unirest.get("https://api.payroc.com/v1/payments/M2MJOG6O2Y")
  .header("Authorization", "Bearer <token>")
  .asString();
```

**`Payment`**

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

$client = new \GuzzleHttp\Client();

$response = $client->request('GET', 'https://api.payroc.com/v1/payments/M2MJOG6O2Y', [
  'headers' => [
    'Authorization' => 'Bearer <token>',
  ],
]);

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

**`Payment`**

```csharp
using RestSharp;

var client = new RestClient("https://api.payroc.com/v1/payments/M2MJOG6O2Y");
var request = new RestRequest(Method.GET);
request.AddHeader("Authorization", "Bearer <token>");
IRestResponse response = client.Execute(request);
```

**`Payment`**

```swift
import Foundation

let headers = ["Authorization": "Bearer <token>"]

let request = NSMutableURLRequest(url: NSURL(string: "https://api.payroc.com/v1/payments/M2MJOG6O2Y")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers

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-2"></a>
### Response fields

If your request is successful, we return the details of the payment.

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

[Response body schema for `GET /payments/{paymentId}`](/api/get-payment)

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

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

```json
{
  "paymentId": "M2MJOG6O2Y",
  "processingTerminalId": "1234001",
  "order": {
    "orderId": "OrderRef6543",
    "amount": 4999,
    "currency": "USD",
    "dateTime": "2024-07-02T15:30:00Z",
    "description": "Large Pepperoni Pizza"
  },
  "card": {
    "type": "MasterCard",
    "cardNumber": "453985******7062",
    "expiryDate": "1230",
    "entryMethod": "keyed",
    "securityChecks": {
      "cvvResult": "M",
      "avsResult": "Y"
    }
  },
  "transactionResult": {
    "status": "ready",
    "responseCode": "A",
    "type": "sale",
    "approvalCode": "OK3",
    "authorizedAmount": 4999,
    "currency": "USD",
    "responseMessage": "OK3"
  },
  "operator": "Jane",
  "customer": {
    "firstName": "Sarah",
    "lastName": "Hopper",
    "billingAddress": {
      "address1": "1 Example Ave.",
      "address2": "Example Address Line 2",
      "address3": "Example Address Line 3",
      "city": "Chicago",
      "state": "Illinois",
      "country": "US",
      "postalCode": "60056"
    },
    "shippingAddress": {
      "recipientName": "Sarah Hopper",
      "address": {
        "address1": "1 Example Ave.",
        "address2": "Example Address Line 2",
        "address3": "Example Address Line 3",
        "city": "Chicago",
        "state": "Illinois",
        "country": "US",
        "postalCode": "60056"
      }
    }
  },
  "supportedOperations": [
    "capture",
    "fullyReverse",
    "partiallyReverse",
    "incrementAuthorization",
    "adjustTip",
    "setAsPending"
  ],
  "customFields": [
    {
      "name": "yourCustomField",
      "value": "abc123"
    }
  ]
}
```

<a id="optional-cancel-a-payment-instruction"></a>
## (Optional) Cancel a payment instruction

To cancel a payment instruction, send a DELETE request to the Payment Instructions endpoint.

| Environment | URL |
| --- | --- |
| Test | `https://api.uat.payroc.com/v1/payment-instructions/{paymentInstructionId}` |
| Production | `https://api.payroc.com/v1/payment-instructions/{paymentInstructionId}` |

\<Note\> **Note:** You can cancel a payment instruction only if its status is `inProgress`. \</Note\>

<a id="request-parameters-3"></a>
### Request parameters

To create your request, use the following parameters:

<a id="schema-requestpath-2"></a>
### Schema (`request.path`)

[Path parameters for `DELETE /payment-instructions/{paymentInstructionId}`](/api/delete-payment-instruction)

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

<a id="schema"></a>
### Schema

[Operation schema for `DELETE /payment-instructions/{paymentInstructionId}`](/api/delete-payment-instruction)

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

If your request is successful, we cancel the payment instruction.
