# Use our gateway

Set up recurring billing by creating a payment plan, saving a secure token, and assigning a customer to a subscription via POST requests to the Payment Plans, Secure Tokens, and Subscriptions endpoints.

**Prerequisites:** [Authentication](/api/authentication)

A merchant can use our gateway to take repeat payments automatically or manually from their customers.

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

```mermaid
sequenceDiagram
    actor C as Customer
    participant MS as Merchant's server
    participant GW as Gateway

    rect rgba(0, 81, 194, 0.4)
        Note over MS,GW: Step 1 — Create a payment plan
        MS->>GW: POST /payment-plans
        Note over MS,GW: name, currency, type, frequency,<br />length, recurringOrder.amount
        GW-->>MS: paymentPlanId
        Note right of MS: Store paymentPlanId
    end

    rect rgba(0, 224, 184, 0.3)
        Note over C,GW: Step 2 — Create a secure token
        C->>MS: Provide payment details
        MS->>GW: POST /secure-tokens
        GW-->>MS: secureToken
        Note right of MS: Store the secure token
    end

    rect rgba(0, 224, 184, 0.3)
        Note over MS,GW: Step 3 — Create a subscription
        MS->>GW: POST /subscriptions
        Note over MS,GW: paymentPlanId,<br />paymentMethod.secureToken.token,<br />startDate
        GW-->>MS: subscriptionId
        Note right of MS: Store subscriptionId
    end

    rect rgba(0, 224, 184, 0.3)
        Note over C,GW: Step 4 — Collect payments
        alt Automatic plan
            GW-->>C: Gateway collects on schedule
        else Manual plan
            MS->>GW: POST /subscriptions/{subscriptionId}/pay
            Note over MS,GW: order.orderId, order.amount
            GW-->>MS: Payment confirmed
        end
    end
```

1. You create a payment plan with our API. Our gateway returns a `paymentPlanId`.
2. You collect the customer's payment details and save them as a secure token.
3. You create a subscription to assign the customer to the payment plan. In your request, send the `paymentPlanId` and the secure token.
4. Our gateway collects payments automatically according to the plan schedule. If the payment plan uses manual collection, use the `subscriptionId` to collect each payment.

A payment plan is a template that describes how the merchant takes payments from their customers, including the following information:

- Number of payments
- Length of the payment plan
- Amount for each payment
- How often payments are taken
- Initial costs
- Whether to automatically collect payments or manually collect payments

A merchant can create multiple payment plans and assign multiple customers to each plan. For example, if the merchant wants to allow customers to pay in weekly installments or in monthly installments, the merchant creates a payment plan for each installment schedule. The merchant can then offer customers a choice of payment plans, and then use subscriptions to assign customers to the plans that they choose.

If the merchant chooses to automatically collect payments, our gateway collects payments from each customer. If the merchant chooses to manually collect payments, they need to use their POS to collect the payments.

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

To use our gateway to take regular payments, integrate with the following:

**Step 1.** Create a payment plan.  
**Step 2.** Create a secure token.  
**Step 3.** Create a subscription.  
**Step 4.** (Optional) Manually collect a payment from the customer.

<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-create-a-payment-plan"></a>
## Step 1. Create a payment plan

To create a payment plan, send a POST request to our Payment Plans endpoint:

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

**Note:** To allow merchants to add their own information to the payment plan, use custom fields. For more information about how to add custom fields, go to [Add custom fields to your integration](/guides/payments/add-custom-fields).

<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 /processing-terminals/{processingTerminalId}/payment-plans`](/api/create-payment-plan)

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

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

POST https://api.payroc.com/v1/processing-terminals/\{processingTerminalId\}/payment-plans

```curl
curl -X POST https://api.payroc.com/v1/processing-terminals/1234001/payment-plans \
     -H "Idempotency-Key: 8e03978e-40d5-43e8-bc93-6894a57f9324" \
     -H "Authorization: Bearer <token>" \
     -H "Content-Type: application/json" \
     -d '{
  "paymentPlanId": "PlanRef8765",
  "name": "Premium Club",
  "currency": "USD",
  "type": "automatic",
  "frequency": "monthly",
  "onUpdate": "continue",
  "onDelete": "complete",
  "description": "Monthly Premium Club subscription",
  "length": 12,
  "customFieldNames": [
    "yourCustomField"
  ],
  "setupOrder": {
    "amount": 4999,
    "description": "Initial setup fee for Premium Club subscription",
    "breakdown": {
      "subtotal": 4347,
      "taxes": [
        {
          "name": "Sales Tax",
          "rate": 5
        }
      ]
    }
  },
  "recurringOrder": {
    "amount": 4999,
    "description": "Monthly Premium Club subscription",
    "breakdown": {
      "subtotal": 4347,
      "taxes": [
        {
          "name": "Sales Tax",
          "rate": 5
        }
      ]
    }
  }
}'
```

**`Payment Plan`**

```python
import requests

url = "https://api.payroc.com/v1/processing-terminals/1234001/payment-plans"

payload = {
    "paymentPlanId": "PlanRef8765",
    "name": "Premium Club",
    "currency": "USD",
    "type": "automatic",
    "frequency": "monthly",
    "onUpdate": "continue",
    "onDelete": "complete",
    "description": "Monthly Premium Club subscription",
    "length": 12,
    "customFieldNames": ["yourCustomField"],
    "setupOrder": {
        "amount": 4999,
        "description": "Initial setup fee for Premium Club subscription",
        "breakdown": {
            "subtotal": 4347,
            "taxes": [
                {
                    "name": "Sales Tax",
                    "rate": 5
                }
            ]
        }
    },
    "recurringOrder": {
        "amount": 4999,
        "description": "Monthly Premium Club subscription",
        "breakdown": {
            "subtotal": 4347,
            "taxes": [
                {
                    "name": "Sales Tax",
                    "rate": 5
                }
            ]
        }
    }
}
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 Plan`**

```javascript
const url = 'https://api.payroc.com/v1/processing-terminals/1234001/payment-plans';
const options = {
  method: 'POST',
  headers: {
    'Idempotency-Key': '8e03978e-40d5-43e8-bc93-6894a57f9324',
    Authorization: 'Bearer <token>',
    'Content-Type': 'application/json'
  },
  body: '{"paymentPlanId":"PlanRef8765","name":"Premium Club","currency":"USD","type":"automatic","frequency":"monthly","onUpdate":"continue","onDelete":"complete","description":"Monthly Premium Club subscription","length":12,"customFieldNames":["yourCustomField"],"setupOrder":{"amount":4999,"description":"Initial setup fee for Premium Club subscription","breakdown":{"subtotal":4347,"taxes":[{"name":"Sales Tax","rate":5}]}},"recurringOrder":{"amount":4999,"description":"Monthly Premium Club subscription","breakdown":{"subtotal":4347,"taxes":[{"name":"Sales Tax","rate":5}]}}}'
};

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

**`Payment Plan`**

