# Run a referenced refund for a card payment

Refund a card payment by sending a POST request to the Payments endpoint using the original paymentId, with optional GET requests to retrieve payment details first.

**Prerequisites:** [Authentication](/api/authentication) · [Run a card sale](/guides/payments/run-a-card-sale)

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

A merchant can use the payment details of a card payment to run a referenced refund. To run a referenced refund, the merchant should first retrieve the payment information in one of the following ways:

- Use the paymentId.
- Search for the payment using payment information such as the card number.

**Note:** If the merchant runs a refund on a payment that is in an open batch, our gateway automatically cancels the payment.

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

**Step 1.** Retrieve information about the original payment.  
**(Optional) Step 1a.** Retrieve information about the payment using the paymentId.  
**(Optional) Step 1b.** Retrieve information about the payment without the paymentId.  
**Step 2.** Refund the payment.

<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-retrieve-information-about-the-original-payment"></a>
## Step 1. Retrieve information about the original payment

**1a – (Optional) Retrieve information with the paymentId**

Send a GET request with the paymentID to the Payments endpoint.

| Environment | URL |
| --- | --- |
| Test | [https://api.uat.payroc.com/v1/payments/\{paymentId\}](https://api.uat.payroc.com/v1/payments/%7BpaymentId%7D) |
| Production | [https://api.payroc.com/v1/payments/\{paymentId\}](https://api.payroc.com/v1/payments/%7BpaymentId%7D) |

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

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

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

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

GET [https://api.payroc.com/v1/payments/\{paymentId\}](https://api.payroc.com/v1/payments/%7BpaymentId%7D)

**`Payment`**

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

If your request is successful, we retrieve the card payment information and return a response. The response contains the following fields:

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

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

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

<a id="response-200"></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"
    }
  ]
}
```

**1b (Optional) – Retrieve information without the payment ID**

Send a GET request to the Payments endpoint.

| Environment | URL |
| --- | --- |
| Test | [https://api.uat.payroc.com/v1/payments](https://api.uat.payroc.com/v1/payments) |
| Production | [https://api.payroc.com/v1/payments](https://api.payroc.com/v1/payments) |

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

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

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

[Path parameters for `GET /payments`](/api/list-payments)

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

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

GET [https://api.payroc.com/v1/payments](https://api.payroc.com/v1/payments)

**`Payment`**

```curl
curl -G https://api.payroc.com/v1/payments \
     -H "Authorization: Bearer <token>" \
     -d after=8516 \
     -d before=2571 \
     --data-urlencode cardholderName=Sarah%20Hazel%20Hopper \
     --data-urlencode dateFrom=2024-07-01T15:30:00Z \
     --data-urlencode dateTo=2024-07-03T15:30:00Z \
     -d first6=453985 \
     -d last4=7062 \
     -d limit=25 \
     -d operator=Jane \
     -d orderId=OrderRef6543 \
     -d paymentLinkId=JZURRJBUPS \
     -d processingTerminalId=1234001 \
     -d settlementDate=2024-07-02 \
     -d settlementState=settled \
     -d status=accepted \
     -d status=ready \
     -d status=complete \
     -d tender=ebt \
     -d tipMode=noTip \
     -d tipMode=prompted \
     -d type=sale \
     -d type=preAuthorization
```

**`Payment`**

```python
import requests

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

querystring = {"after":"8516","before":"2571","cardholderName":"Sarah%20Hazel%20Hopper","dateFrom":"2024-07-01T15:30:00Z","dateTo":"2024-07-03T15:30:00Z","first6":"453985","last4":"7062","limit":"25","operator":"Jane","orderId":"OrderRef6543","paymentLinkId":"JZURRJBUPS","processingTerminalId":"1234001","settlementDate":"2024-07-02","settlementState":"settled","status":"[\"accepted\",\"ready\",\"complete\"]","tender":"ebt","tipMode":"[\"noTip\",\"prompted\"]","type":"[\"sale\",\"preAuthorization\"]"}

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

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