```go
package main

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

func main() {

	url := "https://api.payroc.com/v1/processing-terminals/1234001/payment-plans"

	payload := strings.NewReader("{\n  \"paymentPlanId\": \"PlanRef8765\",\n  \"name\": \"Premium Club\",\n  \"currency\": \"USD\",\n  \"type\": \"automatic\",\n  \"frequency\": \"monthly\",\n  \"onUpdate\": \"continue\",\n  \"onDelete\": \"complete\",\n  \"description\": \"Monthly Premium Club subscription\",\n  \"length\": 12,\n  \"customFieldNames\": [\n    \"yourCustomField\"\n  ],\n  \"setupOrder\": {\n    \"amount\": 4999,\n    \"description\": \"Initial setup fee for Premium Club subscription\",\n    \"breakdown\": {\n      \"subtotal\": 4347,\n      \"taxes\": [\n        {\n          \"name\": \"Sales Tax\",\n          \"rate\": 5\n        }\n      ]\n    }\n  },\n  \"recurringOrder\": {\n    \"amount\": 4999,\n    \"description\": \"Monthly Premium Club subscription\",\n    \"breakdown\": {\n      \"subtotal\": 4347,\n      \"taxes\": [\n        {\n          \"name\": \"Sales Tax\",\n          \"rate\": 5\n        }\n      ]\n    }\n  }\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 Plan`**

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

url = URI("https://api.payroc.com/v1/processing-terminals/1234001/payment-plans")

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  \"paymentPlanId\": \"PlanRef8765\",\n  \"name\": \"Premium Club\",\n  \"currency\": \"USD\",\n  \"type\": \"automatic\",\n  \"frequency\": \"monthly\",\n  \"onUpdate\": \"continue\",\n  \"onDelete\": \"complete\",\n  \"description\": \"Monthly Premium Club subscription\",\n  \"length\": 12,\n  \"customFieldNames\": [\n    \"yourCustomField\"\n  ],\n  \"setupOrder\": {\n    \"amount\": 4999,\n    \"description\": \"Initial setup fee for Premium Club subscription\",\n    \"breakdown\": {\n      \"subtotal\": 4347,\n      \"taxes\": [\n        {\n          \"name\": \"Sales Tax\",\n          \"rate\": 5\n        }\n      ]\n    }\n  },\n  \"recurringOrder\": {\n    \"amount\": 4999,\n    \"description\": \"Monthly Premium Club subscription\",\n    \"breakdown\": {\n      \"subtotal\": 4347,\n      \"taxes\": [\n        {\n          \"name\": \"Sales Tax\",\n          \"rate\": 5\n        }\n      ]\n    }\n  }\n}"

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

**`Payment Plan`**

```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/payment-plans")
  .header("Idempotency-Key", "8e03978e-40d5-43e8-bc93-6894a57f9324")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"paymentPlanId\": \"PlanRef8765\",\n  \"name\": \"Premium Club\",\n  \"currency\": \"USD\",\n  \"type\": \"automatic\",\n  \"frequency\": \"monthly\",\n  \"onUpdate\": \"continue\",\n  \"onDelete\": \"complete\",\n  \"description\": \"Monthly Premium Club subscription\",\n  \"length\": 12,\n  \"customFieldNames\": [\n    \"yourCustomField\"\n  ],\n  \"setupOrder\": {\n    \"amount\": 4999,\n    \"description\": \"Initial setup fee for Premium Club subscription\",\n    \"breakdown\": {\n      \"subtotal\": 4347,\n      \"taxes\": [\n        {\n          \"name\": \"Sales Tax\",\n          \"rate\": 5\n        }\n      ]\n    }\n  },\n  \"recurringOrder\": {\n    \"amount\": 4999,\n    \"description\": \"Monthly Premium Club subscription\",\n    \"breakdown\": {\n      \"subtotal\": 4347,\n      \"taxes\": [\n        {\n          \"name\": \"Sales Tax\",\n          \"rate\": 5\n        }\n      ]\n    }\n  }\n}")
  .asString();
```

**`Payment Plan`**

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

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.payroc.com/v1/processing-terminals/1234001/payment-plans', [
  'body' => '{
  "paymentPlanId": "PlanRef8765",
  "name": "Premium Club",
  "currency": "USD",
  "type": "automatic",
  "frequency": "monthly",
  "onUpdate": "continue",
  "onDelete": "complete",
  "description": "Monthly Premium Club subscription",
  "length": 12,
  "customFieldNames": [
    "yourCustomField"
  ],
  "setupOrder": {
    "amount": 4999,
    "description": "Initial setup fee for Premium Club subscription",
    "breakdown": {
      "subtotal": 4347,
      "taxes": [
        {
          "name": "Sales Tax",
          "rate": 5
        }
      ]
    }
  },
  "recurringOrder": {
    "amount": 4999,
    "description": "Monthly Premium Club subscription",
    "breakdown": {
      "subtotal": 4347,
      "taxes": [
        {
          "name": "Sales Tax",
          "rate": 5
        }
      ]
    }
  }
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
    'Idempotency-Key' => '8e03978e-40d5-43e8-bc93-6894a57f9324',
  ],
]);

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

**`Payment Plan`**

```csharp
using RestSharp;

var client = new RestClient("https://api.payroc.com/v1/processing-terminals/1234001/payment-plans");
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  \"paymentPlanId\": \"PlanRef8765\",\n  \"name\": \"Premium Club\",\n  \"currency\": \"USD\",\n  \"type\": \"automatic\",\n  \"frequency\": \"monthly\",\n  \"onUpdate\": \"continue\",\n  \"onDelete\": \"complete\",\n  \"description\": \"Monthly Premium Club subscription\",\n  \"length\": 12,\n  \"customFieldNames\": [\n    \"yourCustomField\"\n  ],\n  \"setupOrder\": {\n    \"amount\": 4999,\n    \"description\": \"Initial setup fee for Premium Club subscription\",\n    \"breakdown\": {\n      \"subtotal\": 4347,\n      \"taxes\": [\n        {\n          \"name\": \"Sales Tax\",\n          \"rate\": 5\n        }\n      ]\n    }\n  },\n  \"recurringOrder\": {\n    \"amount\": 4999,\n    \"description\": \"Monthly Premium Club subscription\",\n    \"breakdown\": {\n      \"subtotal\": 4347,\n      \"taxes\": [\n        {\n          \"name\": \"Sales Tax\",\n          \"rate\": 5\n        }\n      ]\n    }\n  }\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

**`Payment Plan`**

```swift
import Foundation

let headers = [
  "Idempotency-Key": "8e03978e-40d5-43e8-bc93-6894a57f9324",
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = [
  "paymentPlanId": "PlanRef8765",
  "name": "Premium Club",
  "currency": "USD",
  "type": "automatic",
  "frequency": "monthly",
  "onUpdate": "continue",
  "onDelete": "complete",
  "description": "Monthly Premium Club subscription",
  "length": 12,
  "customFieldNames": ["yourCustomField"],
  "setupOrder": [
    "amount": 4999,
    "description": "Initial setup fee for Premium Club subscription",
    "breakdown": [
      "subtotal": 4347,
      "taxes": [
        [
          "name": "Sales Tax",
          "rate": 5
        ]
      ]
    ]
  ],
  "recurringOrder": [
    "amount": 4999,
    "description": "Monthly Premium Club subscription",
    "breakdown": [
      "subtotal": 4347,
      "taxes": [
        [
          "name": "Sales Tax",
          "rate": 5
        ]
      ]
    ]
  ]
] as [String : Any]

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

let request = NSMutableURLRequest(url: NSURL(string: "https://api.payroc.com/v1/processing-terminals/1234001/payment-plans")! 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 create the payment plan and return a response. The response contains the following fields:

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

[Response body schema for `POST /processing-terminals/{processingTerminalId}/payment-plans`](/api/create-payment-plan)

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

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

```json
{
  "paymentPlanId": "PlanRef8765",
  "name": "Premium Club",
  "currency": "USD",
  "type": "automatic",
  "frequency": "monthly",
  "onUpdate": "continue",
  "onDelete": "complete",
  "processingTerminalId": "1234001",
  "description": "Monthly Premium Club subscription",
  "length": 12,
  "customFieldNames": [
    "yourCustomField"
  ],
  "setupOrder": {
    "amount": 4999,
    "description": "Initial setup fee for Premium Club subscription",
    "breakdown": {
      "subtotal": 4347,
      "taxes": [
        {
          "name": "Sales Tax",
          "rate": 5
        }
      ]
    }
  },
  "recurringOrder": {
    "amount": 4999,
    "description": "Monthly Premium Club subscription",
    "breakdown": {
      "subtotal": 4347,
      "taxes": [
        {
          "name": "Sales Tax",
          "rate": 5
        }
      ]
    }
  }
}
```

<a id="step-2-create-a-secure-token"></a>
## Step 2. Create a secure token

\<Warning\> **Important:** If you have already set up your integration to create a secure token, go to [Step 3. Create a subscription](#step-3-create-a-subscription). \</Warning\>

Before you can assign a customer to a payment plan, save their payment details and create a secure token.

To save the customer’s payment details, send a POST request to our Secure Tokens endpoint.

| Environment | URL |
| --- | --- |
| Test | https://api.uat.payroc.com/v1/processing-terminals/\{processingTerminalId\}/secure-tokens |
| Production | https://api.payroc.com/v1/processing-terminals/\{processingTerminalId\}/secure-tokens |

\<Note\> **Note:** We assign the secure token to the terminal that sent the request. Depending on the merchant’s account settings, other terminals within the merchant’s account can also use the secure token. \</Note\>

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

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

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

[Request body schema for `POST /processing-terminals/{processingTerminalId}/secure-tokens`](/api/create-secure-token)

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

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

POST https://api.payroc.com/v1/processing-terminals/\{processingTerminalId\}/secure-tokens

```curl
curl -X POST https://api.payroc.com/v1/processing-terminals/1234001/secure-tokens \
     -H "Idempotency-Key: 8e03978e-40d5-43e8-bc93-6894a57f9324" \
     -H "Authorization: Bearer <token>" \
     -H "Content-Type: application/json" \
     -d '{
  "source": {
    "type": "card",
    "cardDetails": {
      "entryMethod": "keyed",
      "keyedData": {
        "dataFormat": "plainText",
        "cardNumber": "4539858876047062",
        "cvv": "234",
        "expiryDate": "1230"
      },
      "cardholderName": "Sarah Hazel Hopper"
    }
  },
  "operator": "Jane",
  "mitAgreement": "unscheduled",
  "customer": {
    "firstName": "Sarah",
    "lastName": "Hopper",
    "dateOfBirth": "1990-07-15",
    "referenceNumber": "Customer-12",
    "billingAddress": {
      "address1": "1 Example Ave.",
      "city": "Chicago",
      "state": "Illinois",
      "country": "US",
      "postalCode": "60056",
      "address2": "Example Address Line 2",
      "address3": "Example Address Line 3"
    },
    "shippingAddress": {
      "recipientName": "Sarah Hopper",
      "address": {
        "address1": "1 Example Ave.",
        "city": "Chicago",
        "state": "Illinois",
        "country": "US",
        "postalCode": "60056",
        "address2": "Example Address Line 2",
        "address3": "Example Address Line 3"
      }
    },
    "contactMethods": [
      {
        "type": "email",
        "value": "sarah.hopper@example.com"
      }
    ],
    "notificationLanguage": "en"
  },
  "ipAddress": {
    "type": "ipv4",
    "value": "104.18.24.203"
  },
  "customFields": [
    {
      "name": "yourCustomField",
      "value": "abc123"
    }
  ]
}'
```

**`Secure Token`**

```python
import requests

url = "https://api.payroc.com/v1/processing-terminals/1234001/secure-tokens"

payload = {
    "source": {
        "type": "card",
        "cardDetails": {
            "entryMethod": "keyed",
            "keyedData": {
                "dataFormat": "plainText",
                "cardNumber": "4539858876047062",
                "cvv": "234",
                "expiryDate": "1230"
            },
            "cardholderName": "Sarah Hazel Hopper"
        }
    },
    "operator": "Jane",
    "mitAgreement": "unscheduled",
    "customer": {
        "firstName": "Sarah",
        "lastName": "Hopper",
        "dateOfBirth": "1990-07-15",
        "referenceNumber": "Customer-12",
        "billingAddress": {
            "address1": "1 Example Ave.",
            "city": "Chicago",
            "state": "Illinois",
            "country": "US",
            "postalCode": "60056",
            "address2": "Example Address Line 2",
            "address3": "Example Address Line 3"
        },
        "shippingAddress": {
            "recipientName": "Sarah Hopper",
            "address": {
                "address1": "1 Example Ave.",
                "city": "Chicago",
                "state": "Illinois",
                "country": "US",
                "postalCode": "60056",
                "address2": "Example Address Line 2",
                "address3": "Example Address Line 3"
            }
        },
        "contactMethods": [
            {
                "type": "email",
                "value": "sarah.hopper@example.com"
            }
        ],
        "notificationLanguage": "en"
    },
    "ipAddress": {
        "type": "ipv4",
        "value": "104.18.24.203"
    },
    "customFields": [
        {
            "name": "yourCustomField",
            "value": "abc123"
        }
    ]
}
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())
```

**`Secure Token`**

```javascript
const url = 'https://api.payroc.com/v1/processing-terminals/1234001/secure-tokens';
const options = {
  method: 'POST',
  headers: {
    'Idempotency-Key': '8e03978e-40d5-43e8-bc93-6894a57f9324',
    Authorization: 'Bearer <token>',
    'Content-Type': 'application/json'
  },
  body: '{"source":{"type":"card","cardDetails":{"entryMethod":"keyed","keyedData":{"dataFormat":"plainText","cardNumber":"4539858876047062","cvv":"234","expiryDate":"1230"},"cardholderName":"Sarah Hazel Hopper"}},"operator":"Jane","mitAgreement":"unscheduled","customer":{"firstName":"Sarah","lastName":"Hopper","dateOfBirth":"1990-07-15","referenceNumber":"Customer-12","billingAddress":{"address1":"1 Example Ave.","city":"Chicago","state":"Illinois","country":"US","postalCode":"60056","address2":"Example Address Line 2","address3":"Example Address Line 3"},"shippingAddress":{"recipientName":"Sarah Hopper","address":{"address1":"1 Example Ave.","city":"Chicago","state":"Illinois","country":"US","postalCode":"60056","address2":"Example Address Line 2","address3":"Example Address Line 3"}},"contactMethods":[{"type":"email","value":"sarah.hopper@example.com"}],"notificationLanguage":"en"},"ipAddress":{"type":"ipv4","value":"104.18.24.203"},"customFields":[{"name":"yourCustomField","value":"abc123"}]}'
};

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

**`Secure Token`**

```go
package main

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

func main() {

	url := "https://api.payroc.com/v1/processing-terminals/1234001/secure-tokens"

	payload := strings.NewReader("{\n  \"source\": {\n    \"type\": \"card\",\n    \"cardDetails\": {\n      \"entryMethod\": \"keyed\",\n      \"keyedData\": {\n        \"dataFormat\": \"plainText\",\n        \"cardNumber\": \"4539858876047062\",\n        \"cvv\": \"234\",\n        \"expiryDate\": \"1230\"\n      },\n      \"cardholderName\": \"Sarah Hazel Hopper\"\n    }\n  },\n  \"operator\": \"Jane\",\n  \"mitAgreement\": \"unscheduled\",\n  \"customer\": {\n    \"firstName\": \"Sarah\",\n    \"lastName\": \"Hopper\",\n    \"dateOfBirth\": \"1990-07-15\",\n    \"referenceNumber\": \"Customer-12\",\n    \"billingAddress\": {\n      \"address1\": \"1 Example Ave.\",\n      \"city\": \"Chicago\",\n      \"state\": \"Illinois\",\n      \"country\": \"US\",\n      \"postalCode\": \"60056\",\n      \"address2\": \"Example Address Line 2\",\n      \"address3\": \"Example Address Line 3\"\n    },\n    \"shippingAddress\": {\n      \"recipientName\": \"Sarah Hopper\",\n      \"address\": {\n        \"address1\": \"1 Example Ave.\",\n        \"city\": \"Chicago\",\n        \"state\": \"Illinois\",\n        \"country\": \"US\",\n        \"postalCode\": \"60056\",\n        \"address2\": \"Example Address Line 2\",\n        \"address3\": \"Example Address Line 3\"\n      }\n    },\n    \"contactMethods\": [\n      {\n        \"type\": \"email\",\n        \"value\": \"sarah.hopper@example.com\"\n      }\n    ],\n    \"notificationLanguage\": \"en\"\n  },\n  \"ipAddress\": {\n    \"type\": \"ipv4\",\n    \"value\": \"104.18.24.203\"\n  },\n  \"customFields\": [\n    {\n      \"name\": \"yourCustomField\",\n      \"value\": \"abc123\"\n    }\n  ]\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))

}
```

**`Secure Token`**

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

url = URI("https://api.payroc.com/v1/processing-terminals/1234001/secure-tokens")

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  \"source\": {\n    \"type\": \"card\",\n    \"cardDetails\": {\n      \"entryMethod\": \"keyed\",\n      \"keyedData\": {\n        \"dataFormat\": \"plainText\",\n        \"cardNumber\": \"4539858876047062\",\n        \"cvv\": \"234\",\n        \"expiryDate\": \"1230\"\n      },\n      \"cardholderName\": \"Sarah Hazel Hopper\"\n    }\n  },\n  \"operator\": \"Jane\",\n  \"mitAgreement\": \"unscheduled\",\n  \"customer\": {\n    \"firstName\": \"Sarah\",\n    \"lastName\": \"Hopper\",\n    \"dateOfBirth\": \"1990-07-15\",\n    \"referenceNumber\": \"Customer-12\",\n    \"billingAddress\": {\n      \"address1\": \"1 Example Ave.\",\n      \"city\": \"Chicago\",\n      \"state\": \"Illinois\",\n      \"country\": \"US\",\n      \"postalCode\": \"60056\",\n      \"address2\": \"Example Address Line 2\",\n      \"address3\": \"Example Address Line 3\"\n    },\n    \"shippingAddress\": {\n      \"recipientName\": \"Sarah Hopper\",\n      \"address\": {\n        \"address1\": \"1 Example Ave.\",\n        \"city\": \"Chicago\",\n        \"state\": \"Illinois\",\n        \"country\": \"US\",\n        \"postalCode\": \"60056\",\n        \"address2\": \"Example Address Line 2\",\n        \"address3\": \"Example Address Line 3\"\n      }\n    },\n    \"contactMethods\": [\n      {\n        \"type\": \"email\",\n        \"value\": \"sarah.hopper@example.com\"\n      }\n    ],\n    \"notificationLanguage\": \"en\"\n  },\n  \"ipAddress\": {\n    \"type\": \"ipv4\",\n    \"value\": \"104.18.24.203\"\n  },\n  \"customFields\": [\n    {\n      \"name\": \"yourCustomField\",\n      \"value\": \"abc123\"\n    }\n  ]\n}"

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

**`Secure Token`**

```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/secure-tokens")
  .header("Idempotency-Key", "8e03978e-40d5-43e8-bc93-6894a57f9324")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"source\": {\n    \"type\": \"card\",\n    \"cardDetails\": {\n      \"entryMethod\": \"keyed\",\n      \"keyedData\": {\n        \"dataFormat\": \"plainText\",\n        \"cardNumber\": \"4539858876047062\",\n        \"cvv\": \"234\",\n        \"expiryDate\": \"1230\"\n      },\n      \"cardholderName\": \"Sarah Hazel Hopper\"\n    }\n  },\n  \"operator\": \"Jane\",\n  \"mitAgreement\": \"unscheduled\",\n  \"customer\": {\n    \"firstName\": \"Sarah\",\n    \"lastName\": \"Hopper\",\n    \"dateOfBirth\": \"1990-07-15\",\n    \"referenceNumber\": \"Customer-12\",\n    \"billingAddress\": {\n      \"address1\": \"1 Example Ave.\",\n      \"city\": \"Chicago\",\n      \"state\": \"Illinois\",\n      \"country\": \"US\",\n      \"postalCode\": \"60056\",\n      \"address2\": \"Example Address Line 2\",\n      \"address3\": \"Example Address Line 3\"\n    },\n    \"shippingAddress\": {\n      \"recipientName\": \"Sarah Hopper\",\n      \"address\": {\n        \"address1\": \"1 Example Ave.\",\n        \"city\": \"Chicago\",\n        \"state\": \"Illinois\",\n        \"country\": \"US\",\n        \"postalCode\": \"60056\",\n        \"address2\": \"Example Address Line 2\",\n        \"address3\": \"Example Address Line 3\"\n      }\n    },\n    \"contactMethods\": [\n      {\n        \"type\": \"email\",\n        \"value\": \"sarah.hopper@example.com\"\n      }\n    ],\n    \"notificationLanguage\": \"en\"\n  },\n  \"ipAddress\": {\n    \"type\": \"ipv4\",\n    \"value\": \"104.18.24.203\"\n  },\n  \"customFields\": [\n    {\n      \"name\": \"yourCustomField\",\n      \"value\": \"abc123\"\n    }\n  ]\n}")
  .asString();
```

**`Secure Token`**

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

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.payroc.com/v1/processing-terminals/1234001/secure-tokens', [
  'body' => '{
  "source": {
    "type": "card",
    "cardDetails": {
      "entryMethod": "keyed",
      "keyedData": {
        "dataFormat": "plainText",
        "cardNumber": "4539858876047062",
        "cvv": "234",
        "expiryDate": "1230"
      },
      "cardholderName": "Sarah Hazel Hopper"
    }
  },
  "operator": "Jane",
  "mitAgreement": "unscheduled",
  "customer": {
    "firstName": "Sarah",
    "lastName": "Hopper",
    "dateOfBirth": "1990-07-15",
    "referenceNumber": "Customer-12",
    "billingAddress": {
      "address1": "1 Example Ave.",
      "city": "Chicago",
      "state": "Illinois",
      "country": "US",
      "postalCode": "60056",
      "address2": "Example Address Line 2",
      "address3": "Example Address Line 3"
    },
    "shippingAddress": {
      "recipientName": "Sarah Hopper",
      "address": {
        "address1": "1 Example Ave.",
        "city": "Chicago",
        "state": "Illinois",
        "country": "US",
        "postalCode": "60056",
        "address2": "Example Address Line 2",
        "address3": "Example Address Line 3"
      }
    },
    "contactMethods": [
      {
        "type": "email",
        "value": "sarah.hopper@example.com"
      }
    ],
    "notificationLanguage": "en"
  },
  "ipAddress": {
    "type": "ipv4",
    "value": "104.18.24.203"
  },
  "customFields": [
    {
      "name": "yourCustomField",
      "value": "abc123"
    }
  ]
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
    'Idempotency-Key' => '8e03978e-40d5-43e8-bc93-6894a57f9324',
  ],
]);

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

**`Secure Token`**

```csharp
using RestSharp;

var client = new RestClient("https://api.payroc.com/v1/processing-terminals/1234001/secure-tokens");
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  \"source\": {\n    \"type\": \"card\",\n    \"cardDetails\": {\n      \"entryMethod\": \"keyed\",\n      \"keyedData\": {\n        \"dataFormat\": \"plainText\",\n        \"cardNumber\": \"4539858876047062\",\n        \"cvv\": \"234\",\n        \"expiryDate\": \"1230\"\n      },\n      \"cardholderName\": \"Sarah Hazel Hopper\"\n    }\n  },\n  \"operator\": \"Jane\",\n  \"mitAgreement\": \"unscheduled\",\n  \"customer\": {\n    \"firstName\": \"Sarah\",\n    \"lastName\": \"Hopper\",\n    \"dateOfBirth\": \"1990-07-15\",\n    \"referenceNumber\": \"Customer-12\",\n    \"billingAddress\": {\n      \"address1\": \"1 Example Ave.\",\n      \"city\": \"Chicago\",\n      \"state\": \"Illinois\",\n      \"country\": \"US\",\n      \"postalCode\": \"60056\",\n      \"address2\": \"Example Address Line 2\",\n      \"address3\": \"Example Address Line 3\"\n    },\n    \"shippingAddress\": {\n      \"recipientName\": \"Sarah Hopper\",\n      \"address\": {\n        \"address1\": \"1 Example Ave.\",\n        \"city\": \"Chicago\",\n        \"state\": \"Illinois\",\n        \"country\": \"US\",\n        \"postalCode\": \"60056\",\n        \"address2\": \"Example Address Line 2\",\n        \"address3\": \"Example Address Line 3\"\n      }\n    },\n    \"contactMethods\": [\n      {\n        \"type\": \"email\",\n        \"value\": \"sarah.hopper@example.com\"\n      }\n    ],\n    \"notificationLanguage\": \"en\"\n  },\n  \"ipAddress\": {\n    \"type\": \"ipv4\",\n    \"value\": \"104.18.24.203\"\n  },\n  \"customFields\": [\n    {\n      \"name\": \"yourCustomField\",\n      \"value\": \"abc123\"\n    }\n  ]\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

**`Secure Token`**

```swift
import Foundation

let headers = [
  "Idempotency-Key": "8e03978e-40d5-43e8-bc93-6894a57f9324",
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = [
  "source": [
    "type": "card",
    "cardDetails": [
      "entryMethod": "keyed",
      "keyedData": [
        "dataFormat": "plainText",
        "cardNumber": "4539858876047062",
        "cvv": "234",
        "expiryDate": "1230"
      ],
      "cardholderName": "Sarah Hazel Hopper"
    ]
  ],
  "operator": "Jane",
  "mitAgreement": "unscheduled",
  "customer": [
    "firstName": "Sarah",
    "lastName": "Hopper",
    "dateOfBirth": "1990-07-15",
    "referenceNumber": "Customer-12",
    "billingAddress": [
      "address1": "1 Example Ave.",
      "city": "Chicago",
      "state": "Illinois",
      "country": "US",
      "postalCode": "60056",
      "address2": "Example Address Line 2",
      "address3": "Example Address Line 3"
    ],
    "shippingAddress": [
      "recipientName": "Sarah Hopper",
      "address": [
        "address1": "1 Example Ave.",
        "city": "Chicago",
        "state": "Illinois",
        "country": "US",
        "postalCode": "60056",
        "address2": "Example Address Line 2",
        "address3": "Example Address Line 3"
      ]
    ],
    "contactMethods": [
      [
        "type": "email",
        "value": "sarah.hopper@example.com"
      ]
    ],
    "notificationLanguage": "en"
  ],
  "ipAddress": [
    "type": "ipv4",
    "value": "104.18.24.203"
  ],
  "customFields": [
    [
      "name": "yourCustomField",
      "value": "abc123"
    ]
  ]
] as [String : Any]

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

let request = NSMutableURLRequest(url: NSURL(string: "https://api.payroc.com/v1/processing-terminals/1234001/secure-tokens")! 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-1"></a>
### Response fields

If your request is successful, we store the customer’s payment details and return a response. The response contains the following fields:

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

[Response body schema for `POST /processing-terminals/{processingTerminalId}/secure-tokens`](/api/create-secure-token)

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

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

```json
{
  "secureTokenId": "MREF_abc1de23-f4a5-6789-bcd0-12e345678901fa",
  "processingTerminalId": "1234001",
  "source": {
    "type": "card",
    "cardNumber": "453985******7062",
    "cardholderName": "Sarah Hazel Hopper",
    "expiryDate": "1230"
  },
  "token": "296753123456",
  "status": "notValidated",
  "mitAgreement": "unscheduled",
  "customer": {
    "firstName": "Sarah",
    "lastName": "Hopper",
    "dateOfBirth": "1990-07-15",
    "referenceNumber": "Customer-12",
    "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"
      }
    },
    "contactMethods": [
      {
        "type": "email",
        "value": "sarah.hopper@example.com"
      }
    ],
    "notificationLanguage": "en"
  },
  "customFields": [
    {
      "name": "yourCustomField",
      "value": "abc123"
    }
  ]
}
```

<a id="step-3-create-a-subscription"></a>
## Step 3. Create a subscription

To assign a customer to a payment plan, send a POST request to our Subscriptions endpoint. You can also use this request to personalize the payment plan for each customer, for example, provide a discount on each payment or add a one-off setup fee.

| Environment | URL |
| --- | --- |
| Test | https://api.uat.payroc.com/v1/processing-terminals/\{processingTerminalId\}/subscriptions |
| Production | https://api.payroc.com/v1/processing-terminals/\{processingTerminalId\}/subscriptions |

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

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

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

[Request body schema for `POST /processing-terminals/{processingTerminalId}/subscriptions`](/api/create-subscription)

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

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

POST https://api.payroc.com/v1/processing-terminals/\{processingTerminalId\}/subscriptions

```curl
curl -X POST https://api.payroc.com/v1/processing-terminals/1234001/subscriptions \
     -H "Idempotency-Key: 8e03978e-40d5-43e8-bc93-6894a57f9324" \
     -H "Authorization: Bearer <token>" \
     -H "Content-Type: application/json" \
     -d '{
  "subscriptionId": "SubRef7654",
  "paymentPlanId": "PlanRef8765",
  "paymentMethod": {
    "type": "secureToken",
    "token": "296753123456"
  },
  "startDate": "2024-07-02",
  "name": "Premium Club",
  "description": "Premium Club subscription",
  "setupOrder": {
    "orderId": "OrderRef6543",
    "amount": 4999,
    "description": "Initial setup fee for Premium Club subscription"
  },
  "recurringOrder": {
    "amount": 4999,
    "description": "Monthly Premium Club subscription",
    "breakdown": {
      "subtotal": 4347,
      "taxes": [
        {
          "rate": 5,
          "name": "Sales Tax",
          "type": "rate"
        }
      ]
    }
  },
  "endDate": "2025-07-01",
  "length": 12,
  "pauseCollectionFor": 0
}'
```

**`Subscription with surcharge`**

```python
import requests