print(response.json())
```

**`Payment`**

```javascript
const url = 'https://api.payroc.com/v1/payments?after=8516&before=2571&cardholderName=Sarah%2520Hazel%2520Hopper&dateFrom=2024-07-01T15%3A30%3A00Z&dateTo=2024-07-03T15%3A30%3A00Z&first6=453985&last4=7062&limit=25&operator=Jane&orderId=OrderRef6543&paymentLinkId=JZURRJBUPS&processingTerminalId=1234001&settlementDate=2024-07-02&settlementState=settled&status=%5B%22accepted%22%2C%22ready%22%2C%22complete%22%5D&tender=ebt&tipMode=%5B%22noTip%22%2C%22prompted%22%5D&type=%5B%22sale%22%2C%22preAuthorization%22%5D';
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?after=8516&before=2571&cardholderName=Sarah%2520Hazel%2520Hopper&dateFrom=2024-07-01T15%3A30%3A00Z&dateTo=2024-07-03T15%3A30%3A00Z&first6=453985&last4=7062&limit=25&operator=Jane&orderId=OrderRef6543&paymentLinkId=JZURRJBUPS&processingTerminalId=1234001&settlementDate=2024-07-02&settlementState=settled&status=%5B%22accepted%22%2C%22ready%22%2C%22complete%22%5D&tender=ebt&tipMode=%5B%22noTip%22%2C%22prompted%22%5D&type=%5B%22sale%22%2C%22preAuthorization%22%5D"

	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?after=8516&before=2571&cardholderName=Sarah%2520Hazel%2520Hopper&dateFrom=2024-07-01T15%3A30%3A00Z&dateTo=2024-07-03T15%3A30%3A00Z&first6=453985&last4=7062&limit=25&operator=Jane&orderId=OrderRef6543&paymentLinkId=JZURRJBUPS&processingTerminalId=1234001&settlementDate=2024-07-02&settlementState=settled&status=%5B%22accepted%22%2C%22ready%22%2C%22complete%22%5D&tender=ebt&tipMode=%5B%22noTip%22%2C%22prompted%22%5D&type=%5B%22sale%22%2C%22preAuthorization%22%5D")

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?after=8516&before=2571&cardholderName=Sarah%2520Hazel%2520Hopper&dateFrom=2024-07-01T15%3A30%3A00Z&dateTo=2024-07-03T15%3A30%3A00Z&first6=453985&last4=7062&limit=25&operator=Jane&orderId=OrderRef6543&paymentLinkId=JZURRJBUPS&processingTerminalId=1234001&settlementDate=2024-07-02&settlementState=settled&status=%5B%22accepted%22%2C%22ready%22%2C%22complete%22%5D&tender=ebt&tipMode=%5B%22noTip%22%2C%22prompted%22%5D&type=%5B%22sale%22%2C%22preAuthorization%22%5D")
  .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?after=8516&before=2571&cardholderName=Sarah%2520Hazel%2520Hopper&dateFrom=2024-07-01T15%3A30%3A00Z&dateTo=2024-07-03T15%3A30%3A00Z&first6=453985&last4=7062&limit=25&operator=Jane&orderId=OrderRef6543&paymentLinkId=JZURRJBUPS&processingTerminalId=1234001&settlementDate=2024-07-02&settlementState=settled&status=%5B%22accepted%22%2C%22ready%22%2C%22complete%22%5D&tender=ebt&tipMode=%5B%22noTip%22%2C%22prompted%22%5D&type=%5B%22sale%22%2C%22preAuthorization%22%5D', [
  'headers' => [
    'Authorization' => 'Bearer <token>',
  ],
]);

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

**`Payment`**