url = "https://api.payroc.com/v1/processing-terminals/1234001/subscriptions"

payload = {
    "subscriptionId": "SubRef7654",
    "paymentPlanId": "PlanRef8765",
    "paymentMethod": {
        "type": "secureToken",
        "token": "296753123456"
    },
    "startDate": "2024-07-02",
    "name": "Premium Club",
    "description": "Premium Club subscription",
    "setupOrder": {
        "orderId": "OrderRef6543",
        "amount": 4999,
        "description": "Initial setup fee for Premium Club subscription"
    },
    "recurringOrder": {
        "amount": 4999,
        "description": "Monthly Premium Club subscription",
        "breakdown": {
            "subtotal": 4347,
            "taxes": [
                {
                    "rate": 5,
                    "name": "Sales Tax",
                    "type": "rate"
                }
            ]
        }
    },
    "endDate": "2025-07-01",
    "length": 12,
    "pauseCollectionFor": 0
}
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())
```

**`Subscription with surcharge`**

```javascript
const url = 'https://api.payroc.com/v1/processing-terminals/1234001/subscriptions';
const options = {
  method: 'POST',
  headers: {
    'Idempotency-Key': '8e03978e-40d5-43e8-bc93-6894a57f9324',
    Authorization: 'Bearer <token>',
    'Content-Type': 'application/json'
  },
  body: '{"subscriptionId":"SubRef7654","paymentPlanId":"PlanRef8765","paymentMethod":{"type":"secureToken","token":"296753123456"},"startDate":"2024-07-02","name":"Premium Club","description":"Premium Club subscription","setupOrder":{"orderId":"OrderRef6543","amount":4999,"description":"Initial setup fee for Premium Club subscription"},"recurringOrder":{"amount":4999,"description":"Monthly Premium Club subscription","breakdown":{"subtotal":4347,"taxes":[{"rate":5,"name":"Sales Tax","type":"rate"}]}},"endDate":"2025-07-01","length":12,"pauseCollectionFor":0}'
};

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