```csharp
using RestSharp;

var client = new RestClient("https://api.payroc.com/v1/payments?after=8516&before=2571&cardholderName=Sarah%2520Hazel%2520Hopper&dateFrom=2024-07-01T15%3A30%3A00Z&dateTo=2024-07-03T15%3A30%3A00Z&first6=453985&last4=7062&limit=25&operator=Jane&orderId=OrderRef6543&paymentLinkId=JZURRJBUPS&processingTerminalId=1234001&settlementDate=2024-07-02&settlementState=settled&status=%5B%22accepted%22%2C%22ready%22%2C%22complete%22%5D&tender=ebt&tipMode=%5B%22noTip%22%2C%22prompted%22%5D&type=%5B%22sale%22%2C%22preAuthorization%22%5D");
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?after=8516&before=2571&cardholderName=Sarah%2520Hazel%2520Hopper&dateFrom=2024-07-01T15%3A30%3A00Z&dateTo=2024-07-03T15%3A30%3A00Z&first6=453985&last4=7062&limit=25&operator=Jane&orderId=OrderRef6543&paymentLinkId=JZURRJBUPS&processingTerminalId=1234001&settlementDate=2024-07-02&settlementState=settled&status=%5B%22accepted%22%2C%22ready%22%2C%22complete%22%5D&tender=ebt&tipMode=%5B%22noTip%22%2C%22prompted%22%5D&type=%5B%22sale%22%2C%22preAuthorization%22%5D")! 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 retrieve a list of card payments and return a response. The response contains the following fields:

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

[Response body schema for `GET /payments`](/api/list-payments)

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

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

```json
{
  "limit": 2,
  "count": 2,
  "hasMore": true,
  "data": [
    {
      "paymentId": "M2MJOG6O2Y",
      "processingTerminalId": "1234001",
      "order": {
        "orderId": "OrderRef6543",
        "amount": 4999,
        "currency": "USD",
        "dateTime": "2024-07-02T15:30:00Z",
        "description": "Monthly Premium Club subscription"
      },
      "card": {
        "type": "Visa Credit",
        "cardNumber": "453985******7062",
        "expiryDate": "1230",
        "entryMethod": "keyed",
        "cardholderName": "Sarah Hopper",
        "secureToken": {
          "secureTokenId": "MREF_abc1de23-f4a5-6789-bcd0-12e345678901fa",
          "customerName": "Sarah Hopper",
          "token": "296753123456",
          "status": "notValidated",
          "link": {
            "rel": "self",
            "method": "GET",
            "href": "https://api.payroc.com/v1/processing-terminals/1234001/secure-tokens/MREF_abc1de23-f4a5-6789-bcd0-12e345678901fa"
          }
        },
        "securityChecks": {
          "cvvResult": "M",
          "avsResult": "X"
        }
      },
      "transactionResult": {
        "status": "ready",
        "responseCode": "A",
        "type": "sale",
        "approvalCode": "OK3",
        "authorizedAmount": 4999,
        "currency": "USD",
        "responseMessage": "APPROVAL"
      },
      "operator": "Automatic Payment",
      "supportedOperations": [
        "fullyReverse",
        "setAsPending"
      ]
    },
    {
      "paymentId": "E29U8OU8Q4",
      "processingTerminalId": "1234001",
      "order": {
        "orderId": "OrderRef7654",
        "amount": 4999,
        "currency": "USD",
        "dateTime": "2024-07-02T15:30:00Z",
        "description": "Monthly Premium Club subscription"
      },
      "card": {
        "type": "Visa Debit",
        "cardNumber": "453985******7062",
        "expiryDate": "1230",
        "entryMethod": "keyed",
        "cardholderName": "Sarah Hopper",
        "secureToken": {
          "secureTokenId": "MREF_abc1de23-f4a5-6789-bcd0-12e345678901fa",
          "customerName": "Sarah Hopper",
          "token": "296753123456",
          "status": "notValidated",
          "link": {
            "rel": "self",
            "method": "GET",
            "href": "https://api.payroc.com/v1/processing-terminals/1234001/secure-tokens/MREF_abc1de23-f4a5-6789-bcd0-12e345678901fa"
          }
        },
        "securityChecks": {
          "cvvResult": "M",
          "avsResult": "X"
        }
      },
      "transactionResult": {
        "status": "ready",
        "responseCode": "A",
        "type": "sale",
        "approvalCode": "475318",
        "authorizedAmount": 1000,
        "currency": "EUR",
        "responseMessage": "APPROVAL"
      },
      "operator": "Automatic Payment",
      "supportedOperations": [
        "fullyReverse",
        "setAsPending"
      ],
      "customFields": [
        {
          "name": "yourCustomField",
          "value": "abc123"
        }
      ]
    }
  ],
  "links": [
    {
      "rel": "next",
      "method": "get",
      "href": "https://api.payroc.com/v1/payments?processingTerminalId=1234001&limit=2&after=E29U8OU8Q4"
    },
    {
      "rel": "previous",
      "method": "get",
      "href": "https://api.payroc.com/v1/payments?processingTerminalId=1234001&limit=2&before=M2MJOG6O2Y"
    }
  ]
}
```

<a id="step-2-refund-the-payment"></a>
## Step 2. Refund the payment

To refund a card transfer payment, send a POST request to the Payments endpoint.

| Environment | URL |
| --- | --- |
| Test | [https://api.uat.payroc.com/v1/payments/\{paymentId\}/refund](https://api.uat.payroc.com/v1/payments/%7BpaymentId%7D/refund) |
| Production | [https://api.payroc.com/v1/payments/\{paymentId\}/refund](https://api.payroc.com/v1/payments/%7BpaymentId%7D/refund) |

<a id="request-parameters-1"></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 /payments/{paymentId}/refund`](/api/refund-payment)

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

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