**`Subscription with surcharge`**

```go
package main

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

func main() {

	url := "https://api.payroc.com/v1/processing-terminals/1234001/subscriptions"

	payload := strings.NewReader("{\n  \"subscriptionId\": \"SubRef7654\",\n  \"paymentPlanId\": \"PlanRef8765\",\n  \"paymentMethod\": {\n    \"type\": \"secureToken\",\n    \"token\": \"296753123456\"\n  },\n  \"startDate\": \"2024-07-02\",\n  \"name\": \"Premium Club\",\n  \"description\": \"Premium Club subscription\",\n  \"setupOrder\": {\n    \"orderId\": \"OrderRef6543\",\n    \"amount\": 4999,\n    \"description\": \"Initial setup fee for Premium Club subscription\"\n  },\n  \"recurringOrder\": {\n    \"amount\": 4999,\n    \"description\": \"Monthly Premium Club subscription\",\n    \"breakdown\": {\n      \"subtotal\": 4347,\n      \"taxes\": [\n        {\n          \"rate\": 5,\n          \"name\": \"Sales Tax\",\n          \"type\": \"rate\"\n        }\n      ]\n    }\n  },\n  \"endDate\": \"2025-07-01\",\n  \"length\": 12,\n  \"pauseCollectionFor\": 0\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))

}
```