POST [https://api.payroc.com/v1/payments/\{paymentId\}/refund](https://api.payroc.com/v1/payments/%7BpaymentId%7D/refund)

**`Refund Payment`**

```curl
curl -X POST https://api.payroc.com/v1/payments/M2MJOG6O2Y/refund \
     -H "Idempotency-Key: 8e03978e-40d5-43e8-bc93-6894a57f9324" \
     -H "Authorization: Bearer <token>" \
     -H "Content-Type: application/json" \
     -d '{
  "amount": 4999,
  "description": "Refund for order OrderRef6543"
}'
```

**`Refund Payment`**

```python
import requests

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

payload = {
    "amount": 4999,
    "description": "Refund for order OrderRef6543"
}
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())
```

**`Refund Payment`**

```javascript
const url = 'https://api.payroc.com/v1/payments/M2MJOG6O2Y/refund';
const options = {
  method: 'POST',
  headers: {
    'Idempotency-Key': '8e03978e-40d5-43e8-bc93-6894a57f9324',
    Authorization: 'Bearer <token>',
    'Content-Type': 'application/json'
  },
  body: '{"amount":4999,"description":"Refund for order OrderRef6543"}'
};

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

**`Refund Payment`**

```go
package main

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

func main() {

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

	payload := strings.NewReader("{\n  \"amount\": 4999,\n  \"description\": \"Refund for order OrderRef6543\"\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))

}
```

**`Refund Payment`**

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

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

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  \"amount\": 4999,\n  \"description\": \"Refund for order OrderRef6543\"\n}"

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

**`Refund Payment`**

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

HttpResponse<String> response = Unirest.post("https://api.payroc.com/v1/payments/M2MJOG6O2Y/refund")
  .header("Idempotency-Key", "8e03978e-40d5-43e8-bc93-6894a57f9324")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"amount\": 4999,\n  \"description\": \"Refund for order OrderRef6543\"\n}")
  .asString();
```

**`Refund Payment`**

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

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.payroc.com/v1/payments/M2MJOG6O2Y/refund', [
  'body' => '{
  "amount": 4999,
  "description": "Refund for order OrderRef6543"
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
    'Idempotency-Key' => '8e03978e-40d5-43e8-bc93-6894a57f9324',
  ],
]);

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

**`Refund Payment`**

```csharp
using RestSharp;

var client = new RestClient("https://api.payroc.com/v1/payments/M2MJOG6O2Y/refund");
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  \"amount\": 4999,\n  \"description\": \"Refund for order OrderRef6543\"\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

**`Refund Payment`**

```swift
import Foundation