**`Subscription with surcharge`**

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

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

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  \"subscriptionId\": \"SubRef7654\",\n  \"paymentPlanId\": \"PlanRef8765\",\n  \"paymentMethod\": {\n    \"type\": \"secureToken\",\n    \"token\": \"296753123456\"\n  },\n  \"startDate\": \"2024-07-02\",\n  \"name\": \"Premium Club\",\n  \"description\": \"Premium Club subscription\",\n  \"setupOrder\": {\n    \"orderId\": \"OrderRef6543\",\n    \"amount\": 4999,\n    \"description\": \"Initial setup fee for Premium Club subscription\"\n  },\n  \"recurringOrder\": {\n    \"amount\": 4999,\n    \"description\": \"Monthly Premium Club subscription\",\n    \"breakdown\": {\n      \"subtotal\": 4347,\n      \"taxes\": [\n        {\n          \"rate\": 5,\n          \"name\": \"Sales Tax\",\n          \"type\": \"rate\"\n        }\n      ]\n    }\n  },\n  \"endDate\": \"2025-07-01\",\n  \"length\": 12,\n  \"pauseCollectionFor\": 0\n}"

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

**`Subscription with surcharge`**

```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/subscriptions")
  .header("Idempotency-Key", "8e03978e-40d5-43e8-bc93-6894a57f9324")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"subscriptionId\": \"SubRef7654\",\n  \"paymentPlanId\": \"PlanRef8765\",\n  \"paymentMethod\": {\n    \"type\": \"secureToken\",\n    \"token\": \"296753123456\"\n  },\n  \"startDate\": \"2024-07-02\",\n  \"name\": \"Premium Club\",\n  \"description\": \"Premium Club subscription\",\n  \"setupOrder\": {\n    \"orderId\": \"OrderRef6543\",\n    \"amount\": 4999,\n    \"description\": \"Initial setup fee for Premium Club subscription\"\n  },\n  \"recurringOrder\": {\n    \"amount\": 4999,\n    \"description\": \"Monthly Premium Club subscription\",\n    \"breakdown\": {\n      \"subtotal\": 4347,\n      \"taxes\": [\n        {\n          \"rate\": 5,\n          \"name\": \"Sales Tax\",\n          \"type\": \"rate\"\n        }\n      ]\n    }\n  },\n  \"endDate\": \"2025-07-01\",\n  \"length\": 12,\n  \"pauseCollectionFor\": 0\n}")
  .asString();
```

**`Subscription with surcharge`**

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

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.payroc.com/v1/processing-terminals/1234001/subscriptions', [
  'body' => '{
  "subscriptionId": "SubRef7654",
  "paymentPlanId": "PlanRef8765",
  "paymentMethod": {
    "type": "secureToken",
    "token": "296753123456"
  },
  "startDate": "2024-07-02",
  "name": "Premium Club",
  "description": "Premium Club subscription",
  "setupOrder": {
    "orderId": "OrderRef6543",
    "amount": 4999,
    "description": "Initial setup fee for Premium Club subscription"
  },
  "recurringOrder": {
    "amount": 4999,
    "description": "Monthly Premium Club subscription",
    "breakdown": {
      "subtotal": 4347,
      "taxes": [
        {
          "rate": 5,
          "name": "Sales Tax",
          "type": "rate"
        }
      ]
    }
  },
  "endDate": "2025-07-01",
  "length": 12,
  "pauseCollectionFor": 0
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
    'Idempotency-Key' => '8e03978e-40d5-43e8-bc93-6894a57f9324',
  ],
]);

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

**`Subscription with surcharge`**

```csharp
using RestSharp;

var client = new RestClient("https://api.payroc.com/v1/processing-terminals/1234001/subscriptions");
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  \"subscriptionId\": \"SubRef7654\",\n  \"paymentPlanId\": \"PlanRef8765\",\n  \"paymentMethod\": {\n    \"type\": \"secureToken\",\n    \"token\": \"296753123456\"\n  },\n  \"startDate\": \"2024-07-02\",\n  \"name\": \"Premium Club\",\n  \"description\": \"Premium Club subscription\",\n  \"setupOrder\": {\n    \"orderId\": \"OrderRef6543\",\n    \"amount\": 4999,\n    \"description\": \"Initial setup fee for Premium Club subscription\"\n  },\n  \"recurringOrder\": {\n    \"amount\": 4999,\n    \"description\": \"Monthly Premium Club subscription\",\n    \"breakdown\": {\n      \"subtotal\": 4347,\n      \"taxes\": [\n        {\n          \"rate\": 5,\n          \"name\": \"Sales Tax\",\n          \"type\": \"rate\"\n        }\n      ]\n    }\n  },\n  \"endDate\": \"2025-07-01\",\n  \"length\": 12,\n  \"pauseCollectionFor\": 0\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

**`Subscription with surcharge`**

```swift
import Foundation