let headers = [
  "Idempotency-Key": "8e03978e-40d5-43e8-bc93-6894a57f9324",
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = [
  "amount": 4999,
  "description": "Refund for order OrderRef6543"
] as [String : Any]

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

let request = NSMutableURLRequest(url: NSURL(string: "https://api.payroc.com/v1/payments/M2MJOG6O2Y/refund")! 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-2"></a>
### Response fields

If your request is successful, we refund the card payment and return a response. The response contains the following fields:

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

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

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

<a id="response-200-2"></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",
    "entryMethod": "keyed",
    "cardNumber": "453985******7062",
    "expiryDate": "1230",
    "securityChecks": {
      "cvvResult": "M",
      "avsResult": "Y"
    }
  },
  "transactionResult": {
    "status": "complete",
    "responseCode": "A",
    "type": "sale",
    "approvalCode": "OK3",
    "authorizedAmount": 4999,
    "currency": "USD",
    "responseMessage": "OK13"
  },
  "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"
      }
    }
  },
  "refunds": [
    {
      "refundId": "CD3HN88U9F",
      "dateTime": "2024-07-02T15:30:00Z",
      "currency": "USD",
      "amount": -4999,
      "status": "ready",
      "responseCode": "A",
      "responseMessage": "Transaction refunded",
      "link": {
        "rel": "self",
        "method": "GET",
        "href": "https://api.payroc.com/v1/refunds/BI77XQFQ05"
      }
    }
  ],
  "supportedOperations": [
    "refund"
  ],
  "customFields": [
    {
      "name": "yourCustomField",
      "value": "acb123"
    }
  ]
}
```

<a id="test-cases"></a>
## Test cases

Before you run test cases, read the [Payments](/guides/testing/online-payments) page in Test Your Integration.

<a id="refund-a-card-payment"></a>
### Refund a card payment

Send a POST request to the following endpoint:

POST [https://api.uat.payroc.com/v1/payments/\{paymentId\}/refund](https://api.uat.payroc.com/v1/payments/%7BpaymentId%7D/refund)

**Note:** To settle a payment, the terminal must first close the batch and then our gateway settles the payments within an hour. To adjust when the terminal closes a batch, use the terminal settings in the Merchant Portal.

**Example response**

```json
{
	"paymentId": "C8Y177VHWR",
	"processingTerminalId": "3204001",
	"order": {
		"orderId": "Test_006",
		"dateTime": "2023-05-24T15:21:01+01:00",
		"amount": 4000,
		"currency": "USD",
		"standingInstructions": {
			"sequence": "subsequent",
			"processingModel": "recurring"
		}
	},
	"card": {
		"type": "Visa Credit",
		"entryMethod": "keyed",
		"cardNumber": "444433******1111",
		"expiryDate": "1226",
		"secureToken": {
			"secureTokenId": "MREF_1a93f3a6-9029-419f-9e87-3e2db6f0ae85uA",
			"customerName": "",
			"token": "2967538502417872",
			"status": "cvv_validated",
			"link": {
				"rel": "self",
				"method": "GET",
				"href": "https://api.uat.payroc.com/v1/processing-terminals/3204001/secure-tokens/MREF_1a93f3a6-9029-419f-9e87-3e2db6f0ae85uA"
			}
		},
		"securityChecks": {
			"cvvResult": "M",
			"avsResult": "Y"
		}
	},
	"refunds": [
		{
			"refundId": "G6T6S6KF74",
			"dateTime": "2023-05-25T11:12:55+01:00",
			"amount": -4000,
			"currency": "USD",
			"status": "ready",
			"link": {
				"rel": "self",
				"method": "GET",
				"href": "https://api.uat.payroc.com/v1/refunds/G6T6S6KF74"
			}
		}
	],
	"transactionResult": {
		"type": "sale",
		"status": "ready",
		"approvalCode": "OK14486",
		"authorizedAmount": 4000,
		"currency": "USD",
		"responseCode": "A",
		"responseMessage": "OK14486",
		"cardSchemeReferenceId": "JxDfFMHyOE2lyQJ2MnFp"
	}
}

```