let headers = [
  "Idempotency-Key": "8e03978e-40d5-43e8-bc93-6894a57f9324",
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = [
  "subscriptionId": "SubRef7654",
  "paymentPlanId": "PlanRef8765",
  "paymentMethod": [
    "type": "secureToken",
    "token": "296753123456"
  ],
  "startDate": "2024-07-02",
  "name": "Premium Club",
  "description": "Premium Club subscription",
  "setupOrder": [
    "orderId": "OrderRef6543",
    "amount": 4999,
    "description": "Initial setup fee for Premium Club subscription"
  ],
  "recurringOrder": [
    "amount": 4999,
    "description": "Monthly Premium Club subscription",
    "breakdown": [
      "subtotal": 4347,
      "taxes": [
        [
          "rate": 5,
          "name": "Sales Tax",
          "type": "rate"
        ]
      ]
    ]
  ],
  "endDate": "2025-07-01",
  "length": 12,
  "pauseCollectionFor": 0
] as [String : Any]

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

let request = NSMutableURLRequest(url: NSURL(string: "https://api.payroc.com/v1/processing-terminals/1234001/subscriptions")! 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 assign the customer to the payment plan and return a response. The response contains the following fields:

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

[Response body schema for `POST /processing-terminals/{processingTerminalId}/subscriptions`](/api/create-subscription)

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

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

```json
{
  "subscriptionId": "SubRef7654",
  "processingTerminalId": "1234001",
  "paymentPlan": {
    "paymentPlanId": "PlanRef8765",
    "name": "Monthly Premium Club subscription",
    "link": {
      "rel": "self",
      "method": "GET",
      "href": "https://api.payroc.com/v1/processing-terminals/1234001/payment-plans/PlanRef8765"
    }
  },
  "secureToken": {
    "secureTokenId": "MREF_abc1de23-f4a5-6789-bcd0-12e345678901fa",
    "customerName": "Sarah Hazel 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"
    }
  },
  "name": "Premium Club",
  "currency": "USD",
  "currentState": {
    "status": "active",
    "paidInvoices": 0,
    "nextDueDate": "2024-08-02",
    "outstandingInvoices": 3
  },
  "startDate": "2024-07-02",
  "type": "automatic",
  "frequency": "monthly",
  "description": "Premium Club subscription",
  "setupOrder": {
    "orderId": "OrderRef6543",
    "amount": 4999,
    "description": "Initial setup fee for Premium Club subscription",
    "breakdown": {
      "subtotal": 4347,
      "surcharge": {
        "amount": 217,
        "percentage": 5
      },
      "taxes": [
        {
          "name": "Sales Tax",
          "rate": 5
        }
      ]
    }
  },
  "recurringOrder": {
    "amount": 4999,
    "description": "Premium Club subscription",
    "breakdown": {
      "subtotal": 4347,
      "surcharge": {
        "amount": 217,
        "percentage": 5
      },
      "taxes": [
        {
          "name": "Sales Tax",
          "rate": 5
        }
      ]
    }
  },
  "endDate": "2025-07-01",
  "length": 12,
  "pauseCollectionFor": 0,
  "customFields": [
    {
      "name": "yourCustomField",
      "value": "abc123"
    }
  ]
}
```

<a id="step-4-optional-manually-collect-a-payment"></a>
## Step 4. (Optional) Manually collect a payment

The merchant can choose to let our gateway automatically collect payments, or the merchant can manually collect payments. If the merchant chooses to manually collect payments, you must send a request every time the merchant wants to collect a payment from the customer.

To manually collect a payment from a customer, send a POST request to the Subscriptions endpoint.

| Environment | URL |
| --- | --- |
| Test | https://api.uat.payroc.com/v1/processing-terminals/\{processingTerminalId\}/subscriptions/\{subscriptionId\}/pay |
| Production | https://api.payroc.com/v1/processing-terminals/\{processingTerminalId\}/subscriptions/\{subscriptionId\}/pay |

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

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

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

[Request body schema for `POST /processing-terminals/{processingTerminalId}/subscriptions/{subscriptionId}/pay`](/api/pay-subscription)

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

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

POST https://api.payroc.com/v1/processing-terminals/\{processingTerminalId\}/subscriptions/\{subscriptionId\}/pay

```curl
curl -X POST https://api.payroc.com/v1/processing-terminals/1234001/subscriptions/SubRef7654/pay \
     -H "Idempotency-Key: 8e03978e-40d5-43e8-bc93-6894a57f9324" \
     -H "Authorization: Bearer <token>" \
     -H "Content-Type: application/json" \
     -d '{
  "order": {
    "orderId": "OrderRef6543",
    "amount": 4999,
    "description": "Monthly Premium Club subscription"
  },
  "operator": "Jane"
}'
```

**`Subscription manual payment`**

```python
import requests

url = "https://api.payroc.com/v1/processing-terminals/1234001/subscriptions/SubRef7654/pay"

payload = {
    "order": {
        "orderId": "OrderRef6543",
        "amount": 4999,
        "description": "Monthly Premium Club subscription"
    },
    "operator": "Jane"
}
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())
```

**`Subscription manual payment`**

```javascript
const url = 'https://api.payroc.com/v1/processing-terminals/1234001/subscriptions/SubRef7654/pay';
const options = {
  method: 'POST',
  headers: {
    'Idempotency-Key': '8e03978e-40d5-43e8-bc93-6894a57f9324',
    Authorization: 'Bearer <token>',
    'Content-Type': 'application/json'
  },
  body: '{"order":{"orderId":"OrderRef6543","amount":4999,"description":"Monthly Premium Club subscription"},"operator":"Jane"}'
};

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

**`Subscription manual payment`**

```go
package main

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

func main() {

	url := "https://api.payroc.com/v1/processing-terminals/1234001/subscriptions/SubRef7654/pay"

	payload := strings.NewReader("{\n  \"order\": {\n    \"orderId\": \"OrderRef6543\",\n    \"amount\": 4999,\n    \"description\": \"Monthly Premium Club subscription\"\n  },\n  \"operator\": \"Jane\"\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))

}
```

**`Subscription manual payment`**

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

url = URI("https://api.payroc.com/v1/processing-terminals/1234001/subscriptions/SubRef7654/pay")

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  \"order\": {\n    \"orderId\": \"OrderRef6543\",\n    \"amount\": 4999,\n    \"description\": \"Monthly Premium Club subscription\"\n  },\n  \"operator\": \"Jane\"\n}"

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

**`Subscription manual payment`**

```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/subscriptions/SubRef7654/pay")
  .header("Idempotency-Key", "8e03978e-40d5-43e8-bc93-6894a57f9324")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"order\": {\n    \"orderId\": \"OrderRef6543\",\n    \"amount\": 4999,\n    \"description\": \"Monthly Premium Club subscription\"\n  },\n  \"operator\": \"Jane\"\n}")
  .asString();
```

**`Subscription manual payment`**

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

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.payroc.com/v1/processing-terminals/1234001/subscriptions/SubRef7654/pay', [
  'body' => '{
  "order": {
    "orderId": "OrderRef6543",
    "amount": 4999,
    "description": "Monthly Premium Club subscription"
  },
  "operator": "Jane"
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
    'Idempotency-Key' => '8e03978e-40d5-43e8-bc93-6894a57f9324',
  ],
]);

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

**`Subscription manual payment`**

```csharp
using RestSharp;

var client = new RestClient("https://api.payroc.com/v1/processing-terminals/1234001/subscriptions/SubRef7654/pay");
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  \"order\": {\n    \"orderId\": \"OrderRef6543\",\n    \"amount\": 4999,\n    \"description\": \"Monthly Premium Club subscription\"\n  },\n  \"operator\": \"Jane\"\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

**`Subscription manual payment`**

```swift
import Foundation

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

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

let request = NSMutableURLRequest(url: NSURL(string: "https://api.payroc.com/v1/processing-terminals/1234001/subscriptions/SubRef7654/pay")! 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-3"></a>
### Response fields

If your request is successful, we take the payment from the customer and return a response. The response contains the following fields:

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

[Response body schema for `POST /processing-terminals/{processingTerminalId}/subscriptions/{subscriptionId}/pay`](/api/pay-subscription)

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

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

```json
{
  "subscriptionId": "SubRef7654",
  "processingTerminalId": "1234001",
  "payment": {
    "paymentId": "M2MJOG6O2Y",
    "dateTime": "2024-07-02T15:30:00Z",
    "currency": "USD",
    "amount": 4999,
    "status": "ready",
    "responseCode": "A",
    "responseMessage": "Transaction approved",
    "link": {
      "rel": "self",
      "method": "GET",
      "href": "https://api.payroc.com/v1/bank-transfer-payments/M2MJOG6O2Y"
    }
  },
  "secureToken": {
    "secureTokenId": "MREF_abc1de23-f4a5-6789-bcd0-12e345678901fa",
    "customerName": "Sarah Hazel 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"
    }
  },
  "currentState": {
    "status": "active",
    "paidInvoices": 1,
    "nextDueDate": "2024-08-02",
    "outstandingInvoices": 2
  },
  "customFields": [
    {
      "name": "yourCustomField",
      "value": "abc123"
    }
  ]
}
```

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

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

<a id="create-a-payment-plan"></a>
### Create a payment plan

Send a POST request to the following endpoint:

POST https://api.uat.payroc.com/v1/processing-terminals/\{processingTerminalId\}/payment-plans

**Example response**

```json
{
	"paymentPlanId": "PaymentPlanTest",
	"processingTerminalId": "3204001",
	"name": "Davi Crisostomo",
	"description": "Payment Plan creation",
	"currency": "USD",
	"setupOrder": {
		"amount": 11000,
		"description": "Setup Amount"
	},
	"length": 24,
	"type": "manual",
	"frequency": "monthly",
	"onUpdate": "update",
	"onDelete": "complete"
}

```

<a id="create-a-secure-token"></a>
### Create a secure token

Send a POST request to the following endpoint:

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

**Example response**

```json
{
	"secureTokenId": "MREF_1a93f3a6-9029-419f-9e87-3e2db6f0ae85uA",
	"processingTerminalId": "3204001",
	"source": {
		"type": "card",
		"cardholderName": "",
		"cardNumber": "444433******1111",
		"expiryDate": "1226"
	},
	"token": "2967538502417872",
	"status": "cvv_validated"
}

```

<a id="create-a-subscription-for-a-payment-plan"></a>
### Create a subscription for a payment plan

Send a POST request to the following endpoint:

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

**Example response**

```json
{
	"subscriptionId": "SubTest",
	"processingTerminalId": "3204001",
	"paymentPlan": {
		"paymentPlanId": "PaymentPlanTest",
		"name": "Davi Crisostomo",
		"link": {
			"rel": "self",
			"method": "GET",
			"href": "https://api.uat.payroc.com/v1/processing-terminals/3204001/payment-plans/PaymentPlanTest"
		}
	},
	"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"
		}
	},
	"name": "Davi Crisostomo",
	"description": "Create Subscription from ICC payment",
	"currency": "USD",
	"setupOrder": {
		"orderId": "TheOrderID",
		"amount": 11000,
		"description": "Description of SETUPORDER"
	},
	"recurringOrder": {
		"amount": 11000,
		"description": "RECURRING Order price"
	},
	"currentState": {
		"status": "active",
		"nextDueDate": "2023-08-02",
		"paidInvoices": 0,
		"outstandingInvoices": 122
	},
	"startDate": "2023-08-02",
	"endDate": "2025-12-02",
	"length": 24,
	"type": "automatic",
	"frequency": "weekly",
	"pauseCollectionFor": 0
}

```

<a id="manually-pay-a-subscription"></a>
### Manually pay a subscription

Send a POST request to the following endpoint:

POST [https://api.uat.payroc.com/v1/processing-terminals/\{processingTerminalId\}/subscriptions/\{subscriptionId\}/pay](https://api.uat.payroc.com/v1/processing-terminals/%7BprocessingTerminalId%7D/subscriptions/%7BsubscriptionId%7D/pay)

**Example response**

```json
{
	"paymentId": "KOHM1D3EZH",
	"processingTerminalId": "3204001",
	"operator": "Davi Crisostomo",
	"order": {
		"orderId": "UniqueValueForOrderID",
		"dateTime": "2023-06-20T20:25:57.641+01:00",
		"description": "Subscription Payment - Manual",
		"amount": 11000,
		"currency": "USD"
	},
	"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"
		}
	},
	"transactionResult": {
		"type": "sale",
		"status": "ready",
		"approvalCode": "OK24225",
		"authorizedAmount": 11000,
		"currency": "USD",
		"responseCode": "A",
		"responseMessage": "OK24225",
		"cardSchemeReferenceId": "nkMX2G7ZqPavgbYiYacQ"
	}
}
```
