{"_id":"5b2d60111235f100031773e7","category":"5b2d60111235f1000317734a","user":"5564a0073a61a72f0067cb22","project":"555fbba928249c1900618a82","parentDoc":null,"version":"5b2d60111235f10003177402","updates":["5595c7e9f44370190028891c","562aa244ed4bea0d00c11d8b","56bb4e10dabd992100b674f7","56f19a949791b22d0077ba0f"],"next":{"pages":[],"description":""},"createdAt":"2015-06-10T22:06:37.745Z","link_external":false,"link_url":"","githubsync":"","sync_unique":"","hidden":false,"api":{"results":{"codes":[{"language":"json","status":200,"name":"","code":"{}"},{"code":"{}","language":"json","status":400,"name":""}]},"settings":"","auth":"required","params":[],"url":""},"isReference":false,"order":0,"body":"[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"API Authentication (HTTP Basic)\"\n}\n[/block]\nRecurly uses HTTP Basic Authentication—your [Private API key](https://app.recurly.com/go/developer/api_access) is securely encrypted by the SSL channel.\n\nIf you are testing the API calls via the command line with cURL, try:\n\n```\ncurl -H 'Accept: application/xml' \\\n     -H 'X-Api-Version: 2.13' \\\n     -H 'Content-Type: application/xml; charset=utf-8' \\\n     -u '[apikey]' \\\n    https://[subdomain].recurly.com/v2/accounts\n```\n\nReplace `[apikey]` and `[subdomain]` with the appropriate values for your site.\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Calculating your own authorization header\"\n}\n[/block]\nMost programming languages encode the authorization header automatically. With HTTP Basic Authentication, the `Authorization` header is a string containing a Base-64 encoded username and password. In the case of Recurly’s API, you need only specify the username as your API key. If your library requires a password, set it to an empty string.\n\n```\n\"Authorization\": \"Basic \" + base64_encode(API Key)\n```\n\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Additional Request Headers\"\n}\n[/block]\n## Accept Header\nRecurly API v2 returns results as XML. Your requests should always include the header requesting the results as XML:\n\n```\nAccept: application/xml\n```\n\n## Content-Type Header\nWhen sending data to Recurly in a POST or PUT request, your request must specify the content type of your request:\n\n```\nContent-Type: application/xml; charset=utf-8\n```\n\n## X-Api-Version Header\nWhen sending data to Recurly, your request should specify the API version you're attempting to interact with:\n```\nX-Api-Version: 2.13\n```\nYou learn more about the different versions in the [API Versioning](doc:versioning) section.\n[block:callout]\n{\n  \"type\": \"info\",\n  \"title\": \"Acceptable API versions\",\n  \"body\": \"Recurly supports the following API versions: **[2.2](https://dev.recurly.com/v2.2/docs)**, **[2.3](https://dev.recurly.com/v2.3/docs)**, **[2.4](https://dev.recurly.com/v2.4/docs)**, **[2.5](https://dev.recurly.com/v2.5/docs)**, **[2.6](https://dev.recurly.com/v2.6/docs)**, **[2.7](https://dev.recurly.com/v2.7/docs)**, **[2.8](https://dev.recurly.com/v2.8/docs)**, **[2.9](https://dev.recurly.com/v2.9/docs)**, **[2.10](https://dev.recurly.com/v2.10/docs)**, **[2.11](https://dev.recurly.com/v2.11/docs)**, **[2.12](https://dev.recurly.com/v2.12/docs)**, **[2.13](https://dev.recurly.com/v2.13/docs)**\"\n}\n[/block]\n\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Public API Key\"\n}\n[/block]\nRecurly uses two types of API keys: public and private. The Public API key is used by [Recurly.js](doc:recurlyjs) to identify its requests as belonging to your Recurly site. This key can be safely included in Javascript code.\n\nRecurly provides each site with one Public Key. The Public API Key can be regenerated on the [API Credentials](https://app.recurly.com/go/developer/api_access) page.\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Private API Keys\"\n}\n[/block]\n\n[block:callout]\n{\n  \"type\": \"danger\",\n  \"title\": \"Treat your Private API Keys like passwords!\",\n  \"body\": \"The API key allows access to your site's data. Do not include it in Javascript code exposed to browsers.\"\n}\n[/block]\nRecurly supports the use of multiple Private API keys, which can be used to integrate third party services using unique, controlled credentials.\n\n## Limits & Pricing\nMerchants on the Core or grandfathered Recurly plans or merchants in sandbox mode will be granted 5 private API keys. Merchants on Recurly’s Professional plan will be granted 10 private API keys.\n\n## Default Key\nYour default private API key should be used to integrate Recurly with your backend systems. There will be at least one key active at all times.\n\n## Additional Keys\nAdditional private API keys should be used to connect your Recurly data to additional sources, like analytics software, accounting packages, or email tools. Recurly recommends clearly labeling the name of each key to identify the associated vendor.\n\n## Regenerating Private API Keys\nYour API key can be regenerated by clicking on the Regenerate button on the [API credentials](https://app.recurly.com/go/developer/api_access) page. When you generate a private API key, you have two options:\n\n1. Block the old key immediately. This is primarily recommended when the security of a key has been compromised.\n2. Allow the old key access for 12 hours. This is primarily used when updating systems and a smooth transition between keys is needed.\n\n*If a private API key is changed, an email alert will be sent to your Recurly Site Technical Contact.*\n\n## Read-Only Keys\nWhen creating a private key, you will have the option to set the key to “read-only”. This means the API key may make GET requests but cannot not PUT, POST or DELETE requests.","excerpt":"","slug":"getting-started","type":"basic","title":"Authentication","__v":0,"childrenPages":[]}

Authentication


API Authentication (HTTP Basic)

Recurly uses HTTP Basic Authentication—your Private API key is securely encrypted by the SSL channel.

If you are testing the API calls via the command line with cURL, try:

curl -H 'Accept: application/xml' \
     -H 'X-Api-Version: 2.13' \
     -H 'Content-Type: application/xml; charset=utf-8' \
     -u '[apikey]' \
    https://[subdomain].recurly.com/v2/accounts

Replace [apikey] and [subdomain] with the appropriate values for your site.

Calculating your own authorization header

Most programming languages encode the authorization header automatically. With HTTP Basic Authentication, the Authorization header is a string containing a Base-64 encoded username and password. In the case of Recurly’s API, you need only specify the username as your API key. If your library requires a password, set it to an empty string.

"Authorization": "Basic " + base64_encode(API Key)

Additional Request Headers

Accept Header

Recurly API v2 returns results as XML. Your requests should always include the header requesting the results as XML:

Accept: application/xml

Content-Type Header

When sending data to Recurly in a POST or PUT request, your request must specify the content type of your request:

Content-Type: application/xml; charset=utf-8

X-Api-Version Header

When sending data to Recurly, your request should specify the API version you're attempting to interact with:

X-Api-Version: 2.13

You learn more about the different versions in the API Versioning section.

Acceptable API versions

Recurly supports the following API versions: 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9, 2.10, 2.11, 2.12, 2.13

Public API Key

Recurly uses two types of API keys: public and private. The Public API key is used by Recurly.js to identify its requests as belonging to your Recurly site. This key can be safely included in Javascript code.

Recurly provides each site with one Public Key. The Public API Key can be regenerated on the API Credentials page.

Private API Keys

Treat your Private API Keys like passwords!

The API key allows access to your site's data. Do not include it in Javascript code exposed to browsers.

Recurly supports the use of multiple Private API keys, which can be used to integrate third party services using unique, controlled credentials.

Limits & Pricing

Merchants on the Core or grandfathered Recurly plans or merchants in sandbox mode will be granted 5 private API keys. Merchants on Recurly’s Professional plan will be granted 10 private API keys.

Default Key

Your default private API key should be used to integrate Recurly with your backend systems. There will be at least one key active at all times.

Additional Keys

Additional private API keys should be used to connect your Recurly data to additional sources, like analytics software, accounting packages, or email tools. Recurly recommends clearly labeling the name of each key to identify the associated vendor.

Regenerating Private API Keys

Your API key can be regenerated by clicking on the Regenerate button on the API credentials page. When you generate a private API key, you have two options:

  1. Block the old key immediately. This is primarily recommended when the security of a key has been compromised.
  2. Allow the old key access for 12 hours. This is primarily used when updating systems and a smooth transition between keys is needed.

If a private API key is changed, an email alert will be sent to your Recurly Site Technical Contact.

Read-Only Keys

When creating a private key, you will have the option to set the key to “read-only”. This means the API key may make GET requests but cannot not PUT, POST or DELETE requests.

View all 124 endpoints
{"_id":"5b2d60111235f100031773e8","category":"5b2d60111235f1000317734a","user":"559d85d26b21311700fb0b7b","parentDoc":null,"project":"555fbba928249c1900618a82","version":"5b2d60111235f10003177402","updates":[],"next":{"pages":[],"description":""},"createdAt":"2016-07-18T22:26:12.882Z","link_external":false,"link_url":"","githubsync":"","sync_unique":"","hidden":false,"api":{"results":{"codes":[{"name":"","code":"{}","language":"json","status":200},{"name":"","code":"{}","language":"json","status":400}]},"settings":"","auth":"required","params":[],"url":""},"isReference":false,"order":1,"body":"Recurly strives to provide developers with stable APIs to integrate against while still being able to provide new and expanded functionality. To balance these two goals we provide different API versions and only add new features to the latest version of the API. This allows you to choose the best time to update your integration and take advantage of new features.\n\nRecurly offers the following API versions:  [2.13](https://dev.recurly.com/v2.13/docs), [2.12](https://dev.recurly.com/v2.12/docs), \n[2.11](https://dev.recurly.com/v2.11/docs), [2.10](https://dev.recurly.com/v2.10/docs), [2.9](https://dev.recurly.com/v2.9/docs), [2.8](https://dev.recurly.com/v2.8/docs),  [2.7](https://dev.recurly.com/v2.7/docs), [2.6](https://dev.recurly.com/v2.6/docs), [2.5](https://dev.recurly.com/v2.5/docs), [2.4](https://dev.recurly.com/v2.4/docs), [2.3](https://dev.recurly.com/v2.3/docs), [2.2](https://dev.recurly.com/v2.2/docs).\n\n## Requesting A Version\n\nWhen making requests to Recurly, your request should specify the desired API version using the `X-Api-Version` header:\n```\nX-Api-Version: 2.13\n```\nFor backwards compatibility, if no version is specified the default is 2.0.\n\n## Deprecation\n\nTo signal that an API version is deprecated and will be removed in the future, Recurly will respond the following headers:\n```\nRecurly-Deprecated: TRUE\nRecurly-Sunset-Date: 2018-06-01T00:00:00+00:00\n```\nThe sunset date is an ISO 8601 date time when the version will no longer be accessible.\n\nYour integration should check for those headers so you can make updates in a timely fashion.\n\n## Changes in v2.13\n\nRequest and Response changes:\n\n- Changed Plan POST request/response\n  - Added `<auto_renew>` Boolean default: true\n- Changed Plan PUT request/response\n  - Added `<auto_renew>` Boolean default: true\n- Changed Subscription POST request/response\n  - Added `<auto_renew>` Boolean default: true\n  - Added `<renewal_billing_cycles>` Integer default: nil\n- Changed Subscription response\n  - Added `<current_term_started_at>` Datetime default: nil\n  - Added `<current_term_ends_at>` Datetime default: nil\n- Changed Shipping Address request/response XML:\n  - Accept new attributes `first_name` and `last_name` for shipping addresses\n  - Return new attributes `first_name` and `last_name` in address xml for addresses created using new attributes\n- Changed Purchases POST response\n  - Return new attributes `name`,  `first_name` and `last_name` in line item address xml\n- Changed Account, Subscription, and Purchase request/response\n  - Added optional `<custom_fields>` list to account and subscription xml entities\n    - path: `<account><custom_fields><custom_field><name></name><value></value></custom_field></custom_fields></account>`\n    - path: `<subscription><custom_fields><custom_field><name></name><value></value></custom_field></custom_fields></subscription>`\n    - path: `<subscription><account><custom_fields><custom_field><name></name><value></value></custom_field></custom_fields></subscription>`\n    - path: `<purchase><subscriptions><subscription><custom_fields><custom_field><name></name><value></value></custom_field></custom_fields></subscription></subscriptions></purchase>`\n    - path: `<purchase><account><custom_fields><custom_field><name></name><value></value></custom_field></custom_fields></account></purchase>`\n    - description: Allows fetch, create, update, and delete of Custom Fields on Accounts and Subscriptions.\n      Custom Field must be configured through the Admin UI before accessing them through the API.\n      To create or update a custom field, add the name & new value to the `<custom_fields></custom_fields>` list. The field will be created if it does not exist yet.\n      To delete a custom field, add the name & an empty value to the list:\n        `<custom_field><name>[name_of_existing_field]</name><value></value></custom_field>`\n      Existing values which are not present in the request will not be modified.\n- Change Subscription PUT request/response\n  - Added `<auto_renew>` and `<renewal_billing_cycles>`\n- Change Plans PUT request/response\n  - Updates to `<plan_interval_unit>` will be blocked\n  - Updates to `<plan_interval_length>` will be blocked\n\nA complete list of changes for all versions is available on the [API Release Notes](https://dev.recurly.com/page/api-release-notes) page.","excerpt":"","slug":"versioning","type":"basic","title":"API Versioning","__v":0,"childrenPages":[]}

API Versioning


Recurly strives to provide developers with stable APIs to integrate against while still being able to provide new and expanded functionality. To balance these two goals we provide different API versions and only add new features to the latest version of the API. This allows you to choose the best time to update your integration and take advantage of new features.

Recurly offers the following API versions: 2.13, 2.12,
2.11, 2.10, 2.9, 2.8, 2.7, 2.6, 2.5, 2.4, 2.3, 2.2.

Requesting A Version

When making requests to Recurly, your request should specify the desired API version using the X-Api-Version header:

X-Api-Version: 2.13

For backwards compatibility, if no version is specified the default is 2.0.

Deprecation

To signal that an API version is deprecated and will be removed in the future, Recurly will respond the following headers:

Recurly-Deprecated: TRUE
Recurly-Sunset-Date: 2018-06-01T00:00:00+00:00

The sunset date is an ISO 8601 date time when the version will no longer be accessible.

Your integration should check for those headers so you can make updates in a timely fashion.

Changes in v2.13

Request and Response changes:

  • Changed Plan POST request/response
    • Added <auto_renew> Boolean default: true
  • Changed Plan PUT request/response
    • Added <auto_renew> Boolean default: true
  • Changed Subscription POST request/response
    • Added <auto_renew> Boolean default: true
    • Added <renewal_billing_cycles> Integer default: nil
  • Changed Subscription response
    • Added <current_term_started_at> Datetime default: nil
    • Added <current_term_ends_at> Datetime default: nil
  • Changed Shipping Address request/response XML:
    • Accept new attributes first_name and last_name for shipping addresses
    • Return new attributes first_name and last_name in address xml for addresses created using new attributes
  • Changed Purchases POST response
    • Return new attributes name, first_name and last_name in line item address xml
  • Changed Account, Subscription, and Purchase request/response
    • Added optional <custom_fields> list to account and subscription xml entities
      • path: <account><custom_fields><custom_field><name></name><value></value></custom_field></custom_fields></account>
      • path: <subscription><custom_fields><custom_field><name></name><value></value></custom_field></custom_fields></subscription>
      • path: <subscription><account><custom_fields><custom_field><name></name><value></value></custom_field></custom_fields></subscription>
      • path: <purchase><subscriptions><subscription><custom_fields><custom_field><name></name><value></value></custom_field></custom_fields></subscription></subscriptions></purchase>
      • path: <purchase><account><custom_fields><custom_field><name></name><value></value></custom_field></custom_fields></account></purchase>
      • description: Allows fetch, create, update, and delete of Custom Fields on Accounts and Subscriptions.
        Custom Field must be configured through the Admin UI before accessing them through the API.
        To create or update a custom field, add the name & new value to the <custom_fields></custom_fields> list. The field will be created if it does not exist yet.
        To delete a custom field, add the name & an empty value to the list:
        <custom_field><name>[name_of_existing_field]</name><value></value></custom_field>
        Existing values which are not present in the request will not be modified.
  • Change Subscription PUT request/response
    • Added <auto_renew> and <renewal_billing_cycles>
  • Change Plans PUT request/response
    • Updates to <plan_interval_unit> will be blocked
    • Updates to <plan_interval_length> will be blocked

A complete list of changes for all versions is available on the API Release Notes page.

{"_id":"5b2d60111235f100031773e9","category":"5b2d60111235f1000317734a","parentDoc":null,"project":"555fbba928249c1900618a82","user":"55648cf93b87582b003ab8b1","version":"5b2d60111235f10003177402","updates":[],"next":{"pages":[],"description":""},"createdAt":"2015-06-15T22:48:39.567Z","link_external":false,"link_url":"","githubsync":"","sync_unique":"","hidden":false,"api":{"results":{"codes":[{"name":"","code":"{}","language":"json","status":200},{"language":"json","status":400,"name":"","code":"{}"}]},"settings":"","auth":"required","params":[],"url":""},"isReference":false,"order":2,"body":"[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Next Link\"\n}\n[/block]\nThe amount of records returns within a single API request defaults to 50. It may be changed to a maximum of 200 using a `per_page` query parameter, e.g. to return 200 accounts at a time:\n\n```\nhttps://your-subdomain.recurly.com/v2/accounts?per_page=200\n```\n\nWhen there are more records remaining than fit in the current response, the `Link` header is specified with the URI to the next page of results.\n\n```\nStatus: 200 OK \nLink: <https://your-subdomain.recurly.com/v2/accounts?cursor=1972702718353176814%3A1465932489>; rel=\"next\" \nETag: \"a4b0568a2278bc591ceb64b31547eb78\" \n```\n\nThe `cursor` parameter is a time-based pointer indicating where to resume the results. By using a cursor instead of page numbers, the API avoids returning duplicate records in the case where additional resources are added between pagination requests.\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Sorting and Filtering\"\n}\n[/block]\n Many endpoints support these advanced pagination parameters:\n\n* `sort` : String: The attribute that will be used to order records: `created_at`, `updated_at`. Defaults to `created_at`.\n* `order` : String : The order in which products will be returned: `asc` for ascending order, `desc` for descending order. Defaults to `desc`.\n* `begin_time` : Datetime : Operates on the attribute specified by the sort parameter. Filters records to only include those with datetimes greater than or equal to the supplied datetime. Accepts an ISO 8601 date or date and time.\n* `end_time` : Datetime : Operates on the attribute specified by the sort parameter. Filters records to only include those with datetimes less than or equal to the supplied datetime. Accepts an ISO 8601 date or date and time.\n\nReview the parameters on each endpoint for more details.\n[block:callout]\n{\n  \"type\": \"info\",\n  \"body\": \"An account that was updated on `2016-01-19` and then again on `2016-03-23` would not be returned in a request for `sort=updated_at&end_time=2016-03-01`.\",\n  \"title\": \"Updated at really means last updated at\"\n}\n[/block]\n\n[block:api-header]\n{\n  \"title\": \"Counting Records\"\n}\n[/block]\nStarting with API version 2.6, you must explicitly make a `HEAD` request to get the server count. Endpoints that return a list of resources will respond to this request and include a header indicating the total number of records available. They will not contain the xml body. The server count is specified with the `X-Records` header. E.g., for an endpoint with 14 records:\n\n```\nX-Records: 14\n```\n\nYou can pass filtering parameters (described above) to narrow down the resources you wish to count. Consider the example of counting all `collected` invoices in `2016`. You can send a `HEAD` request to this endpoint then parse the count from the X-Records response header:\n\n```\nhttps://your-subdomain.recurly.com/v2/invoices?begin_time=2016-01-01T00:00:00&end_time=2017-01-01T00:00:00&state=collected\n```\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Examples\"\n}\n[/block]\nThis will return accounts that were created on or before 2016-01-01 0:00 UTC in descending order of creation date:\n```\nhttps://your-subdomain.recurly.com/v2/accounts?sort=created_at&order=desc&end_time=2016-01-01\n```\n\nThis will return accounts that were last updated on or after 2016-07-01 10:30:01 Mountain Daylight Time in ascending order of updated date:\n\n```\nhttps://your-subdomain.recurly.com/v2/accounts?sort=updated_at&order=asc&begin_time=2016-07-01T10:30:01-06:00\n```\n[block:callout]\n{\n  \"type\": \"warning\",\n  \"body\": \"It's important to be aware that when paging through records sorted by their `updated_at` value, the order will change if they are modified:\\n* In ascending order, changes to records in previous pages will cause them to move back the end of the list, meaning you may see them multiple times. This can be avoided by using the time the pagination starts as the `end_time`.\\n* In descending order, changes to records in later pages will cause them to move up to the beginning of the list, meaning you would miss results.\",\n  \"title\": \"Beware of changes to records when sorting by updated_at\"\n}\n[/block]\n\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"<?php\\n// When accessing a sub resource with a many-to-one relation\\n// to the parent model, the attribute returns a Recurly_Stub.\\n// For example, take Account -> Invoices\\n\\n$account = Recurly_Account::get('my_account_code');\\n\\n// Calling ->invoices returns a Stub which allows lazily loading the list\\n$invoices = $account->invoices;\\n\\nprint $invoices;\\n// => <Recurly_Stub[invoices] href=https://api.recurly.com/v2/accounts/my_account_code/invoices>\\n\\n/**\\n * Prior to 2.5.0 calling ->get() would only return the first page\\n * of results. With 2.5.0 and later, all results will be returned.\\n */\\nforeach ($invoices->get() as $inv) {\\n   print $inv->invoice_number . \\\"\\\\n\\\";\\n}\\n\\n/**\\n * Creating a List object directly will also allow you to iterate\\n * through all pages\\n */\\n$invoices = Recurly_InvoiceList::getForAccount('my_account_code');\\n\\n// Prints all invoices on the account\\nforeach ($invoices as $inv) {\\n   print $inv->invoice_number . \\\"\\\\n\\\";\\n}\\n\",\n      \"language\": \"php\",\n      \"gist\": \"44632c432dce4f56a0fa\"\n    },\n    {\n      \"code\": \"# Pagination in the ruby client is done using\\n# the Recurly::Pager class.\\n\\n# You can also create a Pager directly from any resource\\nRecurly::Invoice.paginate.class\\n#=> Recurly::Resource::Pager\\n\\n# paginate optionally takes the sorting and filtering params\\n# if you want to specify them\\nopts = {\\n  begin_time: DateTime.new(2016,1,1),\\n  end_time: DateTime.new(2017,1,1),\\n  state: :collected,\\n  per_page: 10\\n}\\n\\n# find_each will fetch the pages for you\\n# until there are none left. It presents\\n# all the invoices on the server as a single enumerable\\nRecurly::Invoice.paginate(opts).find_each do |invoice|\\n  puts invoice.invoice_number\\nend\\n\\n# You can also use #find_each directly on the resource\\nRecurly::Invoice.find_each do |invoice|\\n  puts invoice.invoice_number\\nend\\n\\n# When accessing a sub resource with a many-to-one relation \\n# to the parent model, the attribute returns a Recurly::Resource::Pager. \\n# For example, take Account -> Invoices\\naccount = Recurly::Account.find('my_account_code')\\n\\naccount.invoices.class\\n#=> Recurly::Resource::Pager\\n\\n# Pager#each can be used to iterate through the only the given page\\naccount.invoices.each do |invoice|\\n  puts invoice.invoice_number\\nend\\n\\n# The default page size is 50 items, if you wish to page through more\\n# you can use Pager#find_each, find_each continues to fetch pages until\\n# there are none left\\naccount.invoices.find_each do |invoice|\\n  puts invoice.invoice_number\\nend\",\n      \"language\": \"ruby\"\n    },\n    {\n      \"code\": \"# When accessing a sub resource with a many-to-one relation\\n# to the parent model, the attribute returns a `relatiator` function.\\n# When called it returns a recurly.resource.Page.\\n# For example, take Account -> Invoices\\n\\naccount = recurly.Account.get('tester')\\n\\nprint account.invoices\\n# => <function relatitator at 0x1023628c0>\\n\\nprint account.invoices().__class__\\n# => <class 'recurly.resource.Page'>\\n\\n# To page through every invoice on the account\\nfor invoice in account.invoices():\\n    print invoice.invoice_number\\n\\n# You can also call the all() method on\\n# a resource to page through every resource\\n# on your site. For instance, to page through\\n# every invoice:\\nfor invoice in recurly.Invoice.all():\\n    print invoice.invoice_number\",\n      \"language\": \"python\",\n      \"name\": null\n    },\n    {\n      \"code\": \"using System.Linq;\\n\\nvar accounts = Accounts.List();\\nwhile (accounts.Any())\\n{\\n    foreach (var account in accounts)\\n        Console.WriteLine(account);\\n    accounts = accounts.Next;\\n}\",\n      \"language\": \"csharp\"\n    }\n  ]\n}\n[/block]\n\n[block:callout]\n{\n  \"type\": \"warning\",\n  \"body\": \"The PHP `Recurly_Pager` class sets up an iterator across all the relevant records. It does not provide pagination functionality by default.\",\n  \"title\": \"PHP Pagination\"\n}\n[/block]","excerpt":"","slug":"pagination","type":"basic","title":"Pagination","__v":0,"childrenPages":[]}

Pagination


Next Link

The amount of records returns within a single API request defaults to 50. It may be changed to a maximum of 200 using a per_page query parameter, e.g. to return 200 accounts at a time:

https://your-subdomain.recurly.com/v2/accounts?per_page=200

When there are more records remaining than fit in the current response, the Link header is specified with the URI to the next page of results.

Status: 200 OK 
Link: <https://your-subdomain.recurly.com/v2/accounts?cursor=1972702718353176814%3A1465932489>; rel="next" 
ETag: "a4b0568a2278bc591ceb64b31547eb78"

The cursor parameter is a time-based pointer indicating where to resume the results. By using a cursor instead of page numbers, the API avoids returning duplicate records in the case where additional resources are added between pagination requests.

Sorting and Filtering

Many endpoints support these advanced pagination parameters:

  • sort : String: The attribute that will be used to order records: created_at, updated_at. Defaults to created_at.
  • order : String : The order in which products will be returned: asc for ascending order, desc for descending order. Defaults to desc.
  • begin_time : Datetime : Operates on the attribute specified by the sort parameter. Filters records to only include those with datetimes greater than or equal to the supplied datetime. Accepts an ISO 8601 date or date and time.
  • end_time : Datetime : Operates on the attribute specified by the sort parameter. Filters records to only include those with datetimes less than or equal to the supplied datetime. Accepts an ISO 8601 date or date and time.

Review the parameters on each endpoint for more details.

Updated at really means last updated at

An account that was updated on 2016-01-19 and then again on 2016-03-23 would not be returned in a request for sort=updated_at&end_time=2016-03-01.

Counting Records

Starting with API version 2.6, you must explicitly make a HEAD request to get the server count. Endpoints that return a list of resources will respond to this request and include a header indicating the total number of records available. They will not contain the xml body. The server count is specified with the X-Records header. E.g., for an endpoint with 14 records:

X-Records: 14

You can pass filtering parameters (described above) to narrow down the resources you wish to count. Consider the example of counting all collected invoices in 2016. You can send a HEAD request to this endpoint then parse the count from the X-Records response header:

https://your-subdomain.recurly.com/v2/invoices?begin_time=2016-01-01T00:00:00&end_time=2017-01-01T00:00:00&state=collected

Examples

This will return accounts that were created on or before 2016-01-01 0:00 UTC in descending order of creation date:

https://your-subdomain.recurly.com/v2/accounts?sort=created_at&order=desc&end_time=2016-01-01

This will return accounts that were last updated on or after 2016-07-01 10:30:01 Mountain Daylight Time in ascending order of updated date:

https://your-subdomain.recurly.com/v2/accounts?sort=updated_at&order=asc&begin_time=2016-07-01T10:30:01-06:00

Beware of changes to records when sorting by updated_at

It's important to be aware that when paging through records sorted by their updated_at value, the order will change if they are modified:

  • In ascending order, changes to records in previous pages will cause them to move back the end of the list, meaning you may see them multiple times. This can be avoided by using the time the pagination starts as the end_time.
  • In descending order, changes to records in later pages will cause them to move up to the beginning of the list, meaning you would miss results.
<?php
// When accessing a sub resource with a many-to-one relation
// to the parent model, the attribute returns a Recurly_Stub.
// For example, take Account -> Invoices

$account = Recurly_Account::get('my_account_code');

// Calling ->invoices returns a Stub which allows lazily loading the list
$invoices = $account->invoices;

print $invoices;
// => <Recurly_Stub[invoices] href=https://api.recurly.com/v2/accounts/my_account_code/invoices>

/**
 * Prior to 2.5.0 calling ->get() would only return the first page
 * of results. With 2.5.0 and later, all results will be returned.
 */
foreach ($invoices->get() as $inv) {
   print $inv->invoice_number . "\n";
}

/**
 * Creating a List object directly will also allow you to iterate
 * through all pages
 */
$invoices = Recurly_InvoiceList::getForAccount('my_account_code');

// Prints all invoices on the account
foreach ($invoices as $inv) {
   print $inv->invoice_number . "\n";
}
# Pagination in the ruby client is done using
# the Recurly::Pager class.

# You can also create a Pager directly from any resource
Recurly::Invoice.paginate.class
#=> Recurly::Resource::Pager

# paginate optionally takes the sorting and filtering params
# if you want to specify them
opts = {
  begin_time: DateTime.new(2016,1,1),
  end_time: DateTime.new(2017,1,1),
  state: :collected,
  per_page: 10
}

# find_each will fetch the pages for you
# until there are none left. It presents
# all the invoices on the server as a single enumerable
Recurly::Invoice.paginate(opts).find_each do |invoice|
  puts invoice.invoice_number
end

# You can also use #find_each directly on the resource
Recurly::Invoice.find_each do |invoice|
  puts invoice.invoice_number
end

# When accessing a sub resource with a many-to-one relation 
# to the parent model, the attribute returns a Recurly::Resource::Pager. 
# For example, take Account -> Invoices
account = Recurly::Account.find('my_account_code')

account.invoices.class
#=> Recurly::Resource::Pager

# Pager#each can be used to iterate through the only the given page
account.invoices.each do |invoice|
  puts invoice.invoice_number
end

# The default page size is 50 items, if you wish to page through more
# you can use Pager#find_each, find_each continues to fetch pages until
# there are none left
account.invoices.find_each do |invoice|
  puts invoice.invoice_number
end
# When accessing a sub resource with a many-to-one relation
# to the parent model, the attribute returns a `relatiator` function.
# When called it returns a recurly.resource.Page.
# For example, take Account -> Invoices

account = recurly.Account.get('tester')

print account.invoices
# => <function relatitator at 0x1023628c0>

print account.invoices().__class__
# => <class 'recurly.resource.Page'>

# To page through every invoice on the account
for invoice in account.invoices():
    print invoice.invoice_number

# You can also call the all() method on
# a resource to page through every resource
# on your site. For instance, to page through
# every invoice:
for invoice in recurly.Invoice.all():
    print invoice.invoice_number
using System.Linq;

var accounts = Accounts.List();
while (accounts.Any())
{
    foreach (var account in accounts)
        Console.WriteLine(account);
    accounts = accounts.Next;
}

PHP Pagination

The PHP Recurly_Pager class sets up an iterator across all the relevant records. It does not provide pagination functionality by default.

{"_id":"5b2d60111235f100031773ea","category":"5b2d60111235f1000317734a","parentDoc":null,"project":"555fbba928249c1900618a82","user":"55648cf93b87582b003ab8b1","version":"5b2d60111235f10003177402","updates":[],"next":{"pages":[],"description":""},"createdAt":"2015-06-15T22:49:59.038Z","link_external":false,"link_url":"","githubsync":"","sync_unique":"","hidden":false,"api":{"results":{"codes":[{"name":"","code":"{}","language":"json","status":200},{"name":"","code":"{}","language":"json","status":400}]},"settings":"","auth":"required","params":[],"url":""},"isReference":false,"order":3,"body":"In order to provide a fast response time to all our customers, we may rate limit excessive requests. By default, new Recurly sites have the following API rate limits:\n\n* Sandbox sites: 400 requests/min. All requests count towards the rate limit.\n* Production sites: 1,000 requests/min. Only GET and HEAD requests count towards the rate limit.\n\nOnce your site moves into production mode, Recurly will only rate limit GET and HEAD requests. New subscriptions, account modifications, and other requests using POST, PUT, or DELETE methods will not count against your rate limit.\n\nThe rate limit is calculated over a sliding 5 minute window. This means a production site could make 4,000 requests within one minute and not hit the rate limit so long as the site made less than 1,000 requests during the prior 4 minutes.\n\nWhen your site reaches its rate limit, your site technical contact will receive an email alerting them of the issue. This email will be sent not more than once every three hours. Our support team will also be notified. Please reach out to Recurly support if you need assistance in resolving this issue.\n\nIf an API request exceeds the rate limit, the API returns a 429 status code indicating `Too Many Requests`. If your business needs a higher limit, please contact support.\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"HTTP Headers\"\n}\n[/block]\nEvery authenticated API request returns headers with your current rate limit information. Your requests’ rate limit headers may look like:\n\n```\nX-RateLimit-Limit: 5000\nX-RateLimit-Remaining: 4999\nX-RateLimit-Reset: 1414622019\n```\n\nThe `X-RateLimit-Limit` is your total request limit during the 5 minute window (e.g. requests/min * 5 min). The `X-RateLimit-Remaining` indicates the number of requests remaining until your requests will be denied. Finally, the `X-RateLimit-Reset` header contains a timestamp for when the current window will completely reset assuming no further API requests are made.","excerpt":"","slug":"rate-limits","type":"basic","title":"Rate Limits","__v":0,"childrenPages":[]}

Rate Limits


In order to provide a fast response time to all our customers, we may rate limit excessive requests. By default, new Recurly sites have the following API rate limits:

  • Sandbox sites: 400 requests/min. All requests count towards the rate limit.
  • Production sites: 1,000 requests/min. Only GET and HEAD requests count towards the rate limit.

Once your site moves into production mode, Recurly will only rate limit GET and HEAD requests. New subscriptions, account modifications, and other requests using POST, PUT, or DELETE methods will not count against your rate limit.

The rate limit is calculated over a sliding 5 minute window. This means a production site could make 4,000 requests within one minute and not hit the rate limit so long as the site made less than 1,000 requests during the prior 4 minutes.

When your site reaches its rate limit, your site technical contact will receive an email alerting them of the issue. This email will be sent not more than once every three hours. Our support team will also be notified. Please reach out to Recurly support if you need assistance in resolving this issue.

If an API request exceeds the rate limit, the API returns a 429 status code indicating Too Many Requests. If your business needs a higher limit, please contact support.

HTTP Headers

Every authenticated API request returns headers with your current rate limit information. Your requests’ rate limit headers may look like:

X-RateLimit-Limit: 5000
X-RateLimit-Remaining: 4999
X-RateLimit-Reset: 1414622019

The X-RateLimit-Limit is your total request limit during the 5 minute window (e.g. requests/min * 5 min). The X-RateLimit-Remaining indicates the number of requests remaining until your requests will be denied. Finally, the X-RateLimit-Reset header contains a timestamp for when the current window will completely reset assuming no further API requests are made.

{"_id":"5b2d60111235f100031773eb","category":"5b2d60111235f1000317734a","parentDoc":null,"user":"5564a0073a61a72f0067cb22","project":"555fbba928249c1900618a82","version":"5b2d60111235f10003177402","updates":["56cd46e949abf10b0036a1e6","59b1583ffff23e00100d1937"],"next":{"pages":[],"description":""},"createdAt":"2015-06-10T22:06:26.211Z","link_external":false,"link_url":"","githubsync":"","sync_unique":"","hidden":false,"api":{"results":{"codes":[{"name":"","code":"{}","language":"json","status":200},{"name":"","code":"{}","language":"json","status":400}]},"settings":"","auth":"required","params":[],"url":""},"isReference":false,"order":4,"body":"## SUCCESSFUL STATUS CODES (2XX)\n`200 OK`\nThe request was successful.\n`201 Created`\nThe resource was successfully created. Confirms a success when creating a new account, credit, subscription, etc.\n`204 No Content`\nThe request was successful and there is no response body.\n\n## CLIENT ERROR STATUS CODES (4XX)\n`400 Bad Request`\nThe request was invalid or could not be understood by the server. Resubmitting the request will likely result in the same error. This commonly occurs when your XML is invalid, e.g. ampersands are not correctly encoded in the text of your request. Please inspect the body of the response for more details regarding the error.\n`401 Unauthorized`\nYour API key is missing or invalid.\n`402 Payment Required`\nYour Recurly account is in production mode but is not in good standing. Please pay any outstanding invoices.\n`403 Forbidden`\nThe login is attempting to perform an action it does not have privileges to access. Verify your login credentials are for the appropriate account.\n`404 Not Found`\nThe resource was not found with the given identifier. The response body will explain which resource was not found.\n`405 Method Not Allowed`\nThe requested method is not valid at the given URL.\n`406 Not Acceptable`\nThe request's Accept header is not set to application/xml.\n`412 Precondition Failed`\nThe request was unsuccessful because a condition was not met. For example, this message may be returned if you attempt to cancel a subscription for an account that has no subscription.\n`422 Unprocessable Entity`\nCould not process a POST or PUT request because the request is invalid. See the response body for more details.\n`429 Too many Requests`\nYou have made too many API requests in the last hour. Future API requests will be ignored until the beginning of the next hour.\n\n## SERVER ERROR STATUS CODES (5XX)\n`500 Internal Server Error`\nThe server encountered an error while processing your request and failed.\n`502 Gateway Error`\nThe load balancer or web server has trouble connecting to the Recurly app. Please try the request again.\n`503 Service Unavailable`\nThe service is temporarily unavailable. Please try the request again.\n\n##FUTURE COMPATIBILITY\nFor future compatibility, please interpret the following status code ranges:\n\n**200–299** as success,\n**400–499** as client request errors,\n**500–599** as server errors\n\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"404 Not Found Responses\"\n}\n[/block]\nWhen a lookup, update, or delete request is requested on an object that does not exist, the server returns `404 Not Found`:\n\n```\nStatus: 404 Not Found\nContent-Type: application/xml; charset=utf-8\n```\n\n```\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<error>\n  <symbol>not_found</symbol>\n  <description>The record could not be located.</description>\n</error>\n```\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"422 Unprocessable Entity Responses\"\n}\n[/block]\nIf the requested create, update, or delete cannot be performed due to validation errors, the server returns a `422 Unprocessable Entity` response with either an array of the validation errors or a single error:\n\n```\nStatus: 422 Unprocessable Entity\nContent-Type: application/xml; charset=utf-8\n```\n\n```\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<errors>\n  <error field=\"model_name.field_name\" symbol=\"not_a_number\" lang=\"en-US\">is not a number</error>\n</errors>\n```\n\n```\n<error>\n  <symbol>simultaneous_request</symbol>\n  <description>\n    A change for subscription 3cf89f0c3fcda0b15c50134f63856d4e is already in progress.\n  </description>\n</error>\n```","excerpt":"Every request includes an HTTP status code with the result. The status code should examined before the response. In most error cases, the response body will contain an errors XML document with more details.","slug":"welcome","type":"basic","title":"HTTP Status Codes","__v":0,"childrenPages":[]}

HTTP Status Codes

Every request includes an HTTP status code with the result. The status code should examined before the response. In most error cases, the response body will contain an errors XML document with more details.

SUCCESSFUL STATUS CODES (2XX)

200 OK
The request was successful.
201 Created
The resource was successfully created. Confirms a success when creating a new account, credit, subscription, etc.
204 No Content
The request was successful and there is no response body.

CLIENT ERROR STATUS CODES (4XX)

400 Bad Request
The request was invalid or could not be understood by the server. Resubmitting the request will likely result in the same error. This commonly occurs when your XML is invalid, e.g. ampersands are not correctly encoded in the text of your request. Please inspect the body of the response for more details regarding the error.
401 Unauthorized
Your API key is missing or invalid.
402 Payment Required
Your Recurly account is in production mode but is not in good standing. Please pay any outstanding invoices.
403 Forbidden
The login is attempting to perform an action it does not have privileges to access. Verify your login credentials are for the appropriate account.
404 Not Found
The resource was not found with the given identifier. The response body will explain which resource was not found.
405 Method Not Allowed
The requested method is not valid at the given URL.
406 Not Acceptable
The request's Accept header is not set to application/xml.
412 Precondition Failed
The request was unsuccessful because a condition was not met. For example, this message may be returned if you attempt to cancel a subscription for an account that has no subscription.
422 Unprocessable Entity
Could not process a POST or PUT request because the request is invalid. See the response body for more details.
429 Too many Requests
You have made too many API requests in the last hour. Future API requests will be ignored until the beginning of the next hour.

SERVER ERROR STATUS CODES (5XX)

500 Internal Server Error
The server encountered an error while processing your request and failed.
502 Gateway Error
The load balancer or web server has trouble connecting to the Recurly app. Please try the request again.
503 Service Unavailable
The service is temporarily unavailable. Please try the request again.

FUTURE COMPATIBILITY

For future compatibility, please interpret the following status code ranges:

200–299 as success,
400–499 as client request errors,
500–599 as server errors

404 Not Found Responses

When a lookup, update, or delete request is requested on an object that does not exist, the server returns 404 Not Found:

Status: 404 Not Found
Content-Type: application/xml; charset=utf-8
<?xml version="1.0" encoding="UTF-8"?>
<error>
  <symbol>not_found</symbol>
  <description>The record could not be located.</description>
</error>

422 Unprocessable Entity Responses

If the requested create, update, or delete cannot be performed due to validation errors, the server returns a 422 Unprocessable Entity response with either an array of the validation errors or a single error:

Status: 422 Unprocessable Entity
Content-Type: application/xml; charset=utf-8
<?xml version="1.0" encoding="UTF-8"?>
<errors>
  <error field="model_name.field_name" symbol="not_a_number" lang="en-US">is not a number</error>
</errors>
<error>
  <symbol>simultaneous_request</symbol>
  <description>
    A change for subscription 3cf89f0c3fcda0b15c50134f63856d4e is already in progress.
  </description>
</error>
{"_id":"5b2d60111235f100031773ec","category":"5b2d60111235f1000317734b","parentDoc":null,"user":"55648cf93b87582b003ab8b1","project":"555fbba928249c1900618a82","version":"5b2d60111235f10003177402","updates":[],"next":{"pages":[],"description":""},"createdAt":"2015-06-26T18:21:30.595Z","link_external":false,"link_url":"","githubsync":"","sync_unique":"","hidden":false,"api":{"results":{"codes":[{"name":"","code":"{}","language":"json","status":200},{"name":"","code":"{}","language":"json","status":400}]},"settings":"","auth":"required","params":[],"url":""},"isReference":false,"order":0,"body":"Recurly has a variety of integrations you should check out!\n\n[Webhooks API](https://dev.recurly.com/page/webhooks)\n\n[Customer Imports](https://dev.recurly.com/page/customer-imports)","excerpt":"","slug":"integrations","type":"basic","title":"Integrations","__v":0,"childrenPages":[]}

Integrations


Recurly has a variety of integrations you should check out!

Webhooks API

Customer Imports

{"_id":"5b2d60111235f100031773a0","category":"5b2d60111235f1000317734c","user":"55648cf93b87582b003ab8b1","project":"555fbba928249c1900618a82","parentDoc":null,"version":"5b2d60111235f10003177402","updates":["55940e20fd29b92300c262bf","55b2bfc0a74a380d00e290a6","55b2c0466862a10d00887adf","55bbb926a8400c2d00873f2a","565f689e413e06170093df6a","58d2b9a19c99c92f00646f8e","5977a75032f043002002f6d9","59b738dba50f750030f42a78","59ccac98e30e6c00300cef7d"],"next":{"pages":[],"description":""},"createdAt":"2015-06-26T18:25:56.960Z","link_external":false,"link_url":"","githubsync":"","sync_unique":"","hidden":false,"api":{"results":{"codes":[{"name":"","code":"{}","language":"json","status":200},{"code":"{}","language":"json","status":400,"name":""}]},"settings":"","auth":"required","params":[],"url":""},"isReference":false,"order":0,"body":"Recurly has a variety of official client libraries you should check out!\n\n[PHP](https://dev.recurly.com/page/php)\n[Ruby](https://dev.recurly.com/page/ruby)\n[Python](https://dev.recurly.com/page/python)\n[Java](https://github.com/killbilling/recurly-java-library)\n[.Net](https://dev.recurly.com/page/net)\niOS – [Github](https://github.com/recurly/recurly-client-ios) | [Documentation](http://cocoadocs.org/docsets/RecurlySDK/)\n[Android](https://github.com/recurly/recurly-client-android)\n\nThere are also some unofficial libraries created by our users:\n\n[GO](https://github.com/blacklightcms/recurly)\n[Node.js](https://github.com/ceejbot/recurring)\n[Elixir](https://github.com/bhelx/recurly-client-elixir)","excerpt":"","slug":"client-libraries","type":"basic","title":"Client Libraries","__v":0,"childrenPages":[]}

Client Libraries


Recurly has a variety of official client libraries you should check out!

PHP
Ruby
Python
Java
.Net
iOS – Github | Documentation
Android

There are also some unofficial libraries created by our users:

GO
Node.js
Elixir

{"_id":"5b2d60111235f100031773b3","category":"5b2d60111235f1000317734d","parentDoc":null,"project":"555fbba928249c1900618a82","user":"5564a0073a61a72f0067cb22","version":"5b2d60111235f10003177402","updates":[],"next":{"pages":[],"description":""},"createdAt":"2016-03-04T22:51:11.649Z","link_external":false,"link_url":"","githubsync":"","sync_unique":"","hidden":false,"api":{"results":{"codes":[{"name":"","code":"{}","language":"json","status":200},{"language":"json","status":400,"name":"","code":"{}"}]},"settings":"","auth":"required","params":[],"url":""},"isReference":false,"order":0,"body":"<img src=\"https://files.readme.io/kBrV8yRSzOKtvARQyP46_RecurlyJS_Logo-594.png\" alt=\"Recurly.js Logo\" width=\"300\">\n\n<h3>Customize Your Checkout Process and Accept Payments Securely</h3>\n\nSecurely accept sensitive payment details within your checkout process with a fully customizable user experience. The Recurly.js JavaScript library secures your checkout forms. Create subscriptions, process one-time transactions, and update customer billing information worry-free.\n\n<h3>PCI Compliance through Hosted Fields</h3>\n\nRecurly provides transparent iframes that allow you to deliver a customized customer checkout experience, while ensuring you meet the latest PCI DSS SAQ A compliance requirements.","excerpt":"","slug":"recurlyjs","type":"basic","title":"Recurly.js Overview","__v":0,"childrenPages":[]}

Recurly.js Overview


Recurly.js Logo

Customize Your Checkout Process and Accept Payments Securely

Securely accept sensitive payment details within your checkout process with a fully customizable user experience. The Recurly.js JavaScript library secures your checkout forms. Create subscriptions, process one-time transactions, and update customer billing information worry-free.

PCI Compliance through Hosted Fields

Recurly provides transparent iframes that allow you to deliver a customized customer checkout experience, while ensuring you meet the latest PCI DSS SAQ A compliance requirements.

{"_id":"5b2d60111235f100031773b4","category":"5b2d60111235f1000317734d","parentDoc":null,"project":"555fbba928249c1900618a82","user":"55648cf93b87582b003ab8b1","version":"5b2d60111235f10003177402","updates":["570eb5f23160d10e0041df28"],"next":{"pages":[],"description":""},"createdAt":"2016-03-01T03:19:34.724Z","link_external":false,"link_url":"","githubsync":"","sync_unique":"","hidden":false,"api":{"settings":"","results":{"codes":[{"name":"","code":"{}","language":"json","status":200},{"name":"","code":"{}","language":"json","status":400}]},"auth":"required","params":[],"url":""},"isReference":false,"order":1,"body":"When a customer submits your payment form, Recurly.js sends customer payment information to be encrypted and stored at Recurly and gives you an authorization key to complete the subscription process using our API.\n\nWith this authorization key (or *token*), you can do anything with our API that requires payment information. Because you never handle any sensitive payment information, your PCI scope is drastically reduced.","excerpt":"","slug":"recurly-js-how-it-works","type":"basic","title":"How it Works","__v":0,"childrenPages":[]}

How it Works


When a customer submits your payment form, Recurly.js sends customer payment information to be encrypted and stored at Recurly and gives you an authorization key to complete the subscription process using our API.

With this authorization key (or token), you can do anything with our API that requires payment information. Because you never handle any sensitive payment information, your PCI scope is drastically reduced.

{"_id":"5b2d60111235f100031773b5","category":"5b2d60111235f1000317734d","project":"555fbba928249c1900618a82","user":"55648cf93b87582b003ab8b1","parentDoc":null,"version":"5b2d60111235f10003177402","updates":["57180cd7602b9c0e000dab2c","59095020269f1f2300349125"],"next":{"pages":[],"description":""},"createdAt":"2016-03-01T03:21:56.345Z","link_external":false,"link_url":"","githubsync":"","sync_unique":"","hidden":false,"api":{"settings":"","results":{"codes":[{"language":"json","status":200,"name":"","code":"{}"},{"name":"","code":"{}","language":"json","status":400}]},"auth":"required","params":[],"url":""},"isReference":false,"order":2,"body":"## Include\n\n```\n<script src=\"https://js.recurly.com/v4/recurly.js\"></script>\n<link href=\"https://js.recurly.com/v4/recurly.css\" rel=\"stylesheet\" type=\"text/css\">\n```\n\nTo begin, you'll include the Recurly.js script on your page.\n\nThis exposes a single global object, `recurly`.\n\nIt is not necessary to include recurly.css, but we highly recommend it while you're getting set up. It provides some helpful default styles to Recurly payment fields.\n[block:callout]\n{\n  \"type\": \"warning\",\n  \"body\": \"The Recurly-hosted version of recurly.js is designed and updated to maintain compatibility with system update deployments that take place from time-to-time. Locally hosted versions of recurly.js run the risk of encountering issues with system interaction and incompatibility which may result in avoidable service interruptions on your client page. It is for this reason, we highly recommend against and do not support locally hosted copies of recurly.js.\",\n  \"title\": \"Self-Hosting Recurly.js\"\n}\n[/block]\n\n[block:callout]\n{\n  \"type\": \"info\",\n  \"title\": \"Framework Support\",\n  \"body\": \"Due to the necessity of gathering customer payment date within iframe elements, and the nature of reactive framework re-rendering requirements, Recurly does not at this time provide native support for reactive frameworks like React and Angular.\"\n}\n[/block]\n## Configure\n\n```\nrecurly.configure('sc-ABCDEFGHI123456789');\n```\n\nSimply call `recurly.configure` anywhere on your page, passing your public key. This identifies your site to Recurly servers. You can find your public key in the [API Access section](https://app.recurly.com/go/developer/api_access) of your admin app.\n[block:callout]\n{\n  \"type\": \"info\",\n  \"body\": \"Be sure to replace `sc-ABCDEFGHI123456789` with your own public key.\",\n  \"title\": \"Use Your Site's Public Key\"\n}\n[/block]\n`recurly.configure` accepts other options not detailed here. You may refer to the [source](https://github.com/recurly/recurly-js/blob/master/lib/recurly.js#L76-L88) for more detail.\n\n## Build a card form\n\nBuild a form however you like. Use the `data-recurly` attribute to identify input field targets to Recurly.js. For this, we recommend using simple div elements.\n\nThere are two ways to display card fields to your customers: a combined card field, and individual card fields.\n\n### Combined card field\n\nThis is the simplest and most streamlined way to accept customer card date. Recurly will inject a single field that will accept all card data. This field is responsive to various device widths and includes helpful UX enhancements to make card entry as smooth as possible.\n[block:html]\n{\n  \"html\": \"<form id=\\\"recurly-js-sample-combined-card-form\\\">\\n  <div data-recurly=\\\"card\\\"></div>\\n</form>\"\n}\n[/block]\n\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"<form>\\n  <input type=\\\"text\\\" data-recurly=\\\"first_name\\\">\\n  <input type=\\\"text\\\" data-recurly=\\\"last_name\\\">\\n  <div data-recurly=\\\"card\\\"></div>\\n  <input type=\\\"hidden\\\" name=\\\"recurly-token\\\" data-recurly=\\\"token\\\">\\n  <button>submit</button>\\n</form>\",\n      \"language\": \"html\"\n    }\n  ]\n}\n[/block]\n### Individual card fields\n\nIf you would like to display card fields separately from each other. This is helpful when the combined field does not fit your design needs.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"<form>\\n  <input type=\\\"text\\\" data-recurly=\\\"first_name\\\">\\n  <input type=\\\"text\\\" data-recurly=\\\"last_name\\\">\\n  <div data-recurly=\\\"number\\\"></div>\\n  <div data-recurly=\\\"month\\\"></div>\\n  <div data-recurly=\\\"year\\\"></div>\\n  <div data-recurly=\\\"cvv\\\"></div>\\n  <input type=\\\"hidden\\\" name=\\\"recurly-token\\\" data-recurly=\\\"token\\\">\\n  <button>submit</button>\\n</form>\",\n      \"language\": \"html\",\n      \"name\": \"HTML\"\n    }\n  ]\n}\n[/block]\nTo collect card payment information from your customers, you'll create a form similar to this one. Recurly.js uses the `data-recurly` attributes on the input tags to gather customer information before sending it to our servers.\n[block:callout]\n{\n  \"type\": \"info\",\n  \"body\": \"In order for recurly.js to inject the card payment hosted fields into your form, the target elements must be present in the document at the time you make the `recurly.configure` call.\"\n}\n[/block]\n**Note** that card data is not present in the form, but merely given a placeholder element. This is because Recurly.js must inject those fields onto the page within iframes to ensure strict security of customer card data. To further customize your checkout experience, you will be able to pick and use any color for the placeholder text.\n\nThis particular form contains the minimum required input fields, and **the table below documents all possible input fields.**\n\n### Card fields\n[block:parameters]\n{\n  \"data\": {\n    \"h-0\": \"Field Name\",\n    \"h-1\": \"Example\",\n    \"h-2\": \"Description\",\n    \"1-0\": \"number\",\n    \"2-0\": \"month\",\n    \"3-0\": \"year\",\n    \"4-0\": \"first_name\",\n    \"5-0\": \"last_name\",\n    \"6-0\": \"cvv\",\n    \"1-1\": \"`4111-1111-1111-1111`\",\n    \"2-1\": \"`8` or `08`\",\n    \"3-1\": \"`22` or `2022`\",\n    \"4-1\": \"`Pat`\",\n    \"5-1\": \"`Smith`\",\n    \"6-1\": \"`123`\",\n    \"1-2\": \"Credit card number. **Required** if using individual card fields\",\n    \"2-2\": \"Card expiration month as a number. **Required** if using individual card fields\",\n    \"3-2\": \"Card expiration year as a number. **Required** if using individual card fields\",\n    \"4-2\": \"Cardholder first name. **Required**\",\n    \"5-2\": \"Cardholder last name. **Required**\",\n    \"6-2\": \"Card security code.\",\n    \"0-0\": \"card\",\n    \"0-1\": \"`4111-1111-1111-1111 08/22 123`\",\n    \"0-2\": \"Combined card field. **Required** if using the combined card field\"\n  },\n  \"cols\": 3,\n  \"rows\": 7\n}\n[/block]\nDepending on how you've configured your [billing address requirements](http://docs.recurly.com/site-settings#address_requirements), some of the following fields may be required.\n\n### Billing address fields\n[block:parameters]\n{\n  \"data\": {\n    \"h-0\": \"Field Name\",\n    \"h-1\": \"Example\",\n    \"h-2\": \"Description\",\n    \"0-0\": \"address1\",\n    \"0-1\": \"`1313 Main St.`\",\n    \"0-2\": \"First line of a street address.\",\n    \"1-0\": \"address2\",\n    \"1-1\": \"`Unit 1`\",\n    \"1-2\": \"Second line of a street address.\",\n    \"2-0\": \"city\",\n    \"2-1\": \"`Hope`\",\n    \"2-2\": \"Town or locality.\",\n    \"3-0\": \"state\",\n    \"3-1\": \"`WA`\",\n    \"3-2\": \"Province or region.\",\n    \"4-0\": \"postal_code\",\n    \"4-1\": \"`98552`\",\n    \"4-2\": \"Postal code.\",\n    \"5-0\": \"country\",\n    \"5-1\": \"`US`\",\n    \"5-2\": \"[ISO 3166-1 alpha-2](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code.\",\n    \"6-0\": \"phone\",\n    \"6-1\": \"`555-867-5309`\",\n    \"6-2\": \"Phone number.\",\n    \"7-0\": \"vat_number\",\n    \"7-1\": \"`SE0000`\",\n    \"7-2\": \"Customer VAT number. Used for VAT exclusion.\"\n  },\n  \"cols\": 3,\n  \"rows\": 8\n}\n[/block]\n## Working with bank accounts\n\nJust like a card form, use the data-recurly attribute to identify fields to Recurly.js. Since Recurly.js does not need to inject fields for bank accounts, all fields may be displayed as inputs on your payment form.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"<form>\\n  <input type=\\\"text\\\" data-recurly=\\\"routing_number\\\">\\n  <input type=\\\"text\\\" data-recurly=\\\"account_number\\\">\\n  <input type=\\\"text\\\" data-recurly=\\\"account_number_confirmation\\\">\\n  <input type=\\\"text\\\" data-recurly=\\\"account_type\\\">\\n  <input type=\\\"text\\\" data-recurly=\\\"name_on_account\\\">\\n  <input type=\\\"hidden\\\" name=\\\"recurly-token\\\" data-recurly=\\\"token\\\">\\n  <button>submit</button>\\n</form>\",\n      \"language\": \"html\"\n    }\n  ]\n}\n[/block]\nAs you would a card form, you collect bank account payment information from your customers, identifying them with the `data-recurly` attributes on the input tags. This form demonstrates the minimum required input fields, and __the table below highlights all possible input fields.__\n\n### Bank Account data\n[block:parameters]\n{\n  \"data\": {\n    \"h-0\": \"Field Name\",\n    \"h-1\": \"Example\",\n    \"h-2\": \"Description\",\n    \"0-0\": \"routing_number\",\n    \"0-1\": \"`123456789`\",\n    \"0-2\": \"Routing number. **Required**\",\n    \"1-0\": \"account_number\",\n    \"2-0\": \"account_number_confirmation\",\n    \"3-0\": \"account_type\",\n    \"4-0\": \"name_on_account\",\n    \"4-1\": \"`Pat Smith`\",\n    \"3-1\": \"`checking` or `savings`\",\n    \"2-1\": \"`987654321`\",\n    \"1-1\": \"`987654321`\",\n    \"1-2\": \"Account number. **Required**\",\n    \"2-2\": \"Account number confirmation. **Required**\",\n    \"3-2\": \"Account type. **Required**\",\n    \"4-2\": \"Full name on account. **Required**\"\n  },\n  \"cols\": 3,\n  \"rows\": 5\n}\n[/block]\n### Billing address\n\n[See card billing address]","excerpt":"","slug":"recurly-js-getting-started","type":"basic","title":"Getting Started","__v":0,"childrenPages":[]}

Getting Started


Include

<script src="https://js.recurly.com/v4/recurly.js"></script>
<link href="https://js.recurly.com/v4/recurly.css" rel="stylesheet" type="text/css">

To begin, you'll include the Recurly.js script on your page.

This exposes a single global object, recurly.

It is not necessary to include recurly.css, but we highly recommend it while you're getting set up. It provides some helpful default styles to Recurly payment fields.

Self-Hosting Recurly.js

The Recurly-hosted version of recurly.js is designed and updated to maintain compatibility with system update deployments that take place from time-to-time. Locally hosted versions of recurly.js run the risk of encountering issues with system interaction and incompatibility which may result in avoidable service interruptions on your client page. It is for this reason, we highly recommend against and do not support locally hosted copies of recurly.js.

Framework Support

Due to the necessity of gathering customer payment date within iframe elements, and the nature of reactive framework re-rendering requirements, Recurly does not at this time provide native support for reactive frameworks like React and Angular.

Configure

recurly.configure('sc-ABCDEFGHI123456789');

Simply call recurly.configure anywhere on your page, passing your public key. This identifies your site to Recurly servers. You can find your public key in the API Access section of your admin app.

Use Your Site's Public Key

Be sure to replace sc-ABCDEFGHI123456789 with your own public key.

recurly.configure accepts other options not detailed here. You may refer to the source for more detail.

Build a card form

Build a form however you like. Use the data-recurly attribute to identify input field targets to Recurly.js. For this, we recommend using simple div elements.

There are two ways to display card fields to your customers: a combined card field, and individual card fields.

Combined card field

This is the simplest and most streamlined way to accept customer card date. Recurly will inject a single field that will accept all card data. This field is responsive to various device widths and includes helpful UX enhancements to make card entry as smooth as possible.

<form>
  <input type="text" data-recurly="first_name">
  <input type="text" data-recurly="last_name">
  <div data-recurly="card"></div>
  <input type="hidden" name="recurly-token" data-recurly="token">
  <button>submit</button>
</form>

Individual card fields

If you would like to display card fields separately from each other. This is helpful when the combined field does not fit your design needs.

<form>
  <input type="text" data-recurly="first_name">
  <input type="text" data-recurly="last_name">
  <div data-recurly="number"></div>
  <div data-recurly="month"></div>
  <div data-recurly="year"></div>
  <div data-recurly="cvv"></div>
  <input type="hidden" name="recurly-token" data-recurly="token">
  <button>submit</button>
</form>

To collect card payment information from your customers, you'll create a form similar to this one. Recurly.js uses the data-recurly attributes on the input tags to gather customer information before sending it to our servers.

In order for recurly.js to inject the card payment hosted fields into your form, the target elements must be present in the document at the time you make the recurly.configure call.

Note that card data is not present in the form, but merely given a placeholder element. This is because Recurly.js must inject those fields onto the page within iframes to ensure strict security of customer card data. To further customize your checkout experience, you will be able to pick and use any color for the placeholder text.

This particular form contains the minimum required input fields, and the table below documents all possible input fields.

Card fields

Field Name
Example
Description

card

4111-1111-1111-1111 08/22 123

Combined card field. Required if using the combined card field

number

4111-1111-1111-1111

Credit card number. Required if using individual card fields

month

8 or 08

Card expiration month as a number. Required if using individual card fields

year

22 or 2022

Card expiration year as a number. Required if using individual card fields

first_name

Pat

Cardholder first name. Required

last_name

Smith

Cardholder last name. Required

cvv

123

Card security code.

Depending on how you've configured your billing address requirements, some of the following fields may be required.

Billing address fields

Field Name
Example
Description

address1

1313 Main St.

First line of a street address.

address2

Unit 1

Second line of a street address.

city

Hope

Town or locality.

state

WA

Province or region.

postal_code

98552

Postal code.

country

US

ISO 3166-1 alpha-2 country code.

phone

555-867-5309

Phone number.

vat_number

SE0000

Customer VAT number. Used for VAT exclusion.

Working with bank accounts

Just like a card form, use the data-recurly attribute to identify fields to Recurly.js. Since Recurly.js does not need to inject fields for bank accounts, all fields may be displayed as inputs on your payment form.

<form>
  <input type="text" data-recurly="routing_number">
  <input type="text" data-recurly="account_number">
  <input type="text" data-recurly="account_number_confirmation">
  <input type="text" data-recurly="account_type">
  <input type="text" data-recurly="name_on_account">
  <input type="hidden" name="recurly-token" data-recurly="token">
  <button>submit</button>
</form>

As you would a card form, you collect bank account payment information from your customers, identifying them with the data-recurly attributes on the input tags. This form demonstrates the minimum required input fields, and the table below highlights all possible input fields.

Bank Account data

Field Name
Example
Description

routing_number

123456789

Routing number. Required

account_number

987654321

Account number. Required

account_number_confirmation

987654321

Account number confirmation. Required

account_type

checking or savings

Account type. Required

name_on_account

Pat Smith

Full name on account. Required

Billing address

[See card billing address]

{"_id":"5b2d60111235f100031773b6","category":"5b2d60111235f1000317734d","project":"555fbba928249c1900618a82","user":"57292bdb0388c70e00f3d8f3","parentDoc":null,"version":"5b2d60111235f10003177402","updates":[],"next":{"pages":[],"description":""},"createdAt":"2018-03-20T23:37:54.259Z","link_external":false,"link_url":"","githubsync":"","sync_unique":"","hidden":false,"api":{"results":{"codes":[{"name":"","code":"{}","language":"json","status":200},{"name":"","code":"{}","language":"json","status":400}]},"settings":"","auth":"required","params":[],"url":""},"isReference":false,"order":3,"body":"[block:api-header]\n{\n  \"title\": \"Example field style configuration\"\n}\n[/block]\n\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"recurly.configure({\\n  publicKey: 'my-public-key',\\n  fields: {\\n    // affects all fields\\n    all: {\\n      style: {\\n        fontFamily: 'Helvetica, sans-serif'\\n      }\\n    },\\n\\n    // affects the combined card field\\n    card: {\\n      displayIcon: true,\\n      style: {\\n        fontSize: '1em',\\n        placeholder: {\\n          color: 'gray !important',\\n          fontWeight: 'bold',\\n          content: {\\n            number: 'Card number',\\n            cvv: 'CVC'\\n          }\\n        },\\n        invalid: {\\n          fontColor: 'red'\\n        }\\n      }\\n    },\\n\\n    // affects individual card field types\\n    number: {\\n      // Custom target selector\\n      selector: '#recurly-number',\\n      // Format the card number\\n      format: true\\n    },\\n    month: {\\n      // Display a month select on mobile devices\\n      inputType: 'mobileSelect',\\n      style: {\\n        placeholder: {\\n          content: 'MM'\\n        }\\n      }\\n    },\\n    year: {\\n      style: {\\n        placeholder: {\\n          content: 'YYYY'\\n        }\\n      }\\n    },\\n    cvv: {}\\n  }\\n});\",\n      \"language\": \"javascript\"\n    }\n  ],\n  \"sidebar\": true\n}\n[/block]\n## Style Configuration\n\nSince card fields must be injected within iframes, any style properties within those iframes must be passed to `recurly.configure`. See the code example at right.\n\n### Styling the combined card field\n\nOptions unique to the combined card field are detailed in the following table. When passed into your `recurly.configure` call, each property must be nested within `fields.card`.\n\n#### Combined card field properties\n[block:parameters]\n{\n  \"data\": {\n    \"h-0\": \"Property\",\n    \"h-1\": \"Default\",\n    \"h-2\": \"Description\",\n    \"0-0\": \"displayIcon\",\n    \"0-1\": \"`true`\",\n    \"0-2\": \"if false, the card brand icon will be hidden\",\n    \"7-0\": \"style.placeholder\",\n    \"8-0\": \"style.placeholder.color\",\n    \"7-1\": \"`{}`\",\n    \"7-2\": \"Object\",\n    \"8-1\": \"`'#a3a3a7'`\",\n    \"8-2\": \"Font <a href=\\\"https://developer.mozilla.org/en-US/docs/Web/CSS/color\\\" target=\\\"_blank\\\">color</a> applied to all placeholder text.\",\n    \"9-0\": \"style.placeholder.content\",\n    \"9-1\": \"`{}`\",\n    \"9-2\": \"Object\",\n    \"10-0\": \"style.placeholder.content.number\",\n    \"10-1\": \"`'Card number'`\",\n    \"10-2\": \"Placeholder content for the number input.\",\n    \"11-0\": \"style.placeholder.content.expiry\",\n    \"11-1\": \"`'MM / YY'`\",\n    \"11-2\": \"Placeholder content for the expiry input.\",\n    \"12-0\": \"style.placeholder.content.cvv\",\n    \"12-1\": \"`'CVV'`\",\n    \"12-2\": \"Placeholder content for the card verification value input.\",\n    \"13-0\": \"style.invalid\",\n    \"13-1\": \"`{}`\",\n    \"13-2\": \"Object. Style to apply to input elements when they contain an invalid value. See [common field style properties](#section-common-field-style-properties).\",\n    \"14-0\": \"style.invalid.fontColor\",\n    \"14-1\": \"`'#a3a3a7'`\",\n    \"14-2\": \"Font <a href=\\\"https://developer.mozilla.org/en-US/docs/Web/CSS/color\\\" target=\\\"_blank\\\">color</a>  applied to invalid input elements.\",\n    \"3-0\": \"style\",\n    \"3-2\": \"See [common field style properties](#section-common-field-style-properties).\",\n    \"3-1\": \"`{}`\",\n    \"2-0\": \"selector\",\n    \"2-2\": \"Specify a custom target selector (e.g. `'#recurly-card'`)\",\n    \"1-0\": \"inputType\",\n    \"1-1\": \"`'text'`\",\n    \"1-2\": \"Modifies the input type of the card field.\\n`'text'` - text input for all fields.\\n`'mobileSelect'` - If the user is using a mobile device, a native expiry select interface will appear when entering the expiration date.\\n`'select'` - Expiration date will be input using a select field on all devices. Mobile devices will display an optimized interface.\",\n    \"15-0\": \"tabIndex\",\n    \"15-1\": \"\",\n    \"15-2\": \"<a href=\\\"https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex\\\" target=\\\"_blank\\\">tabIndex</a> property to be applied to the outer iframe.\",\n    \"4-0\": \"style.fontColor\",\n    \"4-1\": \"`'#545457'`\",\n    \"5-0\": \"style.fontFamily\",\n    \"5-1\": \"`'Source Sans Pro'`\",\n    \"6-0\": \"style.fontSize\",\n    \"6-1\": \"`'16px'`\",\n    \"4-2\": \"Font <a href=\\\"https://developer.mozilla.org/en-US/docs/Web/CSS/color\\\" target=\\\"_blank\\\">color</a> for each input element.\",\n    \"5-2\": \"<a href=\\\"https://developer.mozilla.org/en-US/docs/Web/CSS/font-family\\\" target=\\\"_blank\\\">font-family</a> for each input element.\",\n    \"6-2\": \"<a href=\\\"https://developer.mozilla.org/en-US/docs/Web/CSS/font-size\\\" target=\\\"_blank\\\">font-size</a> for each input element.\"\n  },\n  \"cols\": 3,\n  \"rows\": 16\n}\n[/block]\n### Styling the individual card fields\n\nOptions unique to the individual card fields are detailed in the following table. When passed into your `recurly.configure` call, each property must be nested within `fields.all` or a respective `fields.number`, `fields.month`, `fields.year`, or `fields.cvv` object.\n\n#### Individual card field properties\n[block:parameters]\n{\n  \"data\": {\n    \"h-0\": \"Property\",\n    \"h-1\": \"Default\",\n    \"h-2\": \"Description\",\n    \"0-0\": \"format\",\n    \"0-1\": \"`true`\",\n    \"0-2\": \"Enables contextual input formatting, injecting spaces to match the card brand, and forcing numeric input on expiry and cvv.\",\n    \"3-0\": \"style\",\n    \"3-1\": \"`{}`\",\n    \"3-2\": \"See [common field style properties](#section-common-field-style-properties).\",\n    \"4-0\": \"style.placeholder.color\",\n    \"4-2\": \"Font <a href=\\\"https://developer.mozilla.org/en-US/docs/Web/CSS/color\\\" target=\\\"_blank\\\">color</a>  applied to the placeholder text.\",\n    \"5-0\": \"style.placeholder.content\",\n    \"5-1\": \"`''`\",\n    \"5-2\": \"Placeholder content (e.g. `'Card number'`, `'CVV'`)\",\n    \"2-0\": \"selector\",\n    \"2-2\": \"Specify a custom target selector (e.g. `'#recurly-number'`)\",\n    \"1-0\": \"inputType\",\n    \"1-1\": \"`'text'`\",\n    \"1-2\": \"Modifies the input type of the expiry fields.\\n`'text'` - normal text input.\\n`'mobileSelect'` - If the user is using a mobile device, a native select interface will appear.\\n`'select'` - A select field will display on all devices.\\n\\n*Valid only on the `month`, and `year` fields.*\",\n    \"6-0\": \"tabIndex\",\n    \"6-2\": \"<a href=\\\"https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex\\\" target=\\\"_blank\\\">tabIndex</a>  property to be applied to the outer iframe.\"\n  },\n  \"cols\": 3,\n  \"rows\": 7\n}\n[/block]\n#### Common field style properties\n[block:parameters]\n{\n  \"data\": {\n    \"h-0\": \"Property\",\n    \"h-2\": \"Reference\",\n    \"h-1\": \"Default\",\n    \"0-0\": \"style.fontColor\",\n    \"0-1\": \"`'black'`\",\n    \"0-2\": \"<a href=\\\"https://developer.mozilla.org/en-US/docs/Web/CSS/color\\\" target=\\\"_blank\\\">color</a>\",\n    \"1-0\": \"style.fontFamily\",\n    \"1-1\": \"`'Helvetica'`\",\n    \"1-2\": \"<a href=\\\"https://developer.mozilla.org/en-US/docs/Web/CSS/font-family\\\" target=\\\"_blank\\\">font-family</a>\",\n    \"2-0\": \"style.fontFeatureSettings\",\n    \"2-1\": \"`'normal'`\",\n    \"2-2\": \"<a href=\\\"https://developer.mozilla.org/en-US/docs/Web/CSS/font-feature-settings\\\" target=\\\"_blank\\\">font-feature-settings</a>\",\n    \"3-0\": \"style.fontKerning\",\n    \"4-0\": \"style.fontSize\",\n    \"5-0\": \"style.fontSmoothing\",\n    \"6-0\": \"style.fontStretch\",\n    \"7-0\": \"style.fontStyle\",\n    \"8-0\": \"style.fontVariant\",\n    \"9-0\": \"style.fontWeight\",\n    \"10-0\": \"style.letterSpacing\",\n    \"11-0\": \"style.lineHeight\",\n    \"12-0\": \"style.padding\",\n    \"3-1\": \"`'auto'`\",\n    \"4-1\": \"`'inherit'`\",\n    \"5-1\": \"`'auto'`\",\n    \"6-1\": \"`'normal'`\",\n    \"13-0\": \"style.textAlign\",\n    \"14-0\": \"style.textDecoration\",\n    \"15-0\": \"style.textRendering\",\n    \"16-0\": \"style.textShadow\",\n    \"17-0\": \"style.textTransform\",\n    \"7-1\": \"`'normal'`\",\n    \"8-1\": \"`'normal'`\",\n    \"9-1\": \"`'normal'`\",\n    \"10-1\": \"`'normal'`\",\n    \"11-1\": \"`'normal'`\",\n    \"12-1\": \"\",\n    \"13-1\": \"\",\n    \"15-1\": \"`'auto'`\",\n    \"16-1\": \"`'none'`\",\n    \"17-1\": \"`'none'`\",\n    \"3-2\": \"<a href=\\\"https://developer.mozilla.org/en-US/docs/Web/CSS/font-kerning\\\" target=\\\"_blank\\\">font-kerning</a>\",\n    \"4-2\": \"<a href=\\\"https://developer.mozilla.org/en-US/docs/Web/CSS/font-size\\\" target=\\\"_blank\\\">font-size</a>\",\n    \"5-2\": \"<a href=\\\"https://developer.mozilla.org/en-US/docs/Web/CSS/font-smoothing\\\" target=\\\"_blank\\\">font-smoothing</a>\",\n    \"6-2\": \"<a href=\\\"https://developer.mozilla.org/en-US/docs/Web/CSS/font-stretch\\\" target=\\\"_blank\\\">font-stretch</a>\",\n    \"7-2\": \"<a href=\\\"https://developer.mozilla.org/en-US/docs/Web/CSS/font-style\\\" target=\\\"_blank\\\">font-style</a>\",\n    \"8-2\": \"<a href=\\\"https://developer.mozilla.org/en-US/docs/Web/CSS/font-variant\\\" target=\\\"_blank\\\">font-variant</a>\",\n    \"9-2\": \"<a href=\\\"https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight\\\" target=\\\"_blank\\\">font-weight</a>\",\n    \"10-2\": \"<a href=\\\"https://developer.mozilla.org/en-US/docs/Web/CSS/letter-spacing\\\" target=\\\"_blank\\\">letter-spacing</a>\",\n    \"11-2\": \"<a href=\\\"https://developer.mozilla.org/en-US/docs/Web/CSS/line-height\\\" target=\\\"_blank\\\">line-height</a>\",\n    \"12-2\": \"<a href=\\\"https://developer.mozilla.org/en-US/docs/Web/CSS/padding\\\" target=\\\"_blank\\\">padding</a>\",\n    \"13-2\": \"<a href=\\\"https://developer.mozilla.org/en-US/docs/Web/CSS/text-align\\\" target=\\\"_blank\\\">text-align</a>\",\n    \"14-2\": \"<a href=\\\"https://developer.mozilla.org/en-US/docs/Web/CSS/text-decoration\\\" target=\\\"_blank\\\">text-decoration</a>\",\n    \"15-2\": \"<a href=\\\"https://developer.mozilla.org/en-US/docs/Web/CSS/text-rendering\\\" target=\\\"_blank\\\">text-rendering</a>\",\n    \"16-2\": \"<a href=\\\"https://developer.mozilla.org/en-US/docs/Web/CSS/text-shadow\\\" target=\\\"_blank\\\">text-shadow</a>\",\n    \"17-2\": \"<a href=\\\"https://developer.mozilla.org/en-US/docs/Web/CSS/text-transform\\\" target=\\\"_blank\\\">text-transform</a>\"\n  },\n  \"cols\": 3,\n  \"rows\": 18\n}\n[/block]\n## CSS Classes\n\nSince Recurly.js must inject card data fields into iframes, the default browser appearance for those fields will likely not match the appearance of the other fields in your payment form. We provide the following CSS classes to achieve a look and feel similar to your form. Using these classes, you may specify field size, colors, and a full range of appearance customization to make the injected card fields blend into your payment form.\n[block:parameters]\n{\n  \"data\": {\n    \"h-0\": \"Class Name\",\n    \"h-1\": \"Description\",\n    \"0-0\": \"recurly-hosted-field\",\n    \"0-1\": \"Default styles for the div surrounding each field iframe.\",\n    \"1-0\": \"recurly-hosted-field-focus\",\n    \"1-1\": \"Applied when the user focuses on a field.\",\n    \"3-0\": \"recurly-hosted-field-number\",\n    \"3-1\": \"Default styles for the div surrounding the number field iframe.\",\n    \"4-0\": \"recurly-hosted-field-month\",\n    \"4-1\": \"Default styles for the div surrounding the month field iframe.\",\n    \"5-0\": \"recurly-hosted-field-year\",\n    \"5-1\": \"Default styles for the div surrounding the year field iframe.\",\n    \"6-0\": \"recurly-hosted-field-cvv\",\n    \"6-1\": \"Default styles for the div surrounding the cvv field iframe.\",\n    \"2-0\": \"recurly-hosted-field-card\",\n    \"2-1\": \"Default styles for the div surrounding the combined card field iframe.\"\n  },\n  \"cols\": 2,\n  \"rows\": 7\n}\n[/block]\n## Custom Fonts\n\nYou may specify font and placeholder text for card fields through `recurly.configure`. The example call above demonstrates all available style attributes you may send to `recurly.configure`.\n\nCustom fonts are sourced from [Google Web Fonts](https://www.google.com/fonts). Simply use the name of the font as it appears on the Google Web Fonts site.\n\n## Responsive styles\n\nAll of the built in field classes will support and respond to media queries. You may call `recurly.configure` again to change style properties within each field -- thus you may change any property if the window size changes.","excerpt":"","slug":"recurly-js-styling-card-fields","type":"basic","title":"Styling Card Fields","__v":0,"childrenPages":[]}

Styling Card Fields


Example field style configuration

Style Configuration

Since card fields must be injected within iframes, any style properties within those iframes must be passed to recurly.configure. See the code example at right.

Styling the combined card field

Options unique to the combined card field are detailed in the following table. When passed into your recurly.configure call, each property must be nested within fields.card.

Combined card field properties

Property
Default
Description

displayIcon

true

if false, the card brand icon will be hidden

inputType

'text'

Modifies the input type of the card field.
'text' - text input for all fields.
'mobileSelect' - If the user is using a mobile device, a native expiry select interface will appear when entering the expiration date.
'select' - Expiration date will be input using a select field on all devices. Mobile devices will display an optimized interface.

selector

Specify a custom target selector (e.g. '#recurly-card')

style.fontColor

'#545457'

Font color for each input element.

style.fontFamily

'Source Sans Pro'

font-family for each input element.

style.fontSize

'16px'

font-size for each input element.

style.placeholder

{}

Object

style.placeholder.color

'#a3a3a7'

Font color applied to all placeholder text.

style.placeholder.content

{}

Object

style.placeholder.content.number

'Card number'

Placeholder content for the number input.

style.placeholder.content.expiry

'MM / YY'

Placeholder content for the expiry input.

style.placeholder.content.cvv

'CVV'

Placeholder content for the card verification value input.

style.invalid

{}

Object. Style to apply to input elements when they contain an invalid value. See common field style properties.

style.invalid.fontColor

'#a3a3a7'

Font color applied to invalid input elements.

tabIndex

tabIndex property to be applied to the outer iframe.

Styling the individual card fields

Options unique to the individual card fields are detailed in the following table. When passed into your recurly.configure call, each property must be nested within fields.all or a respective fields.number, fields.month, fields.year, or fields.cvv object.

Individual card field properties

Property
Default
Description

format

true

Enables contextual input formatting, injecting spaces to match the card brand, and forcing numeric input on expiry and cvv.

inputType

'text'

Modifies the input type of the expiry fields.
'text' - normal text input.
'mobileSelect' - If the user is using a mobile device, a native select interface will appear.
'select' - A select field will display on all devices.

Valid only on the month, and year fields.

selector

Specify a custom target selector (e.g. '#recurly-number')

style.placeholder.color

Font color applied to the placeholder text.

style.placeholder.content

''

Placeholder content (e.g. 'Card number', 'CVV')

tabIndex

tabIndex property to be applied to the outer iframe.

Common field style properties

Property
Default
Reference

style.fontColor

'black'

style.fontFamily

'Helvetica'

style.fontFeatureSettings

'normal'

style.fontKerning

'auto'

style.fontSize

'inherit'

style.fontSmoothing

'auto'

style.fontStretch

'normal'

style.fontStyle

'normal'

style.fontVariant

'normal'

style.fontWeight

'normal'

style.letterSpacing

'normal'

style.lineHeight

'normal'

style.padding

style.textAlign

style.textDecoration

style.textRendering

'auto'

style.textShadow

'none'

style.textTransform

'none'

CSS Classes

Since Recurly.js must inject card data fields into iframes, the default browser appearance for those fields will likely not match the appearance of the other fields in your payment form. We provide the following CSS classes to achieve a look and feel similar to your form. Using these classes, you may specify field size, colors, and a full range of appearance customization to make the injected card fields blend into your payment form.

Class Name
Description

recurly-hosted-field

Default styles for the div surrounding each field iframe.

recurly-hosted-field-focus

Applied when the user focuses on a field.

recurly-hosted-field-card

Default styles for the div surrounding the combined card field iframe.

recurly-hosted-field-number

Default styles for the div surrounding the number field iframe.

recurly-hosted-field-month

Default styles for the div surrounding the month field iframe.

recurly-hosted-field-year

Default styles for the div surrounding the year field iframe.

recurly-hosted-field-cvv

Default styles for the div surrounding the cvv field iframe.

Custom Fonts

You may specify font and placeholder text for card fields through recurly.configure. The example call above demonstrates all available style attributes you may send to recurly.configure.

Custom fonts are sourced from Google Web Fonts. Simply use the name of the font as it appears on the Google Web Fonts site.

Responsive styles

All of the built in field classes will support and respond to media queries. You may call recurly.configure again to change style properties within each field -- thus you may change any property if the window size changes.

recurly.configure({
  publicKey: 'my-public-key',
  fields: {
    // affects all fields
    all: {
      style: {
        fontFamily: 'Helvetica, sans-serif'
      }
    },

    // affects the combined card field
    card: {
      displayIcon: true,
      style: {
        fontSize: '1em',
        placeholder: {
          color: 'gray !important',
          fontWeight: 'bold',
          content: {
            number: 'Card number',
            cvv: 'CVC'
          }
        },
        invalid: {
          fontColor: 'red'
        }
      }
    },

    // affects individual card field types
    number: {
      // Custom target selector
      selector: '#recurly-number',
      // Format the card number
      format: true
    },
    month: {
      // Display a month select on mobile devices
      inputType: 'mobileSelect',
      style: {
        placeholder: {
          content: 'MM'
        }
      }
    },
    year: {
      style: {
        placeholder: {
          content: 'YYYY'
        }
      }
    },
    cvv: {}
  }
});
{"_id":"5b2d60111235f100031773b7","category":"5b2d60111235f1000317734d","user":"55648cf93b87582b003ab8b1","parentDoc":null,"project":"555fbba928249c1900618a82","version":"5b2d60111235f10003177402","updates":["583606faf50e460f009179cd"],"next":{"pages":[],"description":""},"createdAt":"2016-03-01T04:39:30.344Z","link_external":false,"link_url":"","githubsync":"","sync_unique":"","hidden":false,"api":{"results":{"codes":[{"name":"","code":"{}","language":"json","status":200},{"name":"","code":"{}","language":"json","status":400}]},"settings":"","auth":"required","params":[],"url":""},"isReference":false,"order":4,"body":"Interrupt the form submit to send billing info to Recurly and get a secure token in exchange. Once you have the token, submit the form to your server.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"$('form').on('submit', function (event) {\\n  var form = this;\\n  event.preventDefault();\\n  recurly.token(form, function (err, token) {\\n    if (err) {\\n      // handle error using err.code and err.fields\\n    } else {\\n      // recurly.js has filled in the 'token' field, so now we can submit the\\n      // form to your server; alternatively, you can access token.id and do\\n      // any processing you wish\\n      form.submit();\\n    }\\n  });\\n});\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\nRecurly.js works with tokens, which represent secure and temporary storage for your customer's sensitive billing information. They are stored directly on Recurly servers to reduce your PCI exposure.\n\nWhen your customers submit your billing form, you'll need to interrupt the submit and ask Recurly.js to create a token from the form. You may have noticed an additional hidden field in the form above, `token`. When you ask Recurly.js for a token during submit, it will automatically populate this field for you. After you get the token, you will submit it to your servers and use it there to talk to any endpoint in our API that accepts a `billing_info`.\n[block:callout]\n{\n  \"type\": \"info\",\n  \"body\": \"This example demonstrates jQuery as an event-binding and DOM library; however, you may use any library you choose, or interact directly with the DOM (hard mode).\"\n}\n[/block]\n# Reference\n[block:html]\n{\n  \"html\": \"<h3>\\n  <span class=\\\"pg-type-big pg-type type-fn\\\">fn</span>\\n  recurly.token\\n</h2>\"\n}\n[/block]\nYou must call recurly.token with your form element.\n\n`recurly.token(document.querySelector('form'), tokenHandler);`\n\nUsing a handler function like this one:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"function tokenHandler (err, token) {\\n  if (err) {\\n    // handle error using err.code and err.fields\\n  } else {\\n    // handle success using token.id\\n  }\\n}\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\nSends billing information to Recurly to store as a token, sending that token id back to you.\n[block:parameters]\n{\n  \"data\": {\n    \"h-0\": \"Param\",\n    \"h-1\": \"Type\",\n    \"h-2\": \"Description\",\n    \"0-0\": \"form\",\n    \"0-1\": \"`HTMLFormElement`\",\n    \"0-2\": \"Parent form containing `data-recurly` fields.\",\n    \"1-0\": \"callback\",\n    \"1-1\": \"`Function`\",\n    \"1-2\": \"Callback function to accept the returned token.\"\n  },\n  \"cols\": 3,\n  \"rows\": 2\n}\n[/block]\nA callback is always required\n\n### Callback Arguments\n[block:parameters]\n{\n  \"data\": {\n    \"h-0\": \"Param\",\n    \"h-1\": \"Type\",\n    \"h-2\": \"Description\",\n    \"0-0\": \"err\",\n    \"1-0\": \"token\",\n    \"2-0\": \"token.id\",\n    \"0-1\": \"`RecurlyError` or `null`\",\n    \"0-2\": \"A [`RecurlyError`](#errors) if an error occurred; otherwise `null`.\",\n    \"1-1\": \"`Object`\",\n    \"1-2\": \"An object containing a token id.\",\n    \"2-1\": \"`String`\",\n    \"2-2\": \"A token id.\"\n  },\n  \"cols\": 3,\n  \"rows\": 3\n}\n[/block]\n### Returns\n\nNothing.\n\n## recurly.bankAccount.token(API)\n\nYou may call recurly.bankAccount.token with a form element\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"recurly.bankAccount.token(document.querySelector('form'), tokenHandler);\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\nOr with an Object\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"// alternatively..\\nvar billingInfo = {\\n  // required attributes\\n  routing_number: '123456780',\\n  account_number: '111111111',\\n  account_number_confirmation: '111111111',\\n  account_type: 'checking',\\n  name_on_account: 'Pat Smith',\\n\\n  // optional attributes\\n  address1: '123 Main St.',\\n  address2: 'Unit 1',\\n  city: 'Hope',\\n  state: 'WA',\\n  postal_code: '98552',\\n  country: 'US',\\n  vat_number: 'SE0000'\\n};\\n\\nrecurly.bankAccount.token(billingInfo, tokenHandler);\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\nBoth methods require using a handler function like this one\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"function tokenHandler (err, token) {\\n  if (err) {\\n    // handle error using err.code and err.fields\\n  } else {\\n    // handle success using token.id\\n  }\\n}\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\nSends bank account billing information to Recurly to store as a token, sending that token id back to you. Just as with card tokenization, there are two ways to call `recurly.bankAccount.token`: with a form, and with an object.\n\nThe simplest is to pass it a form element containing form fields with their corresponding `data-recurly` attributes.\n\n### Arguments (form)\n[block:parameters]\n{\n  \"data\": {\n    \"1-0\": \"callback\",\n    \"0-0\": \"form\",\n    \"h-0\": \"Param\",\n    \"h-1\": \"Type\",\n    \"h-2\": \"Description\",\n    \"0-1\": \"`HTMLFormElement`\",\n    \"0-2\": \"Parent form containing `data-recurly` fields.\",\n    \"1-1\": \"`Function`\",\n    \"1-2\": \"Callback function to accept the returned token.\"\n  },\n  \"cols\": 3,\n  \"rows\": 2\n}\n[/block]\nAlternatively, you can call `recurly.bankAccount.token` with a plain JavaScript object. This allows a more direct interface to the payment flow, eliminating any need to use the DOM.\n\n### Arguments (object)\n[block:parameters]\n{\n  \"data\": {\n    \"0-0\": \"options\",\n    \"1-0\": \"callback\",\n    \"0-1\": \"`Object`\",\n    \"0-2\": \"An object with billing information properties matching those [outlined above].\",\n    \"1-1\": \"`Function`\",\n    \"1-2\": \"Callback function to accept the returned token.\",\n    \"h-0\": \"Param\",\n    \"h-1\": \"Type\",\n    \"h-2\": \"Description\"\n  },\n  \"cols\": 3,\n  \"rows\": 2\n}\n[/block]\nA callback is always required\n\n### Callback Arguments\n[block:parameters]\n{\n  \"data\": {\n    \"h-0\": \"Param\",\n    \"h-1\": \"Type\",\n    \"h-2\": \"Description\",\n    \"0-0\": \"err\",\n    \"1-0\": \"token\",\n    \"2-0\": \"id\",\n    \"2-1\": \"`String`\",\n    \"2-2\": \"A token id.\",\n    \"0-1\": \"`RecurlyError` or `null`\",\n    \"0-2\": \"A [`RecurlyError`](#errors) if an error occurred; otherwise `null`.\",\n    \"1-1\": \"`Object`\",\n    \"1-2\": \"An object containing a token id.\"\n  },\n  \"cols\": 3,\n  \"rows\": 3\n}\n[/block]\n### Returns\n\nNothing.","excerpt":"","slug":"recurly-js-getting-a-token","type":"basic","title":"Getting a Token","__v":0,"childrenPages":[]}

Getting a Token


Interrupt the form submit to send billing info to Recurly and get a secure token in exchange. Once you have the token, submit the form to your server.

$('form').on('submit', function (event) {
  var form = this;
  event.preventDefault();
  recurly.token(form, function (err, token) {
    if (err) {
      // handle error using err.code and err.fields
    } else {
      // recurly.js has filled in the 'token' field, so now we can submit the
      // form to your server; alternatively, you can access token.id and do
      // any processing you wish
      form.submit();
    }
  });
});

Recurly.js works with tokens, which represent secure and temporary storage for your customer's sensitive billing information. They are stored directly on Recurly servers to reduce your PCI exposure.

When your customers submit your billing form, you'll need to interrupt the submit and ask Recurly.js to create a token from the form. You may have noticed an additional hidden field in the form above, token. When you ask Recurly.js for a token during submit, it will automatically populate this field for you. After you get the token, you will submit it to your servers and use it there to talk to any endpoint in our API that accepts a billing_info.

This example demonstrates jQuery as an event-binding and DOM library; however, you may use any library you choose, or interact directly with the DOM (hard mode).

Reference

fn recurly.token

You must call recurly.token with your form element.

recurly.token(document.querySelector('form'), tokenHandler);

Using a handler function like this one:

function tokenHandler (err, token) {
  if (err) {
    // handle error using err.code and err.fields
  } else {
    // handle success using token.id
  }
}

Sends billing information to Recurly to store as a token, sending that token id back to you.

Param
Type
Description

form

HTMLFormElement

Parent form containing data-recurly fields.

callback

Function

Callback function to accept the returned token.

A callback is always required

Callback Arguments

Param
Type
Description

err

RecurlyError or null

A RecurlyError if an error occurred; otherwise null.

token

Object

An object containing a token id.

token.id

String

A token id.

Returns

Nothing.

recurly.bankAccount.token(API)

You may call recurly.bankAccount.token with a form element

recurly.bankAccount.token(document.querySelector('form'), tokenHandler);

Or with an Object

// alternatively..
var billingInfo = {
  // required attributes
  routing_number: '123456780',
  account_number: '111111111',
  account_number_confirmation: '111111111',
  account_type: 'checking',
  name_on_account: 'Pat Smith',

  // optional attributes
  address1: '123 Main St.',
  address2: 'Unit 1',
  city: 'Hope',
  state: 'WA',
  postal_code: '98552',
  country: 'US',
  vat_number: 'SE0000'
};

recurly.bankAccount.token(billingInfo, tokenHandler);

Both methods require using a handler function like this one

function tokenHandler (err, token) {
  if (err) {
    // handle error using err.code and err.fields
  } else {
    // handle success using token.id
  }
}

Sends bank account billing information to Recurly to store as a token, sending that token id back to you. Just as with card tokenization, there are two ways to call recurly.bankAccount.token: with a form, and with an object.

The simplest is to pass it a form element containing form fields with their corresponding data-recurly attributes.

Arguments (form)

Param
Type
Description

form

HTMLFormElement

Parent form containing data-recurly fields.

callback

Function

Callback function to accept the returned token.

Alternatively, you can call recurly.bankAccount.token with a plain JavaScript object. This allows a more direct interface to the payment flow, eliminating any need to use the DOM.

Arguments (object)

Param
Type
Description

options

Object

An object with billing information properties matching those [outlined above].

callback

Function

Callback function to accept the returned token.

A callback is always required

Callback Arguments

Param
Type
Description

err

RecurlyError or null

A RecurlyError if an error occurred; otherwise null.

token

Object

An object containing a token id.

id

String

A token id.

Returns

Nothing.

{"_id":"5b2d60111235f100031773b8","category":"5b2d60111235f1000317734d","parentDoc":null,"user":"55648cf93b87582b003ab8b1","project":"555fbba928249c1900618a82","version":"5b2d60111235f10003177402","updates":["5718f243459f6f0e0075070c"],"next":{"pages":[],"description":""},"createdAt":"2016-03-01T04:28:39.561Z","link_external":false,"link_url":"","githubsync":"","sync_unique":"","hidden":false,"api":{"results":{"codes":[{"name":"","code":"{}","language":"json","status":200},{"name":"","code":"{}","language":"json","status":400}]},"settings":"","auth":"required","params":[],"url":""},"isReference":false,"order":5,"body":"Create a new subscription with a token using one of our [client libraries](/docs/client-libraries) or [API v2](https://dev.recurly.com).\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"Recurly::Subscription.create! plan_code: :monthly_subscription,\\n  account: {\\n    account_code: 'pat_smith',\\n    currency: 'USD',\\n    billing_info: { token_id: 'TOKEN_ID' }\\n  }\",\n      \"language\": \"ruby\"\n    },\n    {\n      \"code\": \"subscription = recurly.Subscription(\\n  plan_code = 'monthly_subscription',\\n  currency = 'EUR',\\n  account = recurly.Account(\\n    account_code = 'pat_smith',\\n    billing_info = recurly.BillingInfo(token_id = 'TOKEN_ID')\\n  )\\n)\\nsubscription.save()\",\n      \"language\": \"python\"\n    },\n    {\n      \"code\": \"$subscription = new Recurly_Subscription();\\n$subscription->plan_code = 'monthly_subscription';\\n$subscription->currency = 'EUR';\\n\\n$subscription->account = new Recurly_Account();\\n$subscription->account->account_code = 'pat_smith';\\n$subscription->account->first_name = 'Pat';\\n$subscription->account->last_name = 'Smith';\\n$subscription->account->email = 'pat@enterpriseexecutive.com';\\n\\n$subscription->account->billing_info = new Recurly_BillingInfo();\\n$subscription->account->billing_info->token_id = 'TOKEN_ID';\\n\\n$subscription->create();\",\n      \"language\": \"php\"\n    },\n    {\n      \"code\": \"var plan = Plans.Get(\\\"monthly_subscription\\\");\\nvar account = new Account(\\\"pat_smith\\\");\\nvar billingInfo = new BillingInfo(account) { TokenId = \\\"TOKEN_ID\\\" };\\nvar subscription = new Subscription(account, plan, \\\"USD\\\");\\n\\nsubscription.Create();\",\n      \"language\": \"csharp\"\n    },\n    {\n      \"code\": \"$ curl https://:subdomain.recurly.com/v2/subscriptions \\\\\\n    -u API_KEY \\\\\\n    -X POST \\\\\\n    -d '<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?> \\\\\\n<subscription> \\\\\\n  <plan_code>monthly_subscription</plan_code> \\\\\\n  <currency>USD</currency> \\\\\\n  <account> \\\\\\n    <account_code>pat_smith</account_code> \\\\\\n    <email>pat@enterpriseexecutive.com</email> \\\\\\n    <first_name>Pat</first_name> \\\\\\n    <last_name>Smith</last_name> \\\\\\n    <billing_info> \\\\\\n      <token_id>TOKEN_ID</token_id> \\\\\\n    </billing_info> \\\\\\n  </account> \\\\\\n</subscription>'\\n\",\n      \"language\": \"curl\"\n    }\n  ]\n}\n[/block]\nOnce Recurly.js has stored your customer's sensitive data and given you a token reference, you will have 20 minutes to use it in our [API](https://dev.recurly.com). Expired tokens are permanently removed from the Recurly servers. Since tokens may be used to create charges in Recurly, be sure to keep them safe and only transmit them over a secure connection.\n[block:callout]\n{\n  \"type\": \"info\",\n  \"body\": \"Tokens expire after 20 minutes.\"\n}\n[/block]\nTokens can be used to populate any account Billing Info data through our API. Simply assign it to the Billing Info's `token_id` property and we'll do the rest.\n\n### These endpoints accept tokens within Billing Info.\n\n- Subscription [`create`](https://dev.recurly.com/docs/create-subscription)\n- Account [`create`](https://dev.recurly.com/docs/create-an-account), [`update`](https://dev.recurly.com/docs/update-account)\n- Billing Info [`update`](https://dev.recurly.com/docs/update-an-accounts-billing-info-token)\n- Transaction [`create`](https://dev.recurly.com/docs/create-transaction)\n[block:callout]\n{\n  \"type\": \"info\",\n  \"body\": \"If you use a token, no other attributes will be allowed on that Billing Info\\n  for that request.\"\n}\n[/block]","excerpt":"","slug":"recurly-js-using-a-token","type":"basic","title":"Using a Token","__v":0,"childrenPages":[]}

Using a Token


Create a new subscription with a token using one of our client libraries or API v2.

Recurly::Subscription.create! plan_code: :monthly_subscription,
  account: {
    account_code: 'pat_smith',
    currency: 'USD',
    billing_info: { token_id: 'TOKEN_ID' }
  }
subscription = recurly.Subscription(
  plan_code = 'monthly_subscription',
  currency = 'EUR',
  account = recurly.Account(
    account_code = 'pat_smith',
    billing_info = recurly.BillingInfo(token_id = 'TOKEN_ID')
  )
)
subscription.save()
$subscription = new Recurly_Subscription();
$subscription->plan_code = 'monthly_subscription';
$subscription->currency = 'EUR';

$subscription->account = new Recurly_Account();
$subscription->account->account_code = 'pat_smith';
$subscription->account->first_name = 'Pat';
$subscription->account->last_name = 'Smith';
$subscription->account->email = 'pat@enterpriseexecutive.com';

$subscription->account->billing_info = new Recurly_BillingInfo();
$subscription->account->billing_info->token_id = 'TOKEN_ID';

$subscription->create();
var plan = Plans.Get("monthly_subscription");
var account = new Account("pat_smith");
var billingInfo = new BillingInfo(account) { TokenId = "TOKEN_ID" };
var subscription = new Subscription(account, plan, "USD");

subscription.Create();
$ curl https://:subdomain.recurly.com/v2/subscriptions \
    -u API_KEY \
    -X POST \
    -d '<?xml version="1.0" encoding="UTF-8"?> \
<subscription> \
  <plan_code>monthly_subscription</plan_code> \
  <currency>USD</currency> \
  <account> \
    <account_code>pat_smith</account_code> \
    <email>pat@enterpriseexecutive.com</email> \
    <first_name>Pat</first_name> \
    <last_name>Smith</last_name> \
    <billing_info> \
      <token_id>TOKEN_ID</token_id> \
    </billing_info> \
  </account> \
</subscription>'

Once Recurly.js has stored your customer's sensitive data and given you a token reference, you will have 20 minutes to use it in our API. Expired tokens are permanently removed from the Recurly servers. Since tokens may be used to create charges in Recurly, be sure to keep them safe and only transmit them over a secure connection.

Tokens expire after 20 minutes.

Tokens can be used to populate any account Billing Info data through our API. Simply assign it to the Billing Info's token_id property and we'll do the rest.

These endpoints accept tokens within Billing Info.

If you use a token, no other attributes will be allowed on that Billing Info
for that request.

{"_id":"5b2d60111235f100031773b9","category":"5b2d60111235f1000317734d","project":"555fbba928249c1900618a82","user":"55648cf93b87582b003ab8b1","parentDoc":null,"version":"5b2d60111235f10003177402","updates":["59095077651f500f001dd3f6"],"next":{"pages":[],"description":""},"createdAt":"2016-03-01T18:53:08.841Z","link_external":false,"link_url":"","githubsync":"","sync_unique":"","hidden":false,"api":{"results":{"codes":[{"name":"","code":"{}","language":"json","status":200},{"name":"","code":"{}","language":"json","status":400}]},"settings":"","auth":"required","params":[],"url":""},"isReference":false,"order":6,"body":"[block:api-header]\n{\n  \"title\": \"Example RecurlyState object\",\n  \"sidebar\": true\n}\n[/block]\n\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"{\\n  fields: {\\n    card: {\\n      brand: 'visa',\\n      cvv: {\\n        empty: false,\\n        focus: false,\\n        valid: true\\n      },\\n      empty: true,\\n      expiry: {\\n        empty: false,\\n        focus: false,\\n        valid: true\\n      },\\n      firstSix: '411111',\\n      focus: false,\\n      lastFour: '1111',\\n      number: {\\n        empty: false,\\n        focus: false,\\n        valid: true\\n      },\\n      valid: false\\n    },\\n    number: {\\n      valid: false,\\n      firstSix: '',\\n      lastFour: '',\\n      brand: 'unknown',\\n      empty: true,\\n      length: 0,\\n      focus: false\\n    },\\n    month: {\\n      valid: false,\\n      empty: true,\\n      length: 0,\\n      focus: false\\n    },\\n    year: {\\n      // same as month\\n    },\\n    cvv: {\\n      // same as month\\n    }\\n  }\\n}\",\n      \"language\": \"javascript\"\n    }\n  ],\n  \"sidebar\": true\n}\n[/block]\nListen to events using Emitter methods\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"// Listen to the 'change' event\\nrecurly.on('change', changeHandler);\\n\\n// But we're feeling indecisive today. Let's detach this event\\nrecurly.off('change', changeHandler);\\n\\n// .once will listen for one event then detach itself\\nrecurly.once('field:submit', function () {\\n  $('#my-payment-form').submit();\\n});\\n\\nfunction changeHandler (state) {\\n  // state.fields\\n}\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\nA `Recurly` instance is an event emitter, and will emit events throughout the lifecycle of your customer's interaction with your payment form. Events can be attached using the `recurly.on` method and removed using `recurly.off`. The example to the right shows the various ways that you can attach and remove events.\n\n### `change`\n\nThis event is emitted whenever a customer changes the state of hosted card fields, those that you may not otherwise observe directly with DOM events. For example, if your customer types '4' into the number field, then the state of the number field will change, and the `change` event will emit.\n\nThe `change` event emits a `RecurlyState` object, whose values are demonstrated to the right. This will give you useful insight into the entire state of the recurly-controlled components of your payment form.\n\n### `field:submit`\n\nThis event is emitted when a user presses the `enter` key while they are focused on a hosted field. Since this action typically submits a form, we recommend performing a payment form submission when this event is emitted.\n\nNote that you can detect the brand of the credit card entered using the \"brand\" field in the state object above.","excerpt":"","slug":"recurly-js-events","type":"basic","title":"Events","__v":0,"childrenPages":[]}

Events


Listen to events using Emitter methods

// Listen to the 'change' event
recurly.on('change', changeHandler);

// But we're feeling indecisive today. Let's detach this event
recurly.off('change', changeHandler);

// .once will listen for one event then detach itself
recurly.once('field:submit', function () {
  $('#my-payment-form').submit();
});

function changeHandler (state) {
  // state.fields
}

A Recurly instance is an event emitter, and will emit events throughout the lifecycle of your customer's interaction with your payment form. Events can be attached using the recurly.on method and removed using recurly.off. The example to the right shows the various ways that you can attach and remove events.

change

This event is emitted whenever a customer changes the state of hosted card fields, those that you may not otherwise observe directly with DOM events. For example, if your customer types '4' into the number field, then the state of the number field will change, and the change event will emit.

The change event emits a RecurlyState object, whose values are demonstrated to the right. This will give you useful insight into the entire state of the recurly-controlled components of your payment form.

field:submit

This event is emitted when a user presses the enter key while they are focused on a hosted field. Since this action typically submits a form, we recommend performing a payment form submission when this event is emitted.

Note that you can detect the brand of the credit card entered using the "brand" field in the state object above.

Example RecurlyState object

{
  fields: {
    card: {
      brand: 'visa',
      cvv: {
        empty: false,
        focus: false,
        valid: true
      },
      empty: true,
      expiry: {
        empty: false,
        focus: false,
        valid: true
      },
      firstSix: '411111',
      focus: false,
      lastFour: '1111',
      number: {
        empty: false,
        focus: false,
        valid: true
      },
      valid: false
    },
    number: {
      valid: false,
      firstSix: '',
      lastFour: '',
      brand: 'unknown',
      empty: true,
      length: 0,
      focus: false
    },
    month: {
      valid: false,
      empty: true,
      length: 0,
      focus: false
    },
    year: {
      // same as month
    },
    cvv: {
      // same as month
    }
  }
}
{"_id":"5b2d60111235f100031773ba","category":"5b2d60111235f1000317734d","project":"555fbba928249c1900618a82","user":"57292bdb0388c70e00f3d8f3","parentDoc":null,"version":"5b2d60111235f10003177402","updates":[],"next":{"pages":[],"description":""},"createdAt":"2017-12-02T11:17:01.032Z","link_external":false,"link_url":"","githubsync":"","sync_unique":"","hidden":false,"api":{"results":{"codes":[{"status":200,"language":"json","code":"{}","name":""},{"status":400,"language":"json","code":"{}","name":""}]},"settings":"","auth":"required","params":[],"url":""},"isReference":false,"order":7,"body":"Recurly.js supports Apple Pay out of the box. To get started, ensure your site is [configured to accept Apple Pay transactions](https://docs.recurly.com/v1.0/docs/apple-pay-on-the-web).\n\nSetting up your Apple Pay integration in Recurly.js involves two parts: a) displaying the button, and b) invoking the purchase flow.\n\n## Displaying the button\n\nYour button styling needs to adhere to [Apple’s specifications](https://developer.apple.com/apple-pay/web-human-interface-guidelines/).\n\nSee Apple's documentation on [Displaying the Apple Pay Button](https://developer.apple.com/documentation/applepayjs/displaying_apple_pay_buttons) for guidelines on display and styling the button.\n\n## Invoking the purchase flow\n\nConfigure a new instance of  `recurly.ApplePay` as follows.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"var applePay = recurly.ApplePay({\\n  country: 'US',\\n  currency: 'USD',\\n  label: 'My Subscription', // This text will be displayed on the Apple Pay payment sheet as \\\"My Subscription\\\"\\n  total: '29.00'\\n});\\n\\n// When the ApplePay instance is ready, bind the Apple Pay button click\\n// to applePay.begin\\napplePay.ready(function () {\\n  $('#my-apple-pay-button').on('click', function () {\\n    applePay.begin();\\n  });\\n});\\n\\n// Handle errors. These may occur at any point in the Apple Pay flow\\napplePay.on('error', function (err) {\\n  // err.code, err.message\\n  console.error('Apple Pay error', err);\\n});\\n\\n// This will fire when the flow is completed and a token has been generated\\napplePay.on('token', function (token) {\\n  console.log('Apple Pay succeeded. Token:', token.id);\\n  // Submit the token to your server\\n});\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n### Additional configuration\n\nIf you are using the `recurly.Pricing` class to calculate checkout prices, you may pass your pricing instance instead of providing a total.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"var pricing = recurly.Pricing();\\n\\nvar applePay = recurly.ApplePay({\\n  // ...\\n  pricing: pricing\\n});\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\nTo provide additional customer data to tokens generated by `recurly.ApplePay`, you may pass a form reference. `recurly.ApplePay` will collect customer data from the form just as would occur during credit card tokenization. See [Getting a Token](doc:recurly-js-getting-a-token) for more information on building such a form. \n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"var applePay = recurly.ApplePay({\\n  // ...\\n  form: document.querySelector('#my-payment-form')\\n});\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n## Integration Notes\n\n  * Recurly.js will automatically pull in the billing info from the customer's Apple account if their Apple Pay setup is complete with full billing information in their Apple Wallet. If the user does **NOT** have a billing name or address attached to their card in their Apple Wallet, the Apple Pay flow will prompt the customer for a billing address.\n  * If you choose to include a Recurly.js payment form, any billing name or address fields entered on that form will be used instead of the address in the user's Apple Wallet; the token request will contain the fields entered on the payment form. If the form is completely empty of name and address inputs, the token request will contain the name and address chosen by the user during the Apple Pay flow.\n\n# Reference\n[block:html]\n{\n  \"html\": \"<h3>\\n  <span class=\\\"pg-type-big pg-type type-fn\\\">fn</span>\\n  recurly.ApplePay\\n</h2>\"\n}\n[/block]\n### Arguments\n[block:parameters]\n{\n  \"data\": {\n    \"0-0\": \"options\",\n    \"0-1\": \"Object\",\n    \"h-0\": \"Param\",\n    \"h-1\": \"Type\",\n    \"h-2\": \"Description\",\n    \"1-0\": \"options.country\",\n    \"2-0\": \"options.currency\",\n    \"3-0\": \"options.label\",\n    \"4-0\": \"[options.total]\",\n    \"5-0\": \"[options.pricing]\",\n    \"6-0\": \"[options.form]\",\n    \"1-1\": \"String\",\n    \"2-1\": \"String\",\n    \"3-1\": \"String\",\n    \"4-1\": \"String\",\n    \"5-1\": \"recurly.Pricing\",\n    \"6-1\": \"HTMLElement\",\n    \"4-2\": \"Total cost to display in the Apple Pay payment sheet. Required if options.pricing is not provided.\",\n    \"5-2\": \"If provided, will override options.total and provide the current total price on the Pricing instance when the Apple Pay flow is initiated.\",\n    \"6-2\": \"If provided, tokens generated by the `recurly.ApplePay` instance will include customer billing address from the form, overriding any billing address gathered from Apple Pay. See [Getting a Token](doc:recurly-js-getting-a-token) for all compatible fields.\",\n    \"3-2\": \"Purchase description to display in the Apple Pay payment sheet.\",\n    \"2-2\": \"ISO 4217 purchase currency (ex: 'USD')\",\n    \"1-2\": \"Your ISO 3166 country code (ex: 'US'). This is your country code as the merchant.\"\n  },\n  \"cols\": 3,\n  \"rows\": 7\n}\n[/block]\n### Returns\n\nA new `recurly.ApplePay` instance\n[block:html]\n{\n  \"html\": \"<h3>\\n  <span class=\\\"pg-type-big pg-type type-fn\\\">fn</span>\\n  applePay.ready\\n</h2>\"\n}\n[/block]\n### Arguments\n[block:parameters]\n{\n  \"data\": {\n    \"h-0\": \"Param\",\n    \"h-1\": \"Type\",\n    \"h-2\": \"Description\",\n    \"0-0\": \"callback\",\n    \"0-1\": \"Function\",\n    \"0-2\": \"Called when the ApplePay instance has completed initialization. Will immediately invoke if the instance is already initialized. The callback is called with no arguments.\"\n  },\n  \"cols\": 3,\n  \"rows\": 1\n}\n[/block]\n### Returns\n\nNothing.\n[block:html]\n{\n  \"html\": \"<h3>\\n  <span class=\\\"pg-type-big pg-type type-fn\\\">fn</span>\\n  applePay.begin\\n</h2>\"\n}\n[/block]\nInitiates Apple Pay payment sheet flow. Should be invoked by a user action, clicking the Apple Pay button on your payment page.\n\n### Arguments\n\nNone.\n\n### Returns\n\nNothing.\n\n## Events\n\n### `token`\n\nThis event is fired when the customer has completed the Apple Pay payment sheet flow. Recurly has received the payment details, and generated this token to be used in our API.\n\n#### Signature\n[block:parameters]\n{\n  \"data\": {\n    \"h-0\": \"Param\",\n    \"h-1\": \"Type\",\n    \"h-2\": \"Description\",\n    \"0-0\": \"token\",\n    \"0-1\": \"Object\",\n    \"1-0\": \"token.id\",\n    \"1-1\": \"String\",\n    \"1-2\": \"Token identifier to be sent to the API\"\n  },\n  \"cols\": 3,\n  \"rows\": 2\n}\n[/block]\n### `error`\n\nThis event is emitted when any error is encountered, whether during setup of the Apple Pay payment sheet, or during payment authorization. It will be useful to display errors to your customer if a problem occurs during the Apple Pay flow.\n\n#### Signature\n[block:parameters]\n{\n  \"data\": {\n    \"h-0\": \"Param\",\n    \"h-1\": \"Type\",\n    \"h-2\": \"Description\",\n    \"0-0\": \"error\",\n    \"0-1\": \"RecurlyError\",\n    \"0-2\": \"An error describing the issue that occurred.\"\n  },\n  \"cols\": 3,\n  \"rows\": 1\n}\n[/block]\n#### Error codes\n[block:parameters]\n{\n  \"data\": {\n    \"h-0\": \"Code\",\n    \"h-1\": \"Description\",\n    \"0-0\": \"apple-pay-init-error\",\n    \"h-2\": \"Additional Properties\",\n    \"0-2\": \"`err` the originating RecurlyError\",\n    \"0-1\": \"A configuration issue has prevented initialization\",\n    \"1-0\": \"apple-pay-not-configured\",\n    \"2-0\": \"apple-pay-configuration-invalid\",\n    \"3-0\": \"apple-pay-merchant-validation-error\",\n    \"4-0\": \"apple-pay-payment-failure\",\n    \"1-1\": \"Your site does not have a gateway which supports Apple Pay\",\n    \"2-1\": \"There is an issue with your Apple Pay authentication information. Check your certificate and key values in your gateway configuration.\",\n    \"3-1\": \"Apple encountered an error validating your merchant credentials\",\n    \"4-1\": \"An error has occurred during tokenization, preventing the payment authorization\"\n  },\n  \"cols\": 3,\n  \"rows\": 5\n}\n[/block]","excerpt":"Use Recurly.js to process Apple Pay transactions.","slug":"recurly-js-apple-pay","type":"basic","title":"Apple Pay","__v":0,"childrenPages":[]}

Apple Pay

Use Recurly.js to process Apple Pay transactions.

Recurly.js supports Apple Pay out of the box. To get started, ensure your site is configured to accept Apple Pay transactions.

Setting up your Apple Pay integration in Recurly.js involves two parts: a) displaying the button, and b) invoking the purchase flow.

Displaying the button

Your button styling needs to adhere to Apple’s specifications.

See Apple's documentation on Displaying the Apple Pay Button for guidelines on display and styling the button.

Invoking the purchase flow

Configure a new instance of recurly.ApplePay as follows.

var applePay = recurly.ApplePay({
  country: 'US',
  currency: 'USD',
  label: 'My Subscription', // This text will be displayed on the Apple Pay payment sheet as "My Subscription"
  total: '29.00'
});

// When the ApplePay instance is ready, bind the Apple Pay button click
// to applePay.begin
applePay.ready(function () {
  $('#my-apple-pay-button').on('click', function () {
    applePay.begin();
  });
});

// Handle errors. These may occur at any point in the Apple Pay flow
applePay.on('error', function (err) {
  // err.code, err.message
  console.error('Apple Pay error', err);
});

// This will fire when the flow is completed and a token has been generated
applePay.on('token', function (token) {
  console.log('Apple Pay succeeded. Token:', token.id);
  // Submit the token to your server
});

Additional configuration

If you are using the recurly.Pricing class to calculate checkout prices, you may pass your pricing instance instead of providing a total.

var pricing = recurly.Pricing();

var applePay = recurly.ApplePay({
  // ...
  pricing: pricing
});

To provide additional customer data to tokens generated by recurly.ApplePay, you may pass a form reference. recurly.ApplePay will collect customer data from the form just as would occur during credit card tokenization. See Getting a Token for more information on building such a form.

var applePay = recurly.ApplePay({
  // ...
  form: document.querySelector('#my-payment-form')
});

Integration Notes

  • Recurly.js will automatically pull in the billing info from the customer's Apple account if their Apple Pay setup is complete with full billing information in their Apple Wallet. If the user does NOT have a billing name or address attached to their card in their Apple Wallet, the Apple Pay flow will prompt the customer for a billing address.
  • If you choose to include a Recurly.js payment form, any billing name or address fields entered on that form will be used instead of the address in the user's Apple Wallet; the token request will contain the fields entered on the payment form. If the form is completely empty of name and address inputs, the token request will contain the name and address chosen by the user during the Apple Pay flow.

Reference

fn recurly.ApplePay

Arguments

Param
Type
Description

options

Object

options.country

String

Your ISO 3166 country code (ex: 'US'). This is your country code as the merchant.

options.currency

String

ISO 4217 purchase currency (ex: 'USD')

options.label

String

Purchase description to display in the Apple Pay payment sheet.

[options.total]

String

Total cost to display in the Apple Pay payment sheet. Required if options.pricing is not provided.

[options.pricing]

recurly.Pricing

If provided, will override options.total and provide the current total price on the Pricing instance when the Apple Pay flow is initiated.

[options.form]

HTMLElement

If provided, tokens generated by the recurly.ApplePay instance will include customer billing address from the form, overriding any billing address gathered from Apple Pay. See Getting a Token for all compatible fields.

Returns

A new recurly.ApplePay instance

fn applePay.ready

Arguments

Param
Type
Description

callback

Function

Called when the ApplePay instance has completed initialization. Will immediately invoke if the instance is already initialized. The callback is called with no arguments.

Returns

Nothing.

fn applePay.begin

Initiates Apple Pay payment sheet flow. Should be invoked by a user action, clicking the Apple Pay button on your payment page.

Arguments

None.

Returns

Nothing.

Events

token

This event is fired when the customer has completed the Apple Pay payment sheet flow. Recurly has received the payment details, and generated this token to be used in our API.

Signature

Param
Type
Description

token

Object

token.id

String

Token identifier to be sent to the API

error

This event is emitted when any error is encountered, whether during setup of the Apple Pay payment sheet, or during payment authorization. It will be useful to display errors to your customer if a problem occurs during the Apple Pay flow.

Signature

Param
Type
Description

error

RecurlyError

An error describing the issue that occurred.

Error codes

Code
Description
Additional Properties

apple-pay-init-error

A configuration issue has prevented initialization

err the originating RecurlyError

apple-pay-not-configured

Your site does not have a gateway which supports Apple Pay

apple-pay-configuration-invalid

There is an issue with your Apple Pay authentication information. Check your certificate and key values in your gateway configuration.

apple-pay-merchant-validation-error

Apple encountered an error validating your merchant credentials

apple-pay-payment-failure

An error has occurred during tokenization, preventing the payment authorization

{"_id":"5b2d60111235f100031773bb","category":"5b2d60111235f1000317734d","parentDoc":null,"project":"555fbba928249c1900618a82","user":"55648cf93b87582b003ab8b1","version":"5b2d60111235f10003177402","updates":["59403323f84a32001ba5a47a"],"next":{"pages":[],"description":""},"createdAt":"2016-03-01T18:54:55.886Z","link_external":false,"link_url":"","githubsync":"","sync_unique":"","hidden":false,"api":{"results":{"codes":[{"name":"","code":"{}","language":"json","status":200},{"name":"","code":"{}","language":"json","status":400}]},"settings":"","auth":"required","params":[],"url":""},"isReference":false,"order":8,"body":"A PayPal transaction is handled entirely within the PayPal checkout flow in a new window. Your customer will authorize a transaction within PayPal. Recurly will then record the authorization and return a Recurly token to you as it does for other payment methods. You will need to use the token within our API before it expires, and expired tokens cannot be retrieved.\n\nFirst, place a button on your page specifically for checking out with PayPal.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"<button>Checkout with PayPal</button>\",\n      \"language\": \"html\"\n    }\n  ]\n}\n[/block]\nNext, create a new `recurly.PayPal` instance.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"var paypal = recurly.PayPal({\\n  display: { displayName: ' My product ' }\\n});\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n**if you're processing PayPal transactions with Braintree**, you'll pass a [client authorization](https://developers.braintreepayments.com/guides/authorization/tokenization-key/javascript/v2#obtaining-a-tokenization-key) during instantiation:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"var paypal = recurly.PayPal({\\n  braintree: { clientAuthorization: MY_CLIENT_AUTHORIZATION }\\n});\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\nYour instance must then be set up to handle error scenarios and start the checkout flow.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"paypal.on('error', function (err) {\\n  // err.code\\n  // err.message\\n  // [err.cause] if there is an embedded error\\n});\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\nNext we must bind a listener to a user action on the button and have it trigger the `start` function on your `recurly.PayPal` instance. This will open the PayPal checkout flow.\n[block:callout]\n{\n  \"type\": \"info\",\n  \"body\": \"As with the rest of Recurly.js, there are no external dependencies. The example uses jQuery to demonstrate binding events, but this can be done any way you wish.\"\n}\n[/block]\n\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"$('#paypal-button').on('click', function () {\\n  paypal.start();\\n});\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n\n[block:callout]\n{\n  \"type\": \"warning\",\n  \"body\": \"the `start` function must be called within a user-initiated event like 'click' or 'touchend'\"\n}\n[/block]\nFinally, add a function to receive the token once your customer completes the checkout flow. At this point you will send the token id to your server to be used in the Recurly API to create a billing info for an account.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"paypal.on('token', function (token) {\\n  // token.id\\n});\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n# Reference\n[block:html]\n{\n  \"html\": \"<h3>\\n  <span class=\\\"pg-type-big pg-type type-fn\\\">fn</span>\\n  recurly.PayPal\\n</h2>\"\n}\n[/block]\n### Arguments\n[block:parameters]\n{\n  \"data\": {\n    \"h-0\": \"Param\",\n    \"h-1\": \"Type\",\n    \"h-2\": \"Description\",\n    \"0-0\": \"options\",\n    \"0-1\": \"`Object`\",\n    \"0-2\": \"Optional.\",\n    \"1-0\": \"options.braintree\",\n    \"1-1\": \"`Object`\",\n    \"1-2\": \"Optional. Braintree configuration.\",\n    \"2-0\": \"options.braintree.clientAuthorization\",\n    \"2-1\": \"`String`\",\n    \"2-2\": \"If using Braintree to proces PayPal transactions, provide your client authorization code here.\"\n  },\n  \"cols\": 3,\n  \"rows\": 3\n}\n[/block]\n### Returns\n\nA new `recurly.PayPal` instance\n[block:html]\n{\n  \"html\": \"<h3>\\n  <span class=\\\"pg-type-big pg-type type-fn\\\">fn</span>\\n  payPal.start\\n</h2>\"\n}\n[/block]\n### Arguments\n[block:parameters]\n{\n  \"data\": {\n    \"0-0\": \"options\",\n    \"0-1\": \"`Object`\",\n    \"0-2\": \"Optional\",\n    \"1-0\": \"options.description\",\n    \"1-1\": \"`String`\",\n    \"1-2\": \"Optional. In legacy PayPal flows, this description will be displayed during the checkout flow.\",\n    \"h-0\": \"Param\",\n    \"h-1\": \"Type\",\n    \"h-2\": \"Description\"\n  },\n  \"cols\": 3,\n  \"rows\": 2\n}\n[/block]\n### Returns\n\nNothing.\n\n## Events\n\n### `error`\n\nThis event is emitted when any error is encountered, whether during setup of the PayPal flow, or during the checkout process. It will be useful to display errors to your customer if a problem occurs during PayPal checkout.\n\n#### Signature\n[block:parameters]\n{\n  \"data\": {\n    \"0-0\": \"error\",\n    \"0-1\": \"`RecurlyError`\",\n    \"0-2\": \"An error describing the issue that occurred\",\n    \"h-0\": \"Param\",\n    \"h-1\": \"Type\",\n    \"h-2\": \"Description\"\n  },\n  \"cols\": 3,\n  \"rows\": 1\n}\n[/block]\n### `cancel`\n\nThis event is emitted when the customer has canceled the PayPal checkout flow before completion. You may wish to reset parts of your checkout experience if this occurs.\n\n#### Signature\n\nNone.\n\n### `token`\n\nThis event is fired when the customer has completed the PayPal checkout flow. Recurly has received the payment details, and generated this token to be used in our API.\n\n#### Signature\n[block:parameters]\n{\n  \"data\": {\n    \"0-0\": \"token\",\n    \"0-1\": \"`Object`\",\n    \"1-0\": \"token.id\",\n    \"1-1\": \"`String`\",\n    \"1-2\": \"Token identifier to be sent to the API\"\n  },\n  \"cols\": 3,\n  \"rows\": 2\n}\n[/block]","excerpt":"Use Recurly to process PayPal transactions using PayPal Business or Braintree.","slug":"recurly-js-paypal","type":"basic","title":"PayPal","__v":0,"childrenPages":[]}

PayPal

Use Recurly to process PayPal transactions using PayPal Business or Braintree.

A PayPal transaction is handled entirely within the PayPal checkout flow in a new window. Your customer will authorize a transaction within PayPal. Recurly will then record the authorization and return a Recurly token to you as it does for other payment methods. You will need to use the token within our API before it expires, and expired tokens cannot be retrieved.

First, place a button on your page specifically for checking out with PayPal.

<button>Checkout with PayPal</button>

Next, create a new recurly.PayPal instance.

var paypal = recurly.PayPal({
  display: { displayName: ' My product ' }
});

if you're processing PayPal transactions with Braintree, you'll pass a client authorization during instantiation:

var paypal = recurly.PayPal({
  braintree: { clientAuthorization: MY_CLIENT_AUTHORIZATION }
});

Your instance must then be set up to handle error scenarios and start the checkout flow.

paypal.on('error', function (err) {
  // err.code
  // err.message
  // [err.cause] if there is an embedded error
});

Next we must bind a listener to a user action on the button and have it trigger the start function on your recurly.PayPal instance. This will open the PayPal checkout flow.

As with the rest of Recurly.js, there are no external dependencies. The example uses jQuery to demonstrate binding events, but this can be done any way you wish.

$('#paypal-button').on('click', function () {
  paypal.start();
});

the start function must be called within a user-initiated event like 'click' or 'touchend'

Finally, add a function to receive the token once your customer completes the checkout flow. At this point you will send the token id to your server to be used in the Recurly API to create a billing info for an account.

paypal.on('token', function (token) {
  // token.id
});

Reference

fn recurly.PayPal

Arguments

Param
Type
Description

options

Object

Optional.

options.braintree

Object

Optional. Braintree configuration.

options.braintree.clientAuthorization

String

If using Braintree to proces PayPal transactions, provide your client authorization code here.

Returns

A new recurly.PayPal instance

fn payPal.start

Arguments

Param
Type
Description

options

Object

Optional

options.description

String

Optional. In legacy PayPal flows, this description will be displayed during the checkout flow.

Returns

Nothing.

Events

error

This event is emitted when any error is encountered, whether during setup of the PayPal flow, or during the checkout process. It will be useful to display errors to your customer if a problem occurs during PayPal checkout.

Signature

Param
Type
Description

error

RecurlyError

An error describing the issue that occurred

cancel

This event is emitted when the customer has canceled the PayPal checkout flow before completion. You may wish to reset parts of your checkout experience if this occurs.

Signature

None.

token

This event is fired when the customer has completed the PayPal checkout flow. Recurly has received the payment details, and generated this token to be used in our API.

Signature

token

Object

token.id

String

Token identifier to be sent to the API

{"_id":"5b2d60111235f100031773bc","category":"5b2d60111235f1000317734d","parentDoc":null,"project":"555fbba928249c1900618a82","user":"55648cf93b87582b003ab8b1","version":"5b2d60111235f10003177402","updates":["59094f4fb662a10f00aeed9e"],"next":{"pages":[],"description":""},"createdAt":"2016-03-01T18:58:37.649Z","link_external":false,"link_url":"","githubsync":"","sync_unique":"","hidden":false,"api":{"results":{"codes":[{"name":"","code":"{}","language":"json","status":200},{"name":"","code":"{}","language":"json","status":400}]},"settings":"","auth":"required","params":[],"url":""},"isReference":false,"order":9,"body":"Recurly automates complicated subscriptions, with many factors influencing total subscription price. With this in mind, Recurly.js provides a robust `recurly.Pricing` class designed to make determining actual subscription costs as simple and flexible as possible.\n\nA Recurly.js pricing instance can be attached to the form we created above, or to any other section of your page meant to display subscription pricing. Let's get to the specifics!\n\n# Reference\n[block:html]\n{\n  \"html\": \"<h3>\\n  <span class=\\\"pg-type-big pg-type type-fn\\\">fn</span>\\n  recurly.Pricing\\n</h2>\"\n}\n[/block]\n\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"var pricing = recurly.Pricing();\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\nCreates a `Pricing` instance.\n\n### No Arguments\n\n### Returns\n\nA new `recurly.Pricing` instance.\n[block:html]\n{\n  \"html\": \"<h3>\\n  <span class=\\\"pg-type-big pg-type type-fn\\\">fn</span>\\n  pricing.attach\\n</h2>\"\n}\n[/block]\nGiven the following example HTML structure\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"<section id=\\\"pricing\\\">\\n  <select data-recurly=\\\"plan\\\">\\n    <option value=\\\"basic\\\">Basic</option>\\n    <option value=\\\"notbasic\\\">Not Basic</option>\\n  </select>\\n  <input type=\\\"text\\\" data-recurly=\\\"coupon\\\">\\n</section>\",\n      \"language\": \"html\"\n    }\n  ]\n}\n[/block]\nUse `pricing.attach` to bind the `<section>` to the pricing calculator.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"var pricing = recurly.Pricing();\\n\\npricing.attach(document.querySelector('#pricing'));\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\nThis is the simplest way to use the pricing module. Simply pass a container element, and the pricing module with use all elements with a valid `data-recurly` attribute to determine price. When a value changes, the pricing module will automatically update its values. This allows your customers to manipulate a pricing form at will, and you will be able to react dynamically in any number of ways.\n\n### Arguments\n[block:parameters]\n{\n  \"data\": {\n    \"0-0\": \"container\",\n    \"0-1\": \"`HTMLElement`\",\n    \"0-2\": \"Parent element containing all `data-recurly` elements\",\n    \"h-0\": \"Param\",\n    \"h-1\": \"Type\",\n    \"h-2\": \"Description\"\n  },\n  \"cols\": 3,\n  \"rows\": 1\n}\n[/block]\n### Returns\n\nNothing.\n\n### Elements\n\nElements bound to a pricing module may be for either input or output.\n\nInput elements should be user-manipulable elements like `input` or `select`. If you want to input a value but not let a customer manipulate it, use an `<input type=\"hidden\">`.\n\n### Input Elements\n[block:parameters]\n{\n  \"data\": {\n    \"h-0\": \"Field Name\",\n    \"h-1\": \"Example Value\",\n    \"h-2\": \"Description\",\n    \"0-0\": \"plan\",\n    \"0-1\": \"`basic`\",\n    \"1-0\": \"plan_quantity\",\n    \"2-0\": \"coupon\",\n    \"3-0\": \"addon\",\n    \"4-0\": \"currency\",\n    \"5-0\": \"country\",\n    \"6-0\": \"postal_code\",\n    \"7-0\": \"tax_code\",\n    \"8-0\": \"vat_number\",\n    \"1-1\": \"`1`\",\n    \"2-1\": \"`15_off`\",\n    \"3-1\": \"`1`\",\n    \"4-1\": \"`USD`\",\n    \"5-1\": \"`US`\",\n    \"5-2\": \"[ISO 3166-1 alpha-2](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code.\",\n    \"4-2\": \"[ISO-4217 currency code](http://docs.recurly.com/currencies).\",\n    \"3-2\": \"Addon quantity. To identify the addon being modified, use the `data-recurly-addon` attribute to set the addon code.\",\n    \"2-2\": \"Coupon code.\",\n    \"1-2\": \"Play quantity. Defaults to 1 if not specified.\",\n    \"0-2\": \"Plan code.\",\n    \"6-2\": \"Customer postal code. Used primarily to compute taxes.\",\n    \"7-2\": \"Product tax code.\",\n    \"8-2\": \"Customer VAT number. Used for VAT exclusion.\",\n    \"6-1\": \"`90210`\",\n    \"7-1\": \"`digital`\",\n    \"8-1\": \"`SE0000`\",\n    \"9-0\": \"gift_card\",\n    \"9-1\": \"`518822D87268C142`\",\n    \"9-2\": \"Gift card's redemption code.\"\n  },\n  \"cols\": 3,\n  \"rows\": 10\n}\n[/block]\nOutput elements should be plain text elements like `output`, `span`, or `div`.\n\n### Output Elements\n[block:parameters]\n{\n  \"data\": {\n    \"h-0\": \"Field Name\",\n    \"h-1\": \"Example Output\",\n    \"h-2\": \"Description\",\n    \"0-0\": \"total_now\",\n    \"1-0\": \"subtotal_now\",\n    \"2-0\": \"addons_now\",\n    \"3-0\": \"discount_now\",\n    \"4-0\": \"setup_fee_now\",\n    \"5-0\": \"tax_now\",\n    \"6-0\": \"currency_code\",\n    \"7-0\": \"currency_symbol\",\n    \"7-1\": \"`$`, `€`\",\n    \"7-2\": \"Symbolic representation of `currency_code`.\",\n    \"6-1\": \"`USD`, `EUR`\",\n    \"6-2\": \"ISO-4217 currency code.\",\n    \"5-1\": \"`15.00`\",\n    \"5-2\": \"Total subscription taxation.\",\n    \"4-1\": \"`5.00`\",\n    \"4-2\": \"Subscription setup fee total.\",\n    \"3-1\": \"`5.00`\",\n    \"3-2\": \"Amount discounted with coupon use.\",\n    \"2-2\": \"Total addon cost.\",\n    \"2-1\": \"`10.00`\",\n    \"1-1\": \"`90.00`\",\n    \"1-2\": \"Subtotal of the following pricing components.\",\n    \"0-1\": \"`100.00`\",\n    \"0-2\": \"Total subscription cost due now.\",\n    \"8-0\": \"gift_card_now\",\n    \"9-0\": \"gift_card_next\",\n    \"8-1\": \"`75.00`\",\n    \"9-1\": \"`25.00`\",\n    \"8-2\": \"The gift card amount that will be applied to the purchase today.\",\n    \"9-2\": \"The remainder gift card amount that will be applied to the next renewal.\"\n  },\n  \"cols\": 3,\n  \"rows\": 10\n}\n[/block]\n\n[block:callout]\n{\n  \"type\": \"success\",\n  \"body\": \"`data-recurly` values ending in `_now` like `subtotal_now` have counterparts ending in `_next`. As you might expect, these correspond to the next billing cycle cost. These values are especially useful for plans with trial periods.\"\n}\n[/block]\n## Events\n[block:api-header]\n{\n  \"title\": \"Example Pricing State Object\",\n  \"sidebar\": true\n}\n[/block]\n\n[block:textarea]\n{\n  \"text\": \"emitted by the **change** event.\",\n  \"sidebar\": true\n}\n[/block]\n\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"{\\n  now: {\\n    subtotal: '25.00',\\n    addons: '0.00',\\n    discount: '0.00',\\n    setup_fee: '25.00',\\n    tax: '0.00',\\n    total: '25.00'\\n  },\\n  next: {\\n    subtotal: '10.00',\\n    addons: '0.00',\\n    discount: '0.00',\\n    tax: '0.00',\\n    total: '10.00'\\n  },\\n  base: {\\n    plan: {\\n      setup_fee: '25.00',\\n      unit: '10.00'\\n    },\\n    addons: {\\n      thing1: '14.00', // cost of one 'thing1' addon\\n      thing2: '8.00'\\n    },\\n  },\\n  currency: {\\n    code: 'USD',\\n    symbol: '$'\\n  }\\n}\",\n      \"language\": \"javascript\"\n    }\n  ],\n  \"sidebar\": true\n}\n[/block]\nPricing instances emit events when various values are set or the price changes.\n\nA `Pricing` instance itself behaves as an event emitter, where events can be attached using the `pricing.on` method and removed using `pricing.off`, similarly to how events are managed on `recurly`.\n\n### `Change`\n\nThis event is emitted whenever a pricing module has updated any of its pricing values. You can use this event to update your pricing display, compute total shopping costs, aggregate to analytics, etc.\n\nChange emits a price object, shown in detail to the right.\n\n### `set.*`\n\n`set.*` events are emitted when specific pricing objects change on a pricing module. For example, when a customer changes their plan, the pricing module will send `set.plan`. This is especially useful for updating checkout previews based on what the customer has selected as one example.\n[block:parameters]\n{\n  \"data\": {\n    \"0-0\": \"`set.plan`\",\n    \"1-0\": \"`set.price`\",\n    \"2-0\": \"`set.addon`\",\n    \"5-0\": \"`set.currency`\",\n    \"4-0\": \"`set.address`\",\n    \"3-0\": \"`set.coupon`\",\n    \"0-1\": \"Plan object.\",\n    \"1-1\": \"Price object.\",\n    \"2-1\": \"Addon object.\",\n    \"3-1\": \"Coupon object.\",\n    \"4-1\": \"Address object.\",\n    \"5-1\": \"Currency code.\",\n    \"6-0\": \"`set.tax`\",\n    \"6-1\": \"Tax object.\",\n    \"7-0\": \"`set.gift_card`\",\n    \"7-1\": \"Gift card object.\"\n  },\n  \"cols\": 2,\n  \"rows\": 8\n}\n[/block]\n## Pricing API\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"var pricing = recurly.Pricing();\\n\\npricing\\n  .plan('basic', { quantity: 1 })\\n  .currency('USD')\\n  .addon('addon1', { quantity: 2 })\\n  .coupon('coop')\\n\\t.giftcard('518822D87268C142')\\n  .address({\\n    country: 'US',\\n    postal_code: '90210'\\n  })\\n  .tax({\\n    tax_code: 'digital',\\n    vat_number: ''\\n  })\\n  .catch(function (err) {\\n    // err.code\\n  })\\n  .done(function (price) {\\n    // price object as emitted by 'change' event\\n  });\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\nThe pricing module can be manipulated with a set of direct method calls. This is useful if you would like to set up a complex pricing schema for your customers, or would just like to use a more programmatic method of determining subscription price. Events fire just as they normally would when using `pricing.attach`.\n\nNote that Recurly.js's DOM binding is one-way. Thus if you use the Pricing API on a pricing instance already attached to a container, the elements within _will not_ update with your Pricing API calls. If you would like two-way DOM binding, we suggest using a framework such as [AngularJS](https://angularjs.org/) and using the Pricing API without attaching it to a container.\n[block:callout]\n{\n  \"type\": \"success\",\n  \"body\": \"The example to the right demonstrates all the ways that a pricing module can be manipulated directly.\"\n}\n[/block]\n### PricingPromise\n\nEach Pricing API method will return a `PricingPromise`. This allows you to chain many asynchronous calls together without having to manage a complex chain of callbacks.\n\nYou don't need to worry much about the internals of a `PricingPromise`, as it is designed to stay out of your way and facilitate asynchronous calls for you.\n\nThe `catch` method, as shown in the example, is used to handle error scenarios, such as when an addon cannot be applied to the selected plan.\n[block:callout]\n{\n  \"type\": \"success\",\n  \"body\": \"At the end of a chain of pricing method calls, be sure to call `.done()` as this tells the pricing module to begin calculating, and gives you the subscription price.\"\n}\n[/block]","excerpt":"","slug":"recurly-js-pricing","type":"basic","title":"Pricing","__v":0,"childrenPages":[]}

Pricing


Recurly automates complicated subscriptions, with many factors influencing total subscription price. With this in mind, Recurly.js provides a robust recurly.Pricing class designed to make determining actual subscription costs as simple and flexible as possible.

A Recurly.js pricing instance can be attached to the form we created above, or to any other section of your page meant to display subscription pricing. Let's get to the specifics!

Reference

fn recurly.Pricing

var pricing = recurly.Pricing();

Creates a Pricing instance.

No Arguments

Returns

A new recurly.Pricing instance.

fn pricing.attach

Given the following example HTML structure

<section id="pricing">
  <select data-recurly="plan">
    <option value="basic">Basic</option>
    <option value="notbasic">Not Basic</option>
  </select>
  <input type="text" data-recurly="coupon">
</section>

Use pricing.attach to bind the <section> to the pricing calculator.

var pricing = recurly.Pricing();

pricing.attach(document.querySelector('#pricing'));

This is the simplest way to use the pricing module. Simply pass a container element, and the pricing module with use all elements with a valid data-recurly attribute to determine price. When a value changes, the pricing module will automatically update its values. This allows your customers to manipulate a pricing form at will, and you will be able to react dynamically in any number of ways.

Arguments

Param
Type
Description

container

HTMLElement

Parent element containing all data-recurly elements

Returns

Nothing.

Elements

Elements bound to a pricing module may be for either input or output.

Input elements should be user-manipulable elements like input or select. If you want to input a value but not let a customer manipulate it, use an <input type="hidden">.

Input Elements

Field Name
Example Value
Description

plan

basic

Plan code.

plan_quantity

1

Play quantity. Defaults to 1 if not specified.

coupon

15_off

Coupon code.

addon

1

Addon quantity. To identify the addon being modified, use the data-recurly-addon attribute to set the addon code.

currency

USD

country

US

ISO 3166-1 alpha-2 country code.

postal_code

90210

Customer postal code. Used primarily to compute taxes.

tax_code

digital

Product tax code.

vat_number

SE0000

Customer VAT number. Used for VAT exclusion.

gift_card

518822D87268C142

Gift card's redemption code.

Output elements should be plain text elements like output, span, or div.

Output Elements

Field Name
Example Output
Description

total_now

100.00

Total subscription cost due now.

subtotal_now

90.00

Subtotal of the following pricing components.

addons_now

10.00

Total addon cost.

discount_now

5.00

Amount discounted with coupon use.

setup_fee_now

5.00

Subscription setup fee total.

tax_now

15.00

Total subscription taxation.

currency_code

USD, EUR

ISO-4217 currency code.

currency_symbol

$,

Symbolic representation of currency_code.

gift_card_now

75.00

The gift card amount that will be applied to the purchase today.

gift_card_next

25.00

The remainder gift card amount that will be applied to the next renewal.

data-recurly values ending in _now like subtotal_now have counterparts ending in _next. As you might expect, these correspond to the next billing cycle cost. These values are especially useful for plans with trial periods.

Events

Pricing instances emit events when various values are set or the price changes.

A Pricing instance itself behaves as an event emitter, where events can be attached using the pricing.on method and removed using pricing.off, similarly to how events are managed on recurly.

Change

This event is emitted whenever a pricing module has updated any of its pricing values. You can use this event to update your pricing display, compute total shopping costs, aggregate to analytics, etc.

Change emits a price object, shown in detail to the right.

set.*

set.* events are emitted when specific pricing objects change on a pricing module. For example, when a customer changes their plan, the pricing module will send set.plan. This is especially useful for updating checkout previews based on what the customer has selected as one example.

set.plan

Plan object.

set.price

Price object.

set.addon

Addon object.

set.coupon

Coupon object.

set.address

Address object.

set.currency

Currency code.

set.tax

Tax object.

set.gift_card

Gift card object.

Pricing API

var pricing = recurly.Pricing();

pricing
  .plan('basic', { quantity: 1 })
  .currency('USD')
  .addon('addon1', { quantity: 2 })
  .coupon('coop')
	.giftcard('518822D87268C142')
  .address({
    country: 'US',
    postal_code: '90210'
  })
  .tax({
    tax_code: 'digital',
    vat_number: ''
  })
  .catch(function (err) {
    // err.code
  })
  .done(function (price) {
    // price object as emitted by 'change' event
  });

The pricing module can be manipulated with a set of direct method calls. This is useful if you would like to set up a complex pricing schema for your customers, or would just like to use a more programmatic method of determining subscription price. Events fire just as they normally would when using pricing.attach.

Note that Recurly.js's DOM binding is one-way. Thus if you use the Pricing API on a pricing instance already attached to a container, the elements within will not update with your Pricing API calls. If you would like two-way DOM binding, we suggest using a framework such as AngularJS and using the Pricing API without attaching it to a container.

The example to the right demonstrates all the ways that a pricing module can be manipulated directly.

PricingPromise

Each Pricing API method will return a PricingPromise. This allows you to chain many asynchronous calls together without having to manage a complex chain of callbacks.

You don't need to worry much about the internals of a PricingPromise, as it is designed to stay out of your way and facilitate asynchronous calls for you.

The catch method, as shown in the example, is used to handle error scenarios, such as when an addon cannot be applied to the selected plan.

At the end of a chain of pricing method calls, be sure to call .done() as this tells the pricing module to begin calculating, and gives you the subscription price.

Example Pricing State Object

emitted by the change event.

{
  now: {
    subtotal: '25.00',
    addons: '0.00',
    discount: '0.00',
    setup_fee: '25.00',
    tax: '0.00',
    total: '25.00'
  },
  next: {
    subtotal: '10.00',
    addons: '0.00',
    discount: '0.00',
    tax: '0.00',
    total: '10.00'
  },
  base: {
    plan: {
      setup_fee: '25.00',
      unit: '10.00'
    },
    addons: {
      thing1: '14.00', // cost of one 'thing1' addon
      thing2: '8.00'
    },
  },
  currency: {
    code: 'USD',
    symbol: '$'
  }
}
{"_id":"5b2d60111235f100031773bd","category":"5b2d60111235f1000317734d","project":"555fbba928249c1900618a82","user":"57292bdb0388c70e00f3d8f3","parentDoc":null,"version":"5b2d60111235f10003177402","updates":[],"next":{"pages":[],"description":""},"createdAt":"2017-12-02T10:05:55.084Z","link_external":false,"link_url":"","githubsync":"","sync_unique":"","hidden":false,"api":{"results":{"codes":[{"status":200,"language":"json","code":"{}","name":""},{"status":400,"language":"json","code":"{}","name":""}]},"settings":"","auth":"required","params":[],"url":""},"isReference":false,"order":10,"body":"Recurly.js provides a fraud protection suite with support for our [Fraud Management](https://docs.recurly.com/v1.0/docs/fraud-management) toolkit, [Kount](https://docs.recurly.com/v1.0/docs/kount) integration, and [Braintree](https://docs.recurly.com/v1.0/docs/additional#section-braintree) gateway integration.\n\nWith fraud protection enabled, tokens created with Recurly.js will include device data we use to analyze fraud risk and flag subsequent transactions accordingly. Configuration is simple.\n\n## Configuring Fraud Protection\n\nOnce you have enabled fraud protection on your site, modify your Recurly.js configuration call according to your fraud protection setup.\n\n### Recurly Fraud Management & Kount Integration\n\nRecurly.js will handle all device data collection when configured as follows.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"recurly.configure({\\n  // ...\\n  fraud: {\\n    kount: { dataCollector: true }\\n  }\\n  // ..\\n});\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\nThis will enable device data collection and automatically apply it to your tokens.\n\n### Braintree Gateway Fraud Integration\n\nFirst, you will need to collect device data [using the Braintree JavaScript client](https://developers.braintreepayments.com/guides/advanced-fraud-tools/client-side/javascript/v2). This is required by Braintree.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"// Collect device data using braintree client\\n// ...\\n\\nvar deviceData = braintreeInstance.deviceData;\\n\\nrecurly.configure({\\n  // ...\\n  fraud: {\\n    braintree: { deviceData: deviceData }\\n  }\\n  // ..\\n});\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\nThis will apply Braintree fraud data to your tokens generated by Recurly.js. Transactions created with those tokens will pass the fraud data to Braintree for fraud analysis.","excerpt":"","slug":"recurly-js-fraud","type":"basic","title":"Fraud","__v":0,"childrenPages":[]}

Fraud


Recurly.js provides a fraud protection suite with support for our Fraud Management toolkit, Kount integration, and Braintree gateway integration.

With fraud protection enabled, tokens created with Recurly.js will include device data we use to analyze fraud risk and flag subsequent transactions accordingly. Configuration is simple.

Configuring Fraud Protection

Once you have enabled fraud protection on your site, modify your Recurly.js configuration call according to your fraud protection setup.

Recurly Fraud Management & Kount Integration

Recurly.js will handle all device data collection when configured as follows.

recurly.configure({
  // ...
  fraud: {
    kount: { dataCollector: true }
  }
  // ..
});

This will enable device data collection and automatically apply it to your tokens.

Braintree Gateway Fraud Integration

First, you will need to collect device data using the Braintree JavaScript client. This is required by Braintree.

// Collect device data using braintree client
// ...

var deviceData = braintreeInstance.deviceData;

recurly.configure({
  // ...
  fraud: {
    braintree: { deviceData: deviceData }
  }
  // ..
});

This will apply Braintree fraud data to your tokens generated by Recurly.js. Transactions created with those tokens will pass the fraud data to Braintree for fraud analysis.

{"_id":"5b2d60111235f100031773be","category":"5b2d60111235f1000317734d","parentDoc":null,"project":"555fbba928249c1900618a82","user":"55648cf93b87582b003ab8b1","version":"5b2d60111235f10003177402","updates":[],"next":{"pages":[],"description":""},"createdAt":"2016-03-01T19:17:35.326Z","link_external":false,"link_url":"","githubsync":"","sync_unique":"","hidden":false,"api":{"results":{"codes":[{"code":"{}","language":"json","status":200,"name":""},{"name":"","code":"{}","language":"json","status":400}]},"settings":"","auth":"required","params":[],"url":""},"isReference":false,"order":11,"body":"Recurly.js bundles a few helpful methods for validating payment information prior to processing. These methods are used when generating tokens, but you can also use them to enhance your form validations and checkout flow.\n\nIt is also possible to inspect the validation state of hosted fields as your customer types, by listening to the ['change' event](doc:events).\n\n# Reference\n[block:html]\n{\n  \"html\": \"<h3>\\n  <span class=\\\"pg-type-big pg-type type-fn\\\">fn</span>\\n  recurly.bankAccount.bankInfo\\n</h2>\"\n}\n[/block]\nRetrieves bank info based from a given routing number.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"recurly.bankAccount.bankInfo({ routingNumber: '123456780' }, function (err, bankInfo) {\\n  if (err) {\\n    // err.code, err.message\\n  } else {\\n    // bankInfo.bank_name\\n  }\\n});\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n### Arguments\n[block:parameters]\n{\n  \"data\": {\n    \"h-0\": \"Param\",\n    \"h-1\": \"Type\",\n    \"h-2\": \"Description\",\n    \"0-0\": \"options\",\n    \"0-1\": \"`Object`\",\n    \"0-2\": \"\",\n    \"1-0\": \"options.routingNumber\",\n    \"1-1\": \"`String`\",\n    \"1-2\": \"The routing number for a bank (ex: '123456780')\",\n    \"2-0\": \"callback\",\n    \"2-1\": \"`Function`\"\n  },\n  \"cols\": 3,\n  \"rows\": 3\n}\n[/block]\n### Callback signature\n[block:parameters]\n{\n  \"data\": {\n    \"h-0\": \"Param\",\n    \"h-1\": \"Type\",\n    \"h-2\": \"Description\",\n    \"0-0\": \"err\",\n    \"0-1\": \"`RecurlyError` or `undefined`\",\n    \"0-2\": \"Error. Usually `invalid-routing-number`\",\n    \"1-1\": \"`Object`\",\n    \"1-2\": \"\",\n    \"1-0\": \"bankInfo\",\n    \"2-0\": \"bankInfo.bank_name\",\n    \"2-1\": \"`String`\",\n    \"2-2\": \"Bank institution name (ex: `Bank of Recurly`)\"\n  },\n  \"cols\": 3,\n  \"rows\": 3\n}\n[/block]","excerpt":"","slug":"recurly-js-validation","type":"basic","title":"Validation","__v":0,"childrenPages":[]}

Validation


Recurly.js bundles a few helpful methods for validating payment information prior to processing. These methods are used when generating tokens, but you can also use them to enhance your form validations and checkout flow.

It is also possible to inspect the validation state of hosted fields as your customer types, by listening to the 'change' event.

Reference

fn recurly.bankAccount.bankInfo

Retrieves bank info based from a given routing number.

recurly.bankAccount.bankInfo({ routingNumber: '123456780' }, function (err, bankInfo) {
  if (err) {
    // err.code, err.message
  } else {
    // bankInfo.bank_name
  }
});

Arguments

Param
Type
Description

options

Object

options.routingNumber

String

The routing number for a bank (ex: '123456780')

callback

Function

Callback signature

Param
Type
Description

err

RecurlyError or undefined

Error. Usually invalid-routing-number

bankInfo

Object

bankInfo.bank_name

String

Bank institution name (ex: Bank of Recurly)

{"_id":"5b2d60111235f100031773bf","category":"5b2d60111235f1000317734d","parentDoc":null,"user":"55648cf93b87582b003ab8b1","project":"555fbba928249c1900618a82","version":"5b2d60111235f10003177402","updates":[],"next":{"pages":[],"description":""},"createdAt":"2016-03-01T19:19:09.515Z","link_external":false,"link_url":"","githubsync":"","sync_unique":"","hidden":false,"api":{"results":{"codes":[{"name":"","code":"{}","language":"json","status":200},{"name":"","code":"{}","language":"json","status":400}]},"settings":"","auth":"required","params":[],"url":""},"isReference":false,"order":12,"body":"[block:api-header]\n{\n  \"title\": \"Example RecurlyError object\",\n  \"sidebar\": true\n}\n[/block]\n\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"{\\n  name: 'validation',\\n  code: 'validation',\\n  message: 'There was an error validating your request.',\\n  fields: [\\n    'number',\\n    'year'\\n  ]\\n}\",\n      \"language\": \"javascript\"\n    }\n  ],\n  \"sidebar\": true\n}\n[/block]\nErrors are encapsulated by a `RecurlyError`, which contains a few standard properties to help you diagnose error cases and inform your customers accordingly.\n\nErrors will be thrown if the exception will prevent proper execution. If an error can be recovered, it will be passed to the proper error handling event listener, callback, or `PricingPromise` handler for you to inspect.\n\n### Best Practices\n\nThe `message` property contains diagnostic information intended to help you diagnose problems with the form, and we do not recommend displaying its contents to your customers.\n\nTo provide the best customer experience, we recommend that you provide your own error text to be displayed, based on the error code you receive.\n\n### Error Codes\n\n## Configuration\n[block:parameters]\n{\n  \"data\": {\n    \"h-0\": \"Code\",\n    \"h-1\": \"Description\",\n    \"0-0\": \"not-configured\",\n    \"1-0\": \"missing-public-key\",\n    \"2-0\": \"invalid-public-key\",\n    \"3-0\": \"missing-hosted-field-target\",\n    \"4-0\": \"\",\n    \"0-1\": \"This error appears when you try to perform an operation without first calling [`recurly.configure`](#configure).\",\n    \"2-1\": \"Check the `publicKey` to ensure it matches that of your admin app's [API Access section](https://app.recurly.com/go/developer/api_access).\",\n    \"1-1\": \"When you call [`recurly.configure`](#configure), you must do so with a `publicKey` property.\",\n    \"3-1\": \"This is thrown when the target element for a hosted payment field cannot be found on the page. Check the error message to check the selector being used, then check your page to ensure the element is present when `recurly.configure` is called.\",\n    \"4-1\": \"\"\n  },\n  \"cols\": 2,\n  \"rows\": 4\n}\n[/block]\n## Tokenization\n[block:parameters]\n{\n  \"data\": {\n    \"h-0\": \"Code\",\n    \"h-1\": \"Description\",\n    \"0-0\": \"validation\",\n    \"1-0\": \"invalid-parameter\",\n    \"2-0\": \"api-error\",\n    \"3-0\": \"\",\n    \"1-1\": \"Occurs when a tokenization parameter does not pass our internal validations. Check the `fields` property to determine which fields caused the error.\",\n    \"2-1\": \"A request to the Recurly API has encountered an issue. This too can indicate many possible issues, and we recommend inspecting the `message` and `fields` properties for more information.\",\n    \"3-1\": \"\",\n    \"0-1\": \"A request validation error has occurred. This can indicate many possible issues, and you should check the `fields` property to determine which fields caused the error.\"\n  },\n  \"cols\": 2,\n  \"rows\": 3\n}\n[/block]\n## Pricing\n[block:parameters]\n{\n  \"data\": {\n    \"h-0\": \"Code\",\n    \"h-1\": \"Description\",\n    \"0-0\": \"not-found\",\n    \"1-0\": \"missing-plan\",\n    \"2-0\": \"invalid-addon\",\n    \"3-0\": \"invalid-currency\",\n    \"5-0\": \"\",\n    \"5-1\": \"\",\n    \"3-1\": \"Similarly, if a currency is requested which is not valid for the selected plan.\",\n    \"2-1\": \"Occurs when an addon is added to a [`Pricing`](#pricing) instance but is not valid for the instance's selected plan.\",\n    \"1-1\": \"A [`Pricing`](#pricing) instance will emit this if a plan has not been specified before trying to set a proeprty that depends on a plan, such as a coupon or addon.\",\n    \"0-1\": \"This happens when a nonexistent plan is requested.\",\n    \"4-0\": \"gift-card-currency-mismatch\",\n    \"4-1\": \"Occurs when a gift card is redeemed with a currency that doesn't match the instance's configured currency.\"\n  },\n  \"cols\": 2,\n  \"rows\": 5\n}\n[/block]\n## PayPal\n[block:parameters]\n{\n  \"data\": {\n    \"0-0\": \"paypal-not-configured\",\n    \"0-1\": \"In order to perform a PayPal transaction, your site must be configured to accept PayPal reference\",\n    \"1-1\": \"The customer canceled the PayPal agreement flow.\",\n    \"2-1\": \"A generic PayPal error has occurred. Inspect `message` to learn more.\",\n    \"3-1\": \"The bank routing number is not valid\",\n    \"3-0\": \"invalid-routing-number\",\n    \"2-0\": \"paypal-error\",\n    \"1-0\": \"paypal-canceled\",\n    \"h-0\": \"Code\",\n    \"h-1\": \"Description\"\n  },\n  \"cols\": 2,\n  \"rows\": 4\n}\n[/block]","excerpt":"","slug":"recurly-js-errors","type":"basic","title":"Errors","__v":0,"childrenPages":[]}

Errors


Errors are encapsulated by a RecurlyError, which contains a few standard properties to help you diagnose error cases and inform your customers accordingly.

Errors will be thrown if the exception will prevent proper execution. If an error can be recovered, it will be passed to the proper error handling event listener, callback, or PricingPromise handler for you to inspect.

Best Practices

The message property contains diagnostic information intended to help you diagnose problems with the form, and we do not recommend displaying its contents to your customers.

To provide the best customer experience, we recommend that you provide your own error text to be displayed, based on the error code you receive.

Error Codes

Configuration

Code
Description

not-configured

This error appears when you try to perform an operation without first calling recurly.configure.

missing-public-key

When you call recurly.configure, you must do so with a publicKey property.

invalid-public-key

Check the publicKey to ensure it matches that of your admin app's API Access section.

missing-hosted-field-target

This is thrown when the target element for a hosted payment field cannot be found on the page. Check the error message to check the selector being used, then check your page to ensure the element is present when recurly.configure is called.

Tokenization

Code
Description

validation

A request validation error has occurred. This can indicate many possible issues, and you should check the fields property to determine which fields caused the error.

invalid-parameter

Occurs when a tokenization parameter does not pass our internal validations. Check the fields property to determine which fields caused the error.

api-error

A request to the Recurly API has encountered an issue. This too can indicate many possible issues, and we recommend inspecting the message and fields properties for more information.

Pricing

Code
Description

not-found

This happens when a nonexistent plan is requested.

missing-plan

A Pricing instance will emit this if a plan has not been specified before trying to set a proeprty that depends on a plan, such as a coupon or addon.

invalid-addon

Occurs when an addon is added to a Pricing instance but is not valid for the instance's selected plan.

invalid-currency

Similarly, if a currency is requested which is not valid for the selected plan.

gift-card-currency-mismatch

Occurs when a gift card is redeemed with a currency that doesn't match the instance's configured currency.

PayPal

Code
Description

paypal-not-configured

In order to perform a PayPal transaction, your site must be configured to accept PayPal reference

paypal-canceled

The customer canceled the PayPal agreement flow.

paypal-error

A generic PayPal error has occurred. Inspect message to learn more.

invalid-routing-number

The bank routing number is not valid

Example RecurlyError object

{
  name: 'validation',
  code: 'validation',
  message: 'There was an error validating your request.',
  fields: [
    'number',
    'year'
  ]
}
{"_id":"5b2d60111235f100031773c0","category":"5b2d60111235f1000317734d","parentDoc":null,"project":"555fbba928249c1900618a82","user":"55648cf93b87582b003ab8b1","version":"5b2d60111235f10003177402","updates":["582136261142c82700b03347"],"next":{"pages":[],"description":""},"createdAt":"2016-03-01T19:35:36.709Z","link_external":false,"link_url":"","githubsync":"","sync_unique":"","hidden":false,"api":{"results":{"codes":[{"name":"","code":"{}","language":"json","status":200},{"language":"json","status":400,"name":"","code":"{}"}]},"settings":"","auth":"required","params":[],"url":""},"isReference":false,"order":13,"body":"### Integration examples\n\nWe've prepared a full suite of example integrations for *Ruby*, *Node.js*, *Python*, and *PHP* using popular web frameworks for each language. These examples demonstrate the simplest method of integration, with a no-frills UI.\n\n[Code on GitHub](https://github.com/recurly/recurly-js-examples)","excerpt":"","slug":"recurly-js-examples","type":"basic","title":"Examples","__v":0,"childrenPages":[]}

Examples


Integration examples

We've prepared a full suite of example integrations for Ruby, Node.js, Python, and PHP using popular web frameworks for each language. These examples demonstrate the simplest method of integration, with a no-frills UI.

Code on GitHub

{"_id":"5b2d60111235f100031773c1","category":"5b2d60111235f1000317734d","parentDoc":null,"project":"555fbba928249c1900618a82","user":"55648cf93b87582b003ab8b1","version":"5b2d60111235f10003177402","updates":[],"next":{"pages":[],"description":""},"createdAt":"2016-03-01T19:37:11.437Z","link_external":false,"link_url":"","githubsync":"","sync_unique":"","hidden":false,"api":{"results":{"codes":[{"status":200,"name":"","code":"{}","language":"json"},{"name":"","code":"{}","language":"json","status":400}]},"settings":"","auth":"required","params":[],"url":""},"isReference":false,"order":14,"body":"Recurly.js supports Chrome, Firefox, Safari, iOS, and IE 10+.\n\nWe're also here to lend a hand on any Recurly.js integration questions! You can get help from us in a handful of ways:\n\n* Find us and other fellow developers in [#recurly](irc://chat.freenode.net:+6697/recurly) on freenode to chat in real-time.\n* Browse and post questions on [Stackoverflow](http://stackoverflow.com/questions/tagged/recurly). We check these regularly.\n* Take a look at the code on [GitHub](https://github.com/recurly/recurly-js). We welcome bug reports through Issues and contributions through Pull Requests.\n\nFor other Recurly related questions, please contact [support@recurly.com](https://support.recurly.com) for help with your account or other general questions.\n\nFor copies of documentation for previous versions of Recurly.js, please contact support.","excerpt":"","slug":"recurly-js-support","type":"basic","title":"Support","__v":0,"childrenPages":[]}

Support


Recurly.js supports Chrome, Firefox, Safari, iOS, and IE 10+.

We're also here to lend a hand on any Recurly.js integration questions! You can get help from us in a handful of ways:

  • Find us and other fellow developers in #recurly on freenode to chat in real-time.
  • Browse and post questions on Stackoverflow. We check these regularly.
  • Take a look at the code on GitHub. We welcome bug reports through Issues and contributions through Pull Requests.

For other Recurly related questions, please contact support@recurly.com for help with your account or other general questions.

For copies of documentation for previous versions of Recurly.js, please contact support.

{"_id":"5b2d60111235f1000317739d","category":"5b2d60111235f1000317734e","project":"555fbba928249c1900618a82","user":"55957fd09b8d0a25005a7d30","parentDoc":null,"version":"5b2d60111235f10003177402","updates":[],"next":{"pages":[],"description":""},"createdAt":"2017-05-16T20:47:47.026Z","link_external":false,"link_url":"","githubsync":"","sync_unique":"","hidden":false,"api":{"method":"post","results":{"codes":[{"name":"","code":"<invoice_collection>\n  <charge_invoice>\n    <account href=\"https://your-subdomain.recurly.com/v2/accounts/1\"/>\n    <subscriptions href=\"https://your-subdomain.recurly.com/v2/invoices/1007/subscriptions\"/>\n    <address>\n      <address1>123 Main St.</address1>\n      <address2 nil=\"nil\"/>\n      <city>San Francisco</city>\n      <state>CA</state>\n      <zip>94105</zip>\n      <country>US</country>\n      <phone nil=\"nil\"/>\n    </address>\n    <uuid>37c0057d2f641f4e2fcbda4b5b833633</uuid>\n    <state>paid</state>\n    <invoice_number_prefix/>\n    <invoice_number type=\"integer\">1007</invoice_number>\n    <po_number nil=\"nil\"/>\n    <vat_number nil=\"nil\"/>\n    <subtotal_in_cents type=\"integer\">2000</subtotal_in_cents>\n    <discount_in_cents type=\"integer\">0</discount_in_cents>\n    <due_on type=\"datetime\">2018-01-30T21:11:50Z</due_on>\n    <balance_in_cents type=\"integer\">0</balance_in_cents>\n    <type>charge</type>\n    <origin>purchase</origin>\n    <credit_invoices href=\"https://your-subdomain.recurly.com/v2/invoices/1325/credit_invoices\"/>\n    <refundable_total_in_cents type=\"integer\">2000</refundable_total_in_cents>\n    <credit_payments type=\"array\">\n    </credit_payments>\n    <tax_in_cents type=\"integer\">424</tax_in_cents>\n    <total_in_cents type=\"integer\">5274</total_in_cents>\n    <currency>EUR</currency>\n    <created_at type=\"datetime\">2016-08-03T16:26:26Z</created_at>\n    <updated_at type=\"datetime\">2016-08-03T16:26:26Z</updated_at>\n    <closed_at type=\"datetime\">2016-08-03T16:26:26Z</closed_at>\n    <terms_and_conditions nil=\"nil\"/>\n    <customer_notes nil=\"nil\"/>\n    <tax_type>usst</tax_type>\n    <tax_region>CA</tax_region>\n    <tax_rate type=\"float\">0.0875</tax_rate>\n    <net_terms type=\"integer\">0</net_terms>\n    <collection_method>automatic</collection_method>\n    <redemptions href=\"https://your-subdomain.recurly.com/v2/invoices/1007/redemptions\"/>\n    <line_items type=\"array\">\n      <adjustment href=\"https://your-subdomain.recurly.com/v2/adjustments/37c0057d2a3ace0c3f3d674ae89fdabd\" type=\"charge\">\n        <account href=\"https://your-subdomain.recurly.com/v2/accounts/1\"/>\n        <invoice href=\"https://your-subdomain.recurly.com/v2/invoices/1007\"/>\n        <subscription href=\"https://your-subdomain.recurly.com/v2/subscriptions/37c0057cb105f67b6b8a1146f7b59c41\"/>\n        <uuid>37c0057d2a3ace0c3f3d674ae89fdabd</uuid>\n        <state>invoiced</state>\n        <description>Setup fee: Gold plan</description>\n        <accounting_code nil=\"nil\"/>\n        <product_code>gold</product_code>\n        <origin>setup_fee</origin>\n        <unit_amount_in_cents type=\"integer\">800</unit_amount_in_cents>\n        <quantity type=\"integer\">1</quantity>\n        <discount_in_cents type=\"integer\">0</discount_in_cents>\n        <tax_in_cents type=\"integer\">70</tax_in_cents>\n        <total_in_cents type=\"integer\">870</total_in_cents>\n        <currency>EUR</currency>\n        <taxable type=\"boolean\">false</taxable>\n        <tax_type>usst</tax_type>\n        <tax_region>CA</tax_region>\n        <tax_rate type=\"float\">0.0875</tax_rate>\n        <tax_exempt type=\"boolean\">false</tax_exempt>\n        <tax_code nil=\"nil\"/>\n        <shipping_address>\n          <first_name>Lon</first_name>\n          <last_name>Doner</last_name>\n          <address1>400 Alabama St</address1>\n          <address2></address2>\n          <city>San Francisco</city>\n          <state>CA</state>\n          <zip>94110</zip>\n          <country>US</country>\n          <phone></phone>\n          <nickname>home</nickname>\n        </shipping_address>\n        <start_date type=\"datetime\">2016-08-03T16:26:26Z</start_date>\n        <end_date nil=\"nil\"/>\n        <created_at type=\"datetime\">2016-08-03T16:26:26Z</created_at>\n        <updated_at type=\"datetime\">2016-08-03T16:26:26Z</updated_at>\n        <revenue_schedule_type>evenly</revenue_schedule_type>\n      </adjustment>\n      <!-- Continued... -->\n    </line_items>\n    <transactions type=\"array\">\n      <!-- Detail. -->\n    </transactions>\n    <a name=\"refund\" href=\"https://your-subdomain.recurly.com/v2/invoices/1007/refund\" method=\"post\"/>\n  </charge_invoice>\n  <credit_invoices type=\"array\">\n  </credit_invoices>\n</invoice_collection>","language":"xml","status":200}]},"settings":"","examples":{"codes":[{"code":"<purchase>\n  <collection_method>automatic</collection_method>\n  <currency>USD</currency>\n  <customer_notes>Some notes for the customer.</customer_notes>\n  <terms_and_conditions>Our company terms and conditions.</terms_and_conditions>\n  <vat_reverse_charge_notes>Vat reverse charge notes.</vat_reverse_charge_notes>\n  <account>\n    <account_code>c442b36c-c64f-41d7-b8e1-9c04e7a6ff82</account_code>\n    <shipping_addresses>\n      <shipping_address>\n        <first_name>Lon</first_name>\n        <last_name>Doner</last_name>        \n        <address1>221B Baker St.</address1>\n        <city>London</city>\n        <state></state>\n        <zip>W1K 6AH</zip>\n        <country>GB</country>\n        <nickname>Home</nickname>\n      </shipping_address>\n    </shipping_addresses>\n    <billing_info>\n      <address1>400 Alabama St</address1>\n      <city>San Francisco</city>\n      <country>US</country>\n      <first_name>Benjamin</first_name>\n      <last_name>Du Monde</last_name>\n      <month>12</month>\n      <number>4111-1111-1111-1111</number>\n      <state>CA</state>\n      <year>2019</year>\n      <zip>94110</zip>\n    </billing_info>\n  </account>\n  <adjustments>\n    <adjustment>\n      <product_code>4549449c-5870-4845-b672-1d07f15e87dd</product_code>\n      <quantity>1</quantity>\n      <revenue_schedule_type>at_invoice</revenue_schedule_type>\n      <unit_amount_in_cents>1000</unit_amount_in_cents>\n      <description>Description of this adjustment</description>\n    </adjustment>\n  </adjustments>\n  <subscriptions>\n    <subscription>\n      <plan_code>plan1</plan_code>\n    </subscription>\n  </subscriptions>\n  <coupon_codes>\n  \t<coupon_code>coupon1</coupon_code>\n    <coupon_code>coupon2</coupon_code>\n  </coupon_codes>\n  <gift_card>\n    <redemption_code>ABC1234</redemption_code>\n  </gift_card>\n</purchase>","language":"xml"},{"code":"require 'securerandom'\n\npurchase = Recurly::Purchase.new({\n  currency: 'USD',\n  collection_method: :automatic,\n  account: {\n    account_code: SecureRandom.uuid,\n    billing_info: {\n      first_name: 'Benjamin',\n      last_name: 'Du Monde',\n      address1: '400 Alabama St',\n      city: 'San Francisco',\n      state: 'CA',\n      zip: '94110',\n      country: 'US',\n      number: '4111-1111-1111-1111',\n      month: 12,\n      year: 2019,\n    },\n    shipping_addresses: [\n      {\n        first_name: 'Lon',\n        last_name: 'Dorner',\n        address1: '400 Alabama St',\n        city: 'San Francisco',\n        state: 'CA',\n        zip: '94110',\n        country: 'US',\n        nickname: 'home',\n      }\n    ]\n  },\n  subscriptions: [\n    {\n      plan_code: \"gold\",\n    }\n  ],\n  adjustments: [\n    {product_code: SecureRandom.uuid, unit_amount_in_cents: 1_000, quantity: 1, revenue_schedule_type: :at_invoice},\n  ],\n  coupon_codes: [\n    \"COUPON123\",\n    \"COUPON345\",\n  ],\n  gift_card: {\n    redemption_code: \"BC3749AB38371F273\"\n  }\n})\n\nbegin\n  collection = Recurly::Purchase.invoice!(purchase)\n  puts collection.inspect\nrescue Recurly::Resource::Invalid => e\n  puts e.inspect\n  # Invalid data\nrescue Recurly::Transaction::Error => e\n  puts e.inspect\n  # Transaction error\n  # e.transaction\n  # e.transaction_error_code\nend\n","language":"ruby"},{"code":"<?php\n\n$purchase = new Recurly_Purchase();\n$purchase->currency = 'USD';\n$purchase->collection_method = 'automatic';\n$purchase->account = new Recurly_Account();\n$purchase->account->account_code = 'aba9209a-aa61-4790-8e61-0a2692435fee';\n$purchase->account->email = \"verena@example.com\";\n$purchase->account->first_name = \"Benjamin\";\n$purchase->account->last_name = \"Du Monde\";\n$purchase->account->address->phone = \"555-555-5555\";\n$purchase->account->address->address1 = \"123 Main St.\";\n$purchase->account->address->city = \"San Francisco\";\n$purchase->account->address->state = \"CA\";\n$purchase->account->address->zip = \"94110\";\n$purchase->account->address->country = \"US\";\n\n$billing_info = new Recurly_BillingInfo();\n$billing_info->number = '4111-1111-1111-1111';\n$billing_info->month = 12;\n$billing_info->year = 2019;\n$billing_info->verification_value = '123';\n$billing_info->address1 = '400 Alabama St';\n$billing_info->city = 'San Francisco';\n$billing_info->state = 'CA';\n$billing_info->country = 'US';\n$billing_info->zip = '94110';\n\n$purchase->account->billing_info = $billing_info;\n\n$shipping_address = new Recurly_ShippingAddress();\n$shipping_address->first_name = 'Lon';\n$shipping_address->last_name = 'Dorner';\n$shipping_address->address1 = '400 Dolores St';\n$shipping_address->city = 'San Francisco';\n$shipping_address->state = 'CA';\n$shipping_address->country = 'US';\n$shipping_address->zip = '94110';\n$shipping_address->nickname = 'Home';\n\n$purchase->account->shipping_addresses = array($shipping_address);\n\n$adjustment = new Recurly_Adjustment();\n$adjustment->unit_amount_in_cents = 1000;\n$adjustment->quantity = 1;\n\n$purchase->adjustments = array($adjustment);\n\n$subscription = new Recurly_Subscription();\n$subscription->plan_code = 'pp';\n\n$purchase->subscriptions = array($subscription);\n\n$purchase->coupon_codes = array('couponcode123', 'rqw311ofo6');\n\n$gift_card = new Recurly_GiftCard();\n$gift_card->redemption_code = \"FCJ7GEY4HO8WR16Q\";\n$purchase->gift_card = $gift_card;\n\n// Create an invoice collection\ntry {\n  $collection = Recurly_Purchase::invoice($purchase);\n} catch (Recurly_ValidationError $e) {\n  // You can get an idea why a purchase failed looking at these objects:\n  var_dump($e->errors->transaction_error);  // Recurly_TransactionError\n  var_dump($e->errors->transaction);   // Recurly_Transaction\n} \n","language":"php"},{"code":"var accountCode = \"benjamin-du-monde\";\nvar currency = \"USD\";\nvar planCode = \"surveillance-pro\";\nvar couponCode = \"surveillance-podcast-promo\";\nvar giftCardRedemptionCode = \"8Z5VE6IRMWJDHU4P\";\n\n// We can create a purchase object from an account code or an Account object (first argument).\n// Use the Account object when you want create a new account. This works similar to Subscription.\nvar purchase = new Purchase(accountCode, currency);\n\nvar shipAddr = new ShippingAddress();\nshipAddr.Address1 = \"400 Alabama St\";\nshipAddr.City = \"San Francisco\";\nshipAddr.State = \"CA\";\nshipAddr.Country = \"US\";\nshipAddr.Zip = \"94110\";\nshipAddr.FirstName = \"Lon\";\nshipAddr.LastName = \"Dorner\";\nshipAddr.Nickname = \"home\";\npurchase.Account.ShippingAddresses.Add(shipAddr);\n\n// Add multiple adjustments (optional if subscription[s] included)\npurchase.Adjustments.Add(new Adjustment(4000, \"HD Camera\", 5));\npurchase.Adjustments.Add(new Adjustment(1000, \"Motion Sensor\", 10));\n\n// Add multiple subscriptions (optional if adjustment[s] included)\npurchase.Subscriptions.Add(new Subscription(planCode));\n\n// Add multiple coupon codes the customer may have (optional)\npurchase.CouponCodes.Add(couponCode);\n\n// Redeem a gift card with this purchase if the customer has redemption code (optional)\npurchase.GiftCardRedemptionCode = giftCardRedemptionCode;\n\n// For manual invoicing\n// purchase.CollectionMethod = Invoice.Collection.Manual;\n// purchase.NetTerms = 30;\n\n// Executes the purchase and transactions\nvar collection = Purchase.Invoice(purchase);","language":"csharp"},{"code":"purchase = recurly.Purchase(\n  currency = 'USD',\n  account = recurly.Account(\n    account_code = 'account-code-123',\n    billing_info = recurly.BillingInfo(\n        first_name = 'Benjamin',\n        last_name = 'DuMonde',\n        number = '4111-1111-1111-1111',\n        verification_value = '123',\n        month = 11,\n        year = 2020,\n        address1 = '123 Main St',\n        city = 'New Orleans',\n        state = 'LA',\n        zip = '70114',\n        country = 'US',\n    ),\n    shipping_addresses = [\n      recurly.ShippingAddress(\n          first_name = 'Lon',\n          last_name = 'Dorner',\n          address1 = '400 Alabama St',\n          city = 'San Francisco',\n          state = 'CA',\n          zip = '94110',\n          country = 'US',\n          nickname = 'home'\n      )\n    ]\n  ),\n  subscriptions = [\n      recurly.Subscription(plan_code = 'gold')\n  ],\n  adjustments = [\n      recurly.Adjustment(unit_amount_in_cents=1000, description='Item 1',\n                         quantity=1),\n      recurly.Adjustment(unit_amount_in_cents=2000, description='Item 2',\n                         quantity=2),\n  ]\n)\n\ncollection = purchase.invoice()\nprint(collection)","language":"python"}]},"auth":"required","params":[{"_id":"591b66df7d2cb40f00d471d6","ref":"","in":"body","required":true,"desc":"An account object. This can be an existing account or a new account. If using a new account and adding shipping addresses, the last shipping address in the list will apply to every subscription and adjustment in the purchase.","default":"","type":"object","name":"account"},{"_id":"591b66df7d2cb40f00d471d5","ref":"","in":"body","required":true,"desc":"This should be a list of Adjustment objects. Required if there are no subscriptions.","default":"","type":"array_object","name":"adjustments"},{"_id":"591b66df7d2cb40f00d471d4","ref":"","in":"body","required":false,"desc":"The collection method for the invoice (`automatic` or `manual`).","default":"","type":"string","name":"collection_method"},{"_id":"591b66df7d2cb40f00d471d3","ref":"","in":"body","required":true,"desc":"The 3 letter currency code for the adjustments.","default":"","type":"string","name":"currency"},{"_id":"591b66df7d2cb40f00d471d2","ref":"","in":"body","required":false,"desc":"A po number for the resulting invoice.","default":"","type":"string","name":"po_number"},{"_id":"591b66df7d2cb40f00d471d1","ref":"","in":"body","required":false,"desc":"The net terms for the invoice","default":"","type":"int","name":"net_terms"},{"_id":"595575d48613d9002bc540c1","ref":"","in":"body","required":false,"desc":"A gift card with a redemption code to apply to this purchase","default":"","type":"object","name":"gift_card"},{"_id":"595575d48613d9002bc540c0","ref":"","in":"body","required":false,"desc":"A list of coupon codes to apply to this purchase","default":"","type":"array_string","name":"coupon_codes"},{"_id":"595575d48613d9002bc540bf","ref":"","in":"body","required":true,"desc":"A list of Subscriptions to invoice in this purchase. Required if there are no adjustments.","default":"","type":"array_object","name":"subscriptions"},{"_id":"59d696a76d3f930010332fd4","ref":"","in":"body","required":false,"desc":"Optional notes to show customer on the invoice. This will default to the Customer Notes text specified on the Invoice Settings page in your Recurly admin. Custom notes made on an invoice for a one time charge will not carry over to subsequent invoices.","default":"","type":"string","name":"customer_notes"},{"_id":"59d696a76d3f930010332fd3","ref":"","in":"body","required":false,"desc":"Optional terms and conditions to show customer on the invoice. This will default to the Terms and Conditions text specified on the Invoice Settings page in your Recurly admin. Custom notes will stay with a subscription on all renewals.","default":"","type":"string","name":"terms_and_conditions"},{"_id":"59d696a76d3f930010332fd2","ref":"","in":"body","required":false,"desc":"Optional VAT reverse charge notes to show the customer on the invoice. Only appears if you have EU VAT enabled or are using your own Avalara AvaTax account and the customer is in the EU, has a VAT number, and is in a different country than your own. This will default to the VAT Reverse Charge Notes text specified on the Tax Settings page in your Recurly admin, unless custom notes were created with the original subscription. Custom notes will stay with a subscription on all renewals.","default":"","type":"string","name":"vat_reverse_charge_notes"},{"_id":"5abbd2c152432700129dca5a","ref":"","in":"body","required":false,"desc":"All subscriptions and adjustments on the purchase will use this shipping address unless they specify one of their own. Any subscriptions for which this address might apply will also use it in future renewals unless changed or removed. Cannot be used if a new shipping address is created at the account level.","default":"","type":"long","name":"shipping_address_id"}],"url":"/purchases"},"isReference":true,"order":0,"body":"","excerpt":"A purchase is a checkout containing at least one or more subscriptions or one-time charges (adjustments) and supports both coupon and gift card redemptions. All items purchased will be on one invoice and paid for with one transaction. A purchase is only a request data type and is not persistent in Recurly and an invoice collection will be the returned type. If you plan to use a shipping address(es) for a purchase, please see https://docs.recurly.com/docs/shipping-address-per-line-item","slug":"create-purchase","type":"post","title":"Create Purchase","__v":19,"childrenPages":[]}

postCreate Purchase

A purchase is a checkout containing at least one or more subscriptions or one-time charges (adjustments) and supports both coupon and gift card redemptions. All items purchased will be on one invoice and paid for with one transaction. A purchase is only a request data type and is not persistent in Recurly and an invoice collection will be the returned type. If you plan to use a shipping address(es) for a purchase, please see https://docs.recurly.com/docs/shipping-address-per-line-item

Body Params

account:
required
object
An account object. This can be an existing account or a new account. If using a new account and adding shipping addresses, the last shipping address in the list will apply to every subscription and adjustment in the purchase.
adjustments:
required
array of objects
This should be a list of Adjustment objects. Required if there are no subscriptions.
collection_method:
string
The collection method for the invoice (`automatic` or `manual`).
currency:
required
string
The 3 letter currency code for the adjustments.
po_number:
string
A po number for the resulting invoice.
net_terms:
integer
The net terms for the invoice
gift_card:
object
A gift card with a redemption code to apply to this purchase
coupon_codes:
array of strings
A list of coupon codes to apply to this purchase
subscriptions:
required
array of objects
A list of Subscriptions to invoice in this purchase. Required if there are no adjustments.
customer_notes:
string
Optional notes to show customer on the invoice. This will default to the Customer Notes text specified on the Invoice Settings page in your Recurly admin. Custom notes made on an invoice for a one time charge will not carry over to subsequent invoices.
terms_and_conditions:
string
Optional terms and conditions to show customer on the invoice. This will default to the Terms and Conditions text specified on the Invoice Settings page in your Recurly admin. Custom notes will stay with a subscription on all renewals.
vat_reverse_charge_notes:
string
Optional VAT reverse charge notes to show the customer on the invoice. Only appears if you have EU VAT enabled or are using your own Avalara AvaTax account and the customer is in the EU, has a VAT number, and is in a different country than your own. This will default to the VAT Reverse Charge Notes text specified on the Tax Settings page in your Recurly admin, unless custom notes were created with the original subscription. Custom notes will stay with a subscription on all renewals.
shipping_address_id:
long
All subscriptions and adjustments on the purchase will use this shipping address unless they specify one of their own. Any subscriptions for which this address might apply will also use it in future renewals unless changed or removed. Cannot be used if a new shipping address is created at the account level.

Definition

{{ api_url }}{{ page_api_url }}

Examples

<purchase>
  <collection_method>automatic</collection_method>
  <currency>USD</currency>
  <customer_notes>Some notes for the customer.</customer_notes>
  <terms_and_conditions>Our company terms and conditions.</terms_and_conditions>
  <vat_reverse_charge_notes>Vat reverse charge notes.</vat_reverse_charge_notes>
  <account>
    <account_code>c442b36c-c64f-41d7-b8e1-9c04e7a6ff82</account_code>
    <shipping_addresses>
      <shipping_address>
        <first_name>Lon</first_name>
        <last_name>Doner</last_name>        
        <address1>221B Baker St.</address1>
        <city>London</city>
        <state></state>
        <zip>W1K 6AH</zip>
        <country>GB</country>
        <nickname>Home</nickname>
      </shipping_address>
    </shipping_addresses>
    <billing_info>
      <address1>400 Alabama St</address1>
      <city>San Francisco</city>
      <country>US</country>
      <first_name>Benjamin</first_name>
      <last_name>Du Monde</last_name>
      <month>12</month>
      <number>4111-1111-1111-1111</number>
      <state>CA</state>
      <year>2019</year>
      <zip>94110</zip>
    </billing_info>
  </account>
  <adjustments>
    <adjustment>
      <product_code>4549449c-5870-4845-b672-1d07f15e87dd</product_code>
      <quantity>1</quantity>
      <revenue_schedule_type>at_invoice</revenue_schedule_type>
      <unit_amount_in_cents>1000</unit_amount_in_cents>
      <description>Description of this adjustment</description>
    </adjustment>
  </adjustments>
  <subscriptions>
    <subscription>
      <plan_code>plan1</plan_code>
    </subscription>
  </subscriptions>
  <coupon_codes>
  	<coupon_code>coupon1</coupon_code>
    <coupon_code>coupon2</coupon_code>
  </coupon_codes>
  <gift_card>
    <redemption_code>ABC1234</redemption_code>
  </gift_card>
</purchase>
require 'securerandom'

purchase = Recurly::Purchase.new({
  currency: 'USD',
  collection_method: :automatic,
  account: {
    account_code: SecureRandom.uuid,
    billing_info: {
      first_name: 'Benjamin',
      last_name: 'Du Monde',
      address1: '400 Alabama St',
      city: 'San Francisco',
      state: 'CA',
      zip: '94110',
      country: 'US',
      number: '4111-1111-1111-1111',
      month: 12,
      year: 2019,
    },
    shipping_addresses: [
      {
        first_name: 'Lon',
        last_name: 'Dorner',
        address1: '400 Alabama St',
        city: 'San Francisco',
        state: 'CA',
        zip: '94110',
        country: 'US',
        nickname: 'home',
      }
    ]
  },
  subscriptions: [
    {
      plan_code: "gold",
    }
  ],
  adjustments: [
    {product_code: SecureRandom.uuid, unit_amount_in_cents: 1_000, quantity: 1, revenue_schedule_type: :at_invoice},
  ],
  coupon_codes: [
    "COUPON123",
    "COUPON345",
  ],
  gift_card: {
    redemption_code: "BC3749AB38371F273"
  }
})

begin
  collection = Recurly::Purchase.invoice!(purchase)
  puts collection.inspect
rescue Recurly::Resource::Invalid => e
  puts e.inspect
  # Invalid data
rescue Recurly::Transaction::Error => e
  puts e.inspect
  # Transaction error
  # e.transaction
  # e.transaction_error_code
end
<?php

$purchase = new Recurly_Purchase();
$purchase->currency = 'USD';
$purchase->collection_method = 'automatic';
$purchase->account = new Recurly_Account();
$purchase->account->account_code = 'aba9209a-aa61-4790-8e61-0a2692435fee';
$purchase->account->email = "verena@example.com";
$purchase->account->first_name = "Benjamin";
$purchase->account->last_name = "Du Monde";
$purchase->account->address->phone = "555-555-5555";
$purchase->account->address->address1 = "123 Main St.";
$purchase->account->address->city = "San Francisco";
$purchase->account->address->state = "CA";
$purchase->account->address->zip = "94110";
$purchase->account->address->country = "US";

$billing_info = new Recurly_BillingInfo();
$billing_info->number = '4111-1111-1111-1111';
$billing_info->month = 12;
$billing_info->year = 2019;
$billing_info->verification_value = '123';
$billing_info->address1 = '400 Alabama St';
$billing_info->city = 'San Francisco';
$billing_info->state = 'CA';
$billing_info->country = 'US';
$billing_info->zip = '94110';

$purchase->account->billing_info = $billing_info;

$shipping_address = new Recurly_ShippingAddress();
$shipping_address->first_name = 'Lon';
$shipping_address->last_name = 'Dorner';
$shipping_address->address1 = '400 Dolores St';
$shipping_address->city = 'San Francisco';
$shipping_address->state = 'CA';
$shipping_address->country = 'US';
$shipping_address->zip = '94110';
$shipping_address->nickname = 'Home';

$purchase->account->shipping_addresses = array($shipping_address);

$adjustment = new Recurly_Adjustment();
$adjustment->unit_amount_in_cents = 1000;
$adjustment->quantity = 1;

$purchase->adjustments = array($adjustment);

$subscription = new Recurly_Subscription();
$subscription->plan_code = 'pp';

$purchase->subscriptions = array($subscription);

$purchase->coupon_codes = array('couponcode123', 'rqw311ofo6');

$gift_card = new Recurly_GiftCard();
$gift_card->redemption_code = "FCJ7GEY4HO8WR16Q";
$purchase->gift_card = $gift_card;

// Create an invoice collection
try {
  $collection = Recurly_Purchase::invoice($purchase);
} catch (Recurly_ValidationError $e) {
  // You can get an idea why a purchase failed looking at these objects:
  var_dump($e->errors->transaction_error);  // Recurly_TransactionError
  var_dump($e->errors->transaction);   // Recurly_Transaction
} 
var accountCode = "benjamin-du-monde";
var currency = "USD";
var planCode = "surveillance-pro";
var couponCode = "surveillance-podcast-promo";
var giftCardRedemptionCode = "8Z5VE6IRMWJDHU4P";

// We can create a purchase object from an account code or an Account object (first argument).
// Use the Account object when you want create a new account. This works similar to Subscription.
var purchase = new Purchase(accountCode, currency);

var shipAddr = new ShippingAddress();
shipAddr.Address1 = "400 Alabama St";
shipAddr.City = "San Francisco";
shipAddr.State = "CA";
shipAddr.Country = "US";
shipAddr.Zip = "94110";
shipAddr.FirstName = "Lon";
shipAddr.LastName = "Dorner";
shipAddr.Nickname = "home";
purchase.Account.ShippingAddresses.Add(shipAddr);

// Add multiple adjustments (optional if subscription[s] included)
purchase.Adjustments.Add(new Adjustment(4000, "HD Camera", 5));
purchase.Adjustments.Add(new Adjustment(1000, "Motion Sensor", 10));

// Add multiple subscriptions (optional if adjustment[s] included)
purchase.Subscriptions.Add(new Subscription(planCode));

// Add multiple coupon codes the customer may have (optional)
purchase.CouponCodes.Add(couponCode);

// Redeem a gift card with this purchase if the customer has redemption code (optional)
purchase.GiftCardRedemptionCode = giftCardRedemptionCode;

// For manual invoicing
// purchase.CollectionMethod = Invoice.Collection.Manual;
// purchase.NetTerms = 30;

// Executes the purchase and transactions
var collection = Purchase.Invoice(purchase);
purchase = recurly.Purchase(
  currency = 'USD',
  account = recurly.Account(
    account_code = 'account-code-123',
    billing_info = recurly.BillingInfo(
        first_name = 'Benjamin',
        last_name = 'DuMonde',
        number = '4111-1111-1111-1111',
        verification_value = '123',
        month = 11,
        year = 2020,
        address1 = '123 Main St',
        city = 'New Orleans',
        state = 'LA',
        zip = '70114',
        country = 'US',
    ),
    shipping_addresses = [
      recurly.ShippingAddress(
          first_name = 'Lon',
          last_name = 'Dorner',
          address1 = '400 Alabama St',
          city = 'San Francisco',
          state = 'CA',
          zip = '94110',
          country = 'US',
          nickname = 'home'
      )
    ]
  ),
  subscriptions = [
      recurly.Subscription(plan_code = 'gold')
  ],
  adjustments = [
      recurly.Adjustment(unit_amount_in_cents=1000, description='Item 1',
                         quantity=1),
      recurly.Adjustment(unit_amount_in_cents=2000, description='Item 2',
                         quantity=2),
  ]
)

collection = purchase.invoice()
print(collection)

Result Format

<invoice_collection>
  <charge_invoice>
    <account href="https://your-subdomain.recurly.com/v2/accounts/1"/>
    <subscriptions href="https://your-subdomain.recurly.com/v2/invoices/1007/subscriptions"/>
    <address>
      <address1>123 Main St.</address1>
      <address2 nil="nil"/>
      <city>San Francisco</city>
      <state>CA</state>
      <zip>94105</zip>
      <country>US</country>
      <phone nil="nil"/>
    </address>
    <uuid>37c0057d2f641f4e2fcbda4b5b833633</uuid>
    <state>paid</state>
    <invoice_number_prefix/>
    <invoice_number type="integer">1007</invoice_number>
    <po_number nil="nil"/>
    <vat_number nil="nil"/>
    <subtotal_in_cents type="integer">2000</subtotal_in_cents>
    <discount_in_cents type="integer">0</discount_in_cents>
    <due_on type="datetime">2018-01-30T21:11:50Z</due_on>
    <balance_in_cents type="integer">0</balance_in_cents>
    <type>charge</type>
    <origin>purchase</origin>
    <credit_invoices href="https://your-subdomain.recurly.com/v2/invoices/1325/credit_invoices"/>
    <refundable_total_in_cents type="integer">2000</refundable_total_in_cents>
    <credit_payments type="array">
    </credit_payments>
    <tax_in_cents type="integer">424</tax_in_cents>
    <total_in_cents type="integer">5274</total_in_cents>
    <currency>EUR</currency>
    <created_at type="datetime">2016-08-03T16:26:26Z</created_at>
    <updated_at type="datetime">2016-08-03T16:26:26Z</updated_at>
    <closed_at type="datetime">2016-08-03T16:26:26Z</closed_at>
    <terms_and_conditions nil="nil"/>
    <customer_notes nil="nil"/>
    <tax_type>usst</tax_type>
    <tax_region>CA</tax_region>
    <tax_rate type="float">0.0875</tax_rate>
    <net_terms type="integer">0</net_terms>
    <collection_method>automatic</collection_method>
    <redemptions href="https://your-subdomain.recurly.com/v2/invoices/1007/redemptions"/>
    <line_items type="array">
      <adjustment href="https://your-subdomain.recurly.com/v2/adjustments/37c0057d2a3ace0c3f3d674ae89fdabd" type="charge">
        <account href="https://your-subdomain.recurly.com/v2/accounts/1"/>
        <invoice href="https://your-subdomain.recurly.com/v2/invoices/1007"/>
        <subscription href="https://your-subdomain.recurly.com/v2/subscriptions/37c0057cb105f67b6b8a1146f7b59c41"/>
        <uuid>37c0057d2a3ace0c3f3d674ae89fdabd</uuid>
        <state>invoiced</state>
        <description>Setup fee: Gold plan</description>
        <accounting_code nil="nil"/>
        <product_code>gold</product_code>
        <origin>setup_fee</origin>
        <unit_amount_in_cents type="integer">800</unit_amount_in_cents>
        <quantity type="integer">1</quantity>
        <discount_in_cents type="integer">0</discount_in_cents>
        <tax_in_cents type="integer">70</tax_in_cents>
        <total_in_cents type="integer">870</total_in_cents>
        <currency>EUR</currency>
        <taxable type="boolean">false</taxable>
        <tax_type>usst</tax_type>
        <tax_region>CA</tax_region>
        <tax_rate type="float">0.0875</tax_rate>
        <tax_exempt type="boolean">false</tax_exempt>
        <tax_code nil="nil"/>
        <shipping_address>
          <first_name>Lon</first_name>
          <last_name>Doner</last_name>
          <address1>400 Alabama St</address1>
          <address2></address2>
          <city>San Francisco</city>
          <state>CA</state>
          <zip>94110</zip>
          <country>US</country>
          <phone></phone>
          <nickname>home</nickname>
        </shipping_address>
        <start_date type="datetime">2016-08-03T16:26:26Z</start_date>
        <end_date nil="nil"/>
        <created_at type="datetime">2016-08-03T16:26:26Z</created_at>
        <updated_at type="datetime">2016-08-03T16:26:26Z</updated_at>
        <revenue_schedule_type>evenly</revenue_schedule_type>
      </adjustment>
      <!-- Continued... -->
    </line_items>
    <transactions type="array">
      <!-- Detail. -->
    </transactions>
    <a name="refund" href="https://your-subdomain.recurly.com/v2/invoices/1007/refund" method="post"/>
  </charge_invoice>
  <credit_invoices type="array">
  </credit_invoices>
</invoice_collection>


{"_id":"5b2d60111235f1000317739e","category":"5b2d60111235f1000317734e","user":"55957fd09b8d0a25005a7d30","project":"555fbba928249c1900618a82","parentDoc":null,"version":"5b2d60111235f10003177402","updates":[],"next":{"pages":[],"description":""},"createdAt":"2017-05-17T16:39:29.580Z","link_external":false,"link_url":"","githubsync":"","sync_unique":"","hidden":false,"api":{"examples":{"codes":[{"code":"<purchase>\n  <collection_method>automatic</collection_method>\n  <currency>USD</currency>\n  <customer_notes>Some notes for the customer.</customer_notes>\n  <terms_and_conditions>Our company terms and conditions.</terms_and_conditions>\n  <vat_reverse_charge_notes>Vat reverse charge notes.</vat_reverse_charge_notes>\n  <account>\n    <account_code>c442b36c-c64f-41d7-b8e1-9c04e7a6ff82</account_code>\n    <shipping_addresses>\n      <shipping_address>\n        <first_name>Lon</first_name>\n        <last_name>Doner</last_name>\n        <address1>221B Baker St.</address1>\n        <city>London</city>\n        <state></state>\n        <zip>W1K 6AH</zip>\n        <country>GB</country>\n        <nickname>Home</nickname>\n      </shipping_address>\n    </shipping_addresses>\n    <billing_info>\n      <address1>400 Alabama St</address1>\n      <city>San Francisco</city>\n      <country>US</country>\n      <first_name>Benjamin</first_name>\n      <last_name>Du Monde</last_name>\n      <month>12</month>\n      <number>4111-1111-1111-1111</number>\n      <state>CA</state>\n      <year>2019</year>\n      <zip>94110</zip>\n    </billing_info>\n  </account>\n  <adjustments>\n    <adjustment>\n      <product_code>4549449c-5870-4845-b672-1d07f15e87dd</product_code>\n      <quantity>1</quantity>\n      <revenue_schedule_type>at_invoice</revenue_schedule_type>\n      <unit_amount_in_cents>1000</unit_amount_in_cents>\n      <description>Description of this adjustment</description>\n    </adjustment>\n  </adjustments>\n  <subscriptions>\n    <subscription>\n      <plan_code>plan1</plan_code>\n    </subscription>\n  </subscriptions>\n  <coupon_codes>\n  \t<coupon_code>coupon1</coupon_code>\n    <coupon_code>coupon2</coupon_code>\n  </coupon_codes>\n  <gift_card>\n    <redemption_code>ABC1234</redemption_code>\n  </gift_card>\n</purchase>","language":"xml"},{"code":"require 'securerandom'\n\npurchase = Recurly::Purchase.new({\n  currency: 'USD',\n  collection_method: :automatic,\n  account: {\n    account_code: SecureRandom.uuid,\n    billing_info: {\n      first_name: 'Benjamin',\n      last_name: 'Du Monde',\n      address1: '400 Alabama St',\n      city: 'San Francisco',\n      state: 'CA',\n      zip: '94110',\n      country: 'US',\n      number: '4111-1111-1111-1111',\n      month: 12,\n      year: 2019,\n    },\n    shipping_addresses: [\n      {\n        first_name: 'Lon',\n        last_name: 'Dorner',\n        address1: '400 Alabama St',\n        city: 'San Francisco',\n        state: 'CA',\n        zip: '94110',\n        country: 'US',\n        nickname: 'home',\n      }\n    ]\n  },\n  subscriptions: [\n    {\n      plan_code: \"gold\",\n    }\n  ],\n  adjustments: [\n    {product_code: SecureRandom.uuid, unit_amount_in_cents: 1_000, quantity: 1, revenue_schedule_type: :at_invoice},\n  ],\n  coupon_codes: [\n    \"COUPON123\",\n    \"COUPON345\",\n  ],\n  gift_card: {\n    redemption_code: \"BC3749AB38371F273\"\n  }\n})\n\nbegin\n  preview_collection = Recurly::Purchase.preview!(purchase)\n  puts preview_collection.inspect\nrescue Recurly::Resource::Invalid => e\n  puts e.inspect\n  # Invalid data\nend","language":"ruby"},{"code":"<?php\n\n$purchase = new Recurly_Purchase();\n$purchase->currency = 'USD';\n$purchase->collection_method = 'automatic';\n$purchase->account = new Recurly_Account();\n$purchase->account->account_code = 'aba9209a-aa61-4790-8e61-0a2692435fee';\n$purchase->account->email = \"verena@example.com\";\n$purchase->account->first_name = \"Benjamin\";\n$purchase->account->last_name = \"Du Monde\";\n$purchase->account->address->phone = \"555-555-5555\";\n$purchase->account->address->address1 = \"123 Main St.\";\n$purchase->account->address->city = \"San Francisco\";\n$purchase->account->address->state = \"CA\";\n$purchase->account->address->zip = \"94110\";\n$purchase->account->address->country = \"US\";\n\n$billing_info = new Recurly_BillingInfo();\n$billing_info->number = '4111-1111-1111-1111';\n$billing_info->month = 12;\n$billing_info->year = 2019;\n$billing_info->verification_value = '123';\n$billing_info->address1 = '400 Alabama St';\n$billing_info->city = 'San Francisco';\n$billing_info->state = 'CA';\n$billing_info->country = 'US';\n$billing_info->zip = '94110';\n\n$purchase->account->billing_info = $billing_info;\n\n$shipping_address = new Recurly_ShippingAddress();\n$shipping_address->first_name = 'Lon';\n$shipping_address->last_name = 'Dorner';\n$shipping_address->address1 = '400 Dolores St';\n$shipping_address->city = 'San Francisco';\n$shipping_address->state = 'CA';\n$shipping_address->country = 'US';\n$shipping_address->zip = '94110';\n$shipping_address->nickname = 'Home';\n\n$purchase->account->shipping_addresses = array($shipping_address);\n\n$adjustment = new Recurly_Adjustment();\n$adjustment->unit_amount_in_cents = 1000;\n$adjustment->quantity = 1;\n\n$purchase->adjustments = array($adjustment);\n\n$subscription = new Recurly_Subscription();\n$subscription->plan_code = 'pp';\n\n$purchase->subscriptions = array($subscription);\n\n$purchase->coupon_codes = array('couponcode123', 'rqw311ofo6');\n\n$gift_card = new Recurly_GiftCard();\n$gift_card->redemption_code = \"FCJ7GEY4HO8WR16Q\";\n$purchase->gift_card = $gift_card;\n\n// Create a preview invoice collection\ntry {\n  $previewCollection = Recurly_Purchase::preview($purchase);\n} catch (Recurly_ValidationError $e) {\n  // You can get an idea why a purchase failed looking at these objects:\n  var_dump($e);\n} ","language":"php"},{"code":"var accountCode = \"benjamin-du-monde\";\nvar currency = \"USD\";\nvar planCode = \"surveillance-pro\";\nvar couponCode = \"surveillance-podcast-promo\";\nvar giftCardRedemptionCode = \"8Z5VE6IRMWJDHU4P\";\n\n// We can create a purchase object from an account code or an Account object (first argument).\n// Use the Account object when you want create a new account. This works similar to Subscription.\nvar purchase = new Purchase(accountCode, currency);\n\nvar shipAddr = new ShippingAddress();\nshipAddr.Address1 = \"400 Alabama St\";\nshipAddr.City = \"San Francisco\";\nshipAddr.State = \"CA\";\nshipAddr.Country = \"US\";\nshipAddr.Zip = \"94110\";\nshipAddr.FirstName = \"Lon\";\nshipAddr.LastName = \"Dorner\";\nshipAddr.Nickname = \"home\";\npurchase.Account.ShippingAddresses.Add(shipAddr);\n\n// Add multiple adjustments (optional if subscription[s] included)\npurchase.Adjustments.Add(new Adjustment(4000, \"HD Camera\", 5));\npurchase.Adjustments.Add(new Adjustment(1000, \"Motion Sensor\", 10));\n\n// Add multiple subscriptions (optional if adjustment[s] included)\npurchase.Subscriptions.Add(new Subscription(planCode));\n\n// Add multiple coupon codes the customer may have (optional)\npurchase.CouponCodes.Add(couponCode);\n\n// Redeem a gift card with this purchase if the customer has redemption code (optional)\npurchase.GiftCardRedemptionCode = giftCardRedemptionCode;\n\n// For manual invoicing\n// purchase.CollectionMethod = Invoice.Collection.Manual;\n// purchase.NetTerms = 30;\n\n// Previewing allows us to run all calculations and validations without running the\n// transactions yet. This allows us to check the information and show the customer\n// the the detailed invoices before they confirm the purchase.\nvar previewCollection = Purchase.Preview(purchase);","language":"csharp"},{"code":"purchase = recurly.Purchase(\n  currency = 'USD',\n  account = recurly.Account(\n    account_code = 'account-code-123',\n    billing_info = recurly.BillingInfo(\n        first_name = 'Benjamin',\n        last_name = 'DuMonde',\n        number = '4111-1111-1111-1111',\n        verification_value = '123',\n        month = 11,\n        year = 2020,\n        address1 = '123 Main St',\n        city = 'New Orleans',\n        state = 'LA',\n        zip = '70114',\n        country = 'US',\n    ),\n    shipping_addresses = [\n      recurly.ShippingAddress(\n          first_name = 'Lon',\n          last_name = 'Dorner',\n          address1 = '400 Alabama St',\n          city = 'San Francisco',\n          state = 'CA',\n          zip = '94110',\n          country = 'US',\n          nickname = 'home'\n      )\n    ]\n  ),\n  subscriptions = [\n      recurly.Subscription(plan_code = 'gold')\n  ],\n  adjustments = [\n      recurly.Adjustment(unit_amount_in_cents=1000, description='Item 1',\n                         quantity=1),\n      recurly.Adjustment(unit_amount_in_cents=2000, description='Item 2',\n                         quantity=2),\n  ]\n)\n\npreview_collection = purchase.preview()\nprint(preview_collection)","language":"python"}]},"method":"post","results":{"codes":[{"name":"","code":"<invoice_collection>\n  <charge_invoice>\n    <account href=\"https://your-subdomain.recurly.com/v2/accounts/1\"/>\n    <subscriptions href=\"https://your-subdomain.recurly.com/v2/invoices/1007/subscriptions\"/>\n    <address>\n      <address1>123 Main St.</address1>\n      <address2 nil=\"nil\"/>\n      <city>San Francisco</city>\n      <state>CA</state>\n      <zip>94105</zip>\n      <country>US</country>\n      <phone nil=\"nil\"/>\n    </address>\n    <shipping_address>\n      <first_name>Lon</first_name>\n      <last_name>Doner</last_name>\n      <address1>221B Baker St.</address1>\n      <address2></address2>\n      <city>London</city>\n      <state></state>\n      <zip>W1K 6AH</zip>\n      <country>GB</country>\n      <phone></phone>\n    </shipping_address>\n    <uuid>37c0057d2f641f4e2fcbda4b5b833633</uuid>\n    <state>paid</state>\n    <invoice_number_prefix/>\n    <invoice_number type=\"integer\">1007</invoice_number>\n    <po_number nil=\"nil\"/>\n    <vat_number nil=\"nil\"/>\n    <subtotal_in_cents type=\"integer\">2000</subtotal_in_cents>\n    <discount_in_cents type=\"integer\">0</discount_in_cents>\n    <due_on type=\"datetime\">2018-01-30T21:11:50Z</due_on>\n    <balance_in_cents type=\"integer\">0</balance_in_cents>\n    <type>charge</type>\n    <origin>purchase</origin>\n    <credit_invoices href=\"https://your-subdomain.recurly.com/v2/invoices/1325/credit_invoices\"/>\n    <refundable_total_in_cents type=\"integer\">2000</refundable_total_in_cents>\n    <credit_payments type=\"array\">\n    </credit_payments>\n    <tax_in_cents type=\"integer\">424</tax_in_cents>\n    <total_in_cents type=\"integer\">5274</total_in_cents>\n    <currency>EUR</currency>\n    <created_at type=\"datetime\">2016-08-03T16:26:26Z</created_at>\n    <updated_at type=\"datetime\">2016-08-03T16:26:26Z</updated_at>\n    <closed_at type=\"datetime\">2016-08-03T16:26:26Z</closed_at>\n    <terms_and_conditions nil=\"nil\"/>\n    <customer_notes nil=\"nil\"/>\n    <tax_type>usst</tax_type>\n    <tax_region>CA</tax_region>\n    <tax_rate type=\"float\">0.0875</tax_rate>\n    <net_terms type=\"integer\">0</net_terms>\n    <collection_method>automatic</collection_method>\n    <redemptions href=\"https://your-subdomain.recurly.com/v2/invoices/1007/redemptions\"/>\n    <line_items type=\"array\">\n      <adjustment href=\"https://your-subdomain.recurly.com/v2/adjustments/37c0057d2a3ace0c3f3d674ae89fdabd\" type=\"charge\">\n        <account href=\"https://your-subdomain.recurly.com/v2/accounts/1\"/>\n        <invoice href=\"https://your-subdomain.recurly.com/v2/invoices/1007\"/>\n        <subscription href=\"https://your-subdomain.recurly.com/v2/subscriptions/37c0057cb105f67b6b8a1146f7b59c41\"/>\n        <uuid>37c0057d2a3ace0c3f3d674ae89fdabd</uuid>\n        <state>invoiced</state>\n        <description>Setup fee: Gold plan</description>\n        <accounting_code nil=\"nil\"/>\n        <product_code>gold</product_code>\n        <origin>setup_fee</origin>\n        <unit_amount_in_cents type=\"integer\">800</unit_amount_in_cents>\n        <quantity type=\"integer\">1</quantity>\n        <discount_in_cents type=\"integer\">0</discount_in_cents>\n        <tax_in_cents type=\"integer\">70</tax_in_cents>\n        <total_in_cents type=\"integer\">870</total_in_cents>\n        <currency>EUR</currency>\n        <taxable type=\"boolean\">false</taxable>\n        <tax_type>usst</tax_type>\n        <tax_region>CA</tax_region>\n        <tax_rate type=\"float\">0.0875</tax_rate>\n        <tax_exempt type=\"boolean\">false</tax_exempt>\n        <tax_code nil=\"nil\"/>\n        <start_date type=\"datetime\">2016-08-03T16:26:26Z</start_date>\n        <end_date nil=\"nil\"/>\n        <created_at type=\"datetime\">2016-08-03T16:26:26Z</created_at>\n        <updated_at type=\"datetime\">2016-08-03T16:26:26Z</updated_at>\n        <revenue_schedule_type>evenly</revenue_schedule_type>\n      </adjustment>\n      <!-- Continued... -->\n    </line_items>\n    <transactions type=\"array\">\n      <!-- Detail. -->\n    </transactions>\n    <a name=\"refund\" href=\"https://your-subdomain.recurly.com/v2/invoices/1007/refund\" method=\"post\"/>\n  </charge_invoice>\n  <credit_invoices type=\"array\">\n  </credit_invoices>\n</invoice_collection>","language":"xml","status":200}]},"settings":"","auth":"required","params":[{"_id":"591b66df7d2cb40f00d471d6","ref":"","in":"body","required":true,"desc":"An account object. This can be an existing account or a new account. If using a new account and adding shipping addresses, the last shipping address in the list will apply to every subscription and adjustment in the purchase.","default":"","type":"object","name":"account"},{"_id":"591b66df7d2cb40f00d471d5","ref":"","in":"body","required":true,"desc":"This should be a list of Adjustment objects. Required if there are no subscriptions.","default":"","type":"array_object","name":"adjustments"},{"_id":"591b66df7d2cb40f00d471d4","ref":"","in":"body","required":false,"desc":"The collection method for the invoice (`automatic` or `manual`).","default":"","type":"string","name":"collection_method"},{"_id":"591b66df7d2cb40f00d471d3","ref":"","in":"body","required":false,"desc":"The 3 letter currency code for the adjustments.","default":"","type":"string","name":"currency"},{"_id":"591b66df7d2cb40f00d471d2","ref":"","in":"body","required":false,"desc":"A po number for the resulting invoice.","default":"","type":"string","name":"po_number"},{"_id":"591b66df7d2cb40f00d471d1","ref":"","in":"body","required":false,"desc":"The net terms for the invoice","default":"","type":"int","name":"net_terms"},{"_id":"5955762bba6cff002966ae31","ref":"","in":"body","required":false,"desc":"A gift card with a redemption code to apply to this purchase","default":"","type":"object","name":"gift_card"},{"_id":"5955762bba6cff002966ae30","ref":"","in":"body","required":false,"desc":"A list of coupon codes to apply to this purchase","default":"","type":"array_string","name":"coupon_codes"},{"_id":"5955762bba6cff002966ae2f","ref":"","in":"body","required":true,"desc":"A list of Subscriptions to invoice in this purchase. Required if there are no adjustments.","default":"","type":"array_object","name":"subscriptions"},{"_id":"59d699316d3f930010333002","ref":"","in":"body","required":false,"desc":"Optional notes to show customer on the invoice. This will default to the Customer Notes text specified on the Invoice Settings page in your Recurly admin. Custom notes made on an invoice for a one time charge will not carry over to subsequent invoices.","default":"","type":"string","name":"customer_notes"},{"_id":"59d699316d3f930010333001","ref":"","in":"body","required":false,"desc":"Optional terms and conditions to show customer on the invoice. This will default to the Terms and Conditions text specified on the Invoice Settings page in your Recurly admin. Custom notes will stay with a subscription on all renewals.","default":"","type":"string","name":"terms_and_conditions"},{"_id":"59d699316d3f930010333000","ref":"","in":"body","required":false,"desc":"Optional VAT reverse charge notes to show the customer on the invoice. Only appears if you have EU VAT enabled or are using your own Avalara AvaTax account and the customer is in the EU, has a VAT number, and is in a different country than your own. This will default to the VAT Reverse Charge Notes text specified on the Tax Settings page in your Recurly admin, unless custom notes were created with the original subscription. Custom notes will stay with a subscription on all renewals.","default":"","type":"string","name":"vat_reverse_charge_notes"},{"_id":"5abbd2e452432700129dca5b","ref":"","in":"body","required":false,"desc":"All subscriptions and adjustments on the purchase will use this shipping address unless they specify one of their own. Any subscriptions for which this address might apply will also use it in future renewals unless changed or removed. Cannot be used if a new shipping address is created at the account level.","default":"","type":"long","name":"shipping_address_id"}],"url":"/purchases/preview"},"isReference":true,"order":1,"body":"","excerpt":"A purchase is a hybrid checkout containing at least one or more subscriptions or one-time charges (adjustments) and supports both coupon and gift card redemptions. All items purchased will be on one invoice and paid for with one transaction. A purchase is only a request data type and is not persistent in Recurly and an invoice collection will be the returned type.\n\nPOSTing to the preview endpoint runs the validations and creates a preview invoice, but does not run the transactions.","slug":"preview-purchase","type":"post","title":"Preview Purchase","__v":14,"childrenPages":[]}

postPreview Purchase

A purchase is a hybrid checkout containing at least one or more subscriptions or one-time charges (adjustments) and supports both coupon and gift card redemptions. All items purchased will be on one invoice and paid for with one transaction. A purchase is only a request data type and is not persistent in Recurly and an invoice collection will be the returned type. POSTing to the preview endpoint runs the validations and creates a preview invoice, but does not run the transactions.

Body Params

account:
required
object
An account object. This can be an existing account or a new account. If using a new account and adding shipping addresses, the last shipping address in the list will apply to every subscription and adjustment in the purchase.
adjustments:
required
array of objects
This should be a list of Adjustment objects. Required if there are no subscriptions.
collection_method:
string
The collection method for the invoice (`automatic` or `manual`).
currency:
string
The 3 letter currency code for the adjustments.
po_number:
string
A po number for the resulting invoice.
net_terms:
integer
The net terms for the invoice
gift_card:
object
A gift card with a redemption code to apply to this purchase
coupon_codes:
array of strings
A list of coupon codes to apply to this purchase
subscriptions:
required
array of objects
A list of Subscriptions to invoice in this purchase. Required if there are no adjustments.
customer_notes:
string
Optional notes to show customer on the invoice. This will default to the Customer Notes text specified on the Invoice Settings page in your Recurly admin. Custom notes made on an invoice for a one time charge will not carry over to subsequent invoices.
terms_and_conditions:
string
Optional terms and conditions to show customer on the invoice. This will default to the Terms and Conditions text specified on the Invoice Settings page in your Recurly admin. Custom notes will stay with a subscription on all renewals.
vat_reverse_charge_notes:
string
Optional VAT reverse charge notes to show the customer on the invoice. Only appears if you have EU VAT enabled or are using your own Avalara AvaTax account and the customer is in the EU, has a VAT number, and is in a different country than your own. This will default to the VAT Reverse Charge Notes text specified on the Tax Settings page in your Recurly admin, unless custom notes were created with the original subscription. Custom notes will stay with a subscription on all renewals.
shipping_address_id:
long
All subscriptions and adjustments on the purchase will use this shipping address unless they specify one of their own. Any subscriptions for which this address might apply will also use it in future renewals unless changed or removed. Cannot be used if a new shipping address is created at the account level.

Definition

{{ api_url }}{{ page_api_url }}

Examples

<purchase>
  <collection_method>automatic</collection_method>
  <currency>USD</currency>
  <customer_notes>Some notes for the customer.</customer_notes>
  <terms_and_conditions>Our company terms and conditions.</terms_and_conditions>
  <vat_reverse_charge_notes>Vat reverse charge notes.</vat_reverse_charge_notes>
  <account>
    <account_code>c442b36c-c64f-41d7-b8e1-9c04e7a6ff82</account_code>
    <shipping_addresses>
      <shipping_address>
        <first_name>Lon</first_name>
        <last_name>Doner</last_name>
        <address1>221B Baker St.</address1>
        <city>London</city>
        <state></state>
        <zip>W1K 6AH</zip>
        <country>GB</country>
        <nickname>Home</nickname>
      </shipping_address>
    </shipping_addresses>
    <billing_info>
      <address1>400 Alabama St</address1>
      <city>San Francisco</city>
      <country>US</country>
      <first_name>Benjamin</first_name>
      <last_name>Du Monde</last_name>
      <month>12</month>
      <number>4111-1111-1111-1111</number>
      <state>CA</state>
      <year>2019</year>
      <zip>94110</zip>
    </billing_info>
  </account>
  <adjustments>
    <adjustment>
      <product_code>4549449c-5870-4845-b672-1d07f15e87dd</product_code>
      <quantity>1</quantity>
      <revenue_schedule_type>at_invoice</revenue_schedule_type>
      <unit_amount_in_cents>1000</unit_amount_in_cents>
      <description>Description of this adjustment</description>
    </adjustment>
  </adjustments>
  <subscriptions>
    <subscription>
      <plan_code>plan1</plan_code>
    </subscription>
  </subscriptions>
  <coupon_codes>
  	<coupon_code>coupon1</coupon_code>
    <coupon_code>coupon2</coupon_code>
  </coupon_codes>
  <gift_card>
    <redemption_code>ABC1234</redemption_code>
  </gift_card>
</purchase>
require 'securerandom'

purchase = Recurly::Purchase.new({
  currency: 'USD',
  collection_method: :automatic,
  account: {
    account_code: SecureRandom.uuid,
    billing_info: {
      first_name: 'Benjamin',
      last_name: 'Du Monde',
      address1: '400 Alabama St',
      city: 'San Francisco',
      state: 'CA',
      zip: '94110',
      country: 'US',
      number: '4111-1111-1111-1111',
      month: 12,
      year: 2019,
    },
    shipping_addresses: [
      {
        first_name: 'Lon',
        last_name: 'Dorner',
        address1: '400 Alabama St',
        city: 'San Francisco',
        state: 'CA',
        zip: '94110',
        country: 'US',
        nickname: 'home',
      }
    ]
  },
  subscriptions: [
    {
      plan_code: "gold",
    }
  ],
  adjustments: [
    {product_code: SecureRandom.uuid, unit_amount_in_cents: 1_000, quantity: 1, revenue_schedule_type: :at_invoice},
  ],
  coupon_codes: [
    "COUPON123",
    "COUPON345",
  ],
  gift_card: {
    redemption_code: "BC3749AB38371F273"
  }
})

begin
  preview_collection = Recurly::Purchase.preview!(purchase)
  puts preview_collection.inspect
rescue Recurly::Resource::Invalid => e
  puts e.inspect
  # Invalid data
end
<?php

$purchase = new Recurly_Purchase();
$purchase->currency = 'USD';
$purchase->collection_method = 'automatic';
$purchase->account = new Recurly_Account();
$purchase->account->account_code = 'aba9209a-aa61-4790-8e61-0a2692435fee';
$purchase->account->email = "verena@example.com";
$purchase->account->first_name = "Benjamin";
$purchase->account->last_name = "Du Monde";
$purchase->account->address->phone = "555-555-5555";
$purchase->account->address->address1 = "123 Main St.";
$purchase->account->address->city = "San Francisco";
$purchase->account->address->state = "CA";
$purchase->account->address->zip = "94110";
$purchase->account->address->country = "US";

$billing_info = new Recurly_BillingInfo();
$billing_info->number = '4111-1111-1111-1111';
$billing_info->month = 12;
$billing_info->year = 2019;
$billing_info->verification_value = '123';
$billing_info->address1 = '400 Alabama St';
$billing_info->city = 'San Francisco';
$billing_info->state = 'CA';
$billing_info->country = 'US';
$billing_info->zip = '94110';

$purchase->account->billing_info = $billing_info;

$shipping_address = new Recurly_ShippingAddress();
$shipping_address->first_name = 'Lon';
$shipping_address->last_name = 'Dorner';
$shipping_address->address1 = '400 Dolores St';
$shipping_address->city = 'San Francisco';
$shipping_address->state = 'CA';
$shipping_address->country = 'US';
$shipping_address->zip = '94110';
$shipping_address->nickname = 'Home';

$purchase->account->shipping_addresses = array($shipping_address);

$adjustment = new Recurly_Adjustment();
$adjustment->unit_amount_in_cents = 1000;
$adjustment->quantity = 1;

$purchase->adjustments = array($adjustment);

$subscription = new Recurly_Subscription();
$subscription->plan_code = 'pp';

$purchase->subscriptions = array($subscription);

$purchase->coupon_codes = array('couponcode123', 'rqw311ofo6');

$gift_card = new Recurly_GiftCard();
$gift_card->redemption_code = "FCJ7GEY4HO8WR16Q";
$purchase->gift_card = $gift_card;

// Create a preview invoice collection
try {
  $previewCollection = Recurly_Purchase::preview($purchase);
} catch (Recurly_ValidationError $e) {
  // You can get an idea why a purchase failed looking at these objects:
  var_dump($e);
} 
var accountCode = "benjamin-du-monde";
var currency = "USD";
var planCode = "surveillance-pro";
var couponCode = "surveillance-podcast-promo";
var giftCardRedemptionCode = "8Z5VE6IRMWJDHU4P";

// We can create a purchase object from an account code or an Account object (first argument).
// Use the Account object when you want create a new account. This works similar to Subscription.
var purchase = new Purchase(accountCode, currency);

var shipAddr = new ShippingAddress();
shipAddr.Address1 = "400 Alabama St";
shipAddr.City = "San Francisco";
shipAddr.State = "CA";
shipAddr.Country = "US";
shipAddr.Zip = "94110";
shipAddr.FirstName = "Lon";
shipAddr.LastName = "Dorner";
shipAddr.Nickname = "home";
purchase.Account.ShippingAddresses.Add(shipAddr);

// Add multiple adjustments (optional if subscription[s] included)
purchase.Adjustments.Add(new Adjustment(4000, "HD Camera", 5));
purchase.Adjustments.Add(new Adjustment(1000, "Motion Sensor", 10));

// Add multiple subscriptions (optional if adjustment[s] included)
purchase.Subscriptions.Add(new Subscription(planCode));

// Add multiple coupon codes the customer may have (optional)
purchase.CouponCodes.Add(couponCode);

// Redeem a gift card with this purchase if the customer has redemption code (optional)
purchase.GiftCardRedemptionCode = giftCardRedemptionCode;

// For manual invoicing
// purchase.CollectionMethod = Invoice.Collection.Manual;
// purchase.NetTerms = 30;

// Previewing allows us to run all calculations and validations without running the
// transactions yet. This allows us to check the information and show the customer
// the the detailed invoices before they confirm the purchase.
var previewCollection = Purchase.Preview(purchase);
purchase = recurly.Purchase(
  currency = 'USD',
  account = recurly.Account(
    account_code = 'account-code-123',
    billing_info = recurly.BillingInfo(
        first_name = 'Benjamin',
        last_name = 'DuMonde',
        number = '4111-1111-1111-1111',
        verification_value = '123',
        month = 11,
        year = 2020,
        address1 = '123 Main St',
        city = 'New Orleans',
        state = 'LA',
        zip = '70114',
        country = 'US',
    ),
    shipping_addresses = [
      recurly.ShippingAddress(
          first_name = 'Lon',
          last_name = 'Dorner',
          address1 = '400 Alabama St',
          city = 'San Francisco',
          state = 'CA',
          zip = '94110',
          country = 'US',
          nickname = 'home'
      )
    ]
  ),
  subscriptions = [
      recurly.Subscription(plan_code = 'gold')
  ],
  adjustments = [
      recurly.Adjustment(unit_amount_in_cents=1000, description='Item 1',
                         quantity=1),
      recurly.Adjustment(unit_amount_in_cents=2000, description='Item 2',
                         quantity=2),
  ]
)

preview_collection = purchase.preview()
print(preview_collection)

Result Format

<invoice_collection>
  <charge_invoice>
    <account href="https://your-subdomain.recurly.com/v2/accounts/1"/>
    <subscriptions href="https://your-subdomain.recurly.com/v2/invoices/1007/subscriptions"/>
    <address>
      <address1>123 Main St.</address1>
      <address2 nil="nil"/>
      <city>San Francisco</city>
      <state>CA</state>
      <zip>94105</zip>
      <country>US</country>
      <phone nil="nil"/>
    </address>
    <shipping_address>
      <first_name>Lon</first_name>
      <last_name>Doner</last_name>
      <address1>221B Baker St.</address1>
      <address2></address2>
      <city>London</city>
      <state></state>
      <zip>W1K 6AH</zip>
      <country>GB</country>
      <phone></phone>
    </shipping_address>
    <uuid>37c0057d2f641f4e2fcbda4b5b833633</uuid>
    <state>paid</state>
    <invoice_number_prefix/>
    <invoice_number type="integer">1007</invoice_number>
    <po_number nil="nil"/>
    <vat_number nil="nil"/>
    <subtotal_in_cents type="integer">2000</subtotal_in_cents>
    <discount_in_cents type="integer">0</discount_in_cents>
    <due_on type="datetime">2018-01-30T21:11:50Z</due_on>
    <balance_in_cents type="integer">0</balance_in_cents>
    <type>charge</type>
    <origin>purchase</origin>
    <credit_invoices href="https://your-subdomain.recurly.com/v2/invoices/1325/credit_invoices"/>
    <refundable_total_in_cents type="integer">2000</refundable_total_in_cents>
    <credit_payments type="array">
    </credit_payments>
    <tax_in_cents type="integer">424</tax_in_cents>
    <total_in_cents type="integer">5274</total_in_cents>
    <currency>EUR</currency>
    <created_at type="datetime">2016-08-03T16:26:26Z</created_at>
    <updated_at type="datetime">2016-08-03T16:26:26Z</updated_at>
    <closed_at type="datetime">2016-08-03T16:26:26Z</closed_at>
    <terms_and_conditions nil="nil"/>
    <customer_notes nil="nil"/>
    <tax_type>usst</tax_type>
    <tax_region>CA</tax_region>
    <tax_rate type="float">0.0875</tax_rate>
    <net_terms type="integer">0</net_terms>
    <collection_method>automatic</collection_method>
    <redemptions href="https://your-subdomain.recurly.com/v2/invoices/1007/redemptions"/>
    <line_items type="array">
      <adjustment href="https://your-subdomain.recurly.com/v2/adjustments/37c0057d2a3ace0c3f3d674ae89fdabd" type="charge">
        <account href="https://your-subdomain.recurly.com/v2/accounts/1"/>
        <invoice href="https://your-subdomain.recurly.com/v2/invoices/1007"/>
        <subscription href="https://your-subdomain.recurly.com/v2/subscriptions/37c0057cb105f67b6b8a1146f7b59c41"/>
        <uuid>37c0057d2a3ace0c3f3d674ae89fdabd</uuid>
        <state>invoiced</state>
        <description>Setup fee: Gold plan</description>
        <accounting_code nil="nil"/>
        <product_code>gold</product_code>
        <origin>setup_fee</origin>
        <unit_amount_in_cents type="integer">800</unit_amount_in_cents>
        <quantity type="integer">1</quantity>
        <discount_in_cents type="integer">0</discount_in_cents>
        <tax_in_cents type="integer">70</tax_in_cents>
        <total_in_cents type="integer">870</total_in_cents>
        <currency>EUR</currency>
        <taxable type="boolean">false</taxable>
        <tax_type>usst</tax_type>
        <tax_region>CA</tax_region>
        <tax_rate type="float">0.0875</tax_rate>
        <tax_exempt type="boolean">false</tax_exempt>
        <tax_code nil="nil"/>
        <start_date type="datetime">2016-08-03T16:26:26Z</start_date>
        <end_date nil="nil"/>
        <created_at type="datetime">2016-08-03T16:26:26Z</created_at>
        <updated_at type="datetime">2016-08-03T16:26:26Z</updated_at>
        <revenue_schedule_type>evenly</revenue_schedule_type>
      </adjustment>
      <!-- Continued... -->
    </line_items>
    <transactions type="array">
      <!-- Detail. -->
    </transactions>
    <a name="refund" href="https://your-subdomain.recurly.com/v2/invoices/1007/refund" method="post"/>
  </charge_invoice>
  <credit_invoices type="array">
  </credit_invoices>
</invoice_collection>


{"_id":"5b2d60111235f1000317739f","category":"5b2d60111235f1000317734e","project":"555fbba928249c1900618a82","user":"55957fd09b8d0a25005a7d30","parentDoc":null,"version":"5b2d60111235f10003177402","updates":[],"next":{"pages":[],"description":""},"createdAt":"2017-11-20T19:03:04.216Z","link_external":false,"link_url":"","githubsync":"","sync_unique":"","hidden":false,"api":{"settings":"","results":{"codes":[{"name":"","code":"<invoice_collection>\n  <charge_invoice>\n    <account href=\"https://your-subdomain.recurly.com/v2/accounts/1\"/>\n    <subscriptions href=\"https://your-subdomain.recurly.com/v2/invoices/1007/subscriptions\"/>\n    <address>\n      <address1>123 Main St.</address1>\n      <address2 nil=\"nil\"/>\n      <city>San Francisco</city>\n      <state>CA</state>\n      <zip>94105</zip>\n      <country>US</country>\n      <phone nil=\"nil\"/>\n    </address>\n    <shipping_address>\n      <first_name>Lon</first_name>\n      <last_name>Doner</last_name>\n      <address1>221B Baker St.</address1>\n      <address2></address2>\n      <city>London</city>\n      <state></state>\n      <zip>W1K 6AH</zip>\n      <country>GB</country>\n      <phone></phone>\n    </shipping_address>\n    <uuid>37c0057d2f641f4e2fcbda4b5b833633</uuid>\n    <state>paid</state>\n    <invoice_number_prefix/>\n    <invoice_number type=\"integer\">1007</invoice_number>\n    <po_number nil=\"nil\"/>\n    <vat_number nil=\"nil\"/>\n    <subtotal_in_cents type=\"integer\">2000</subtotal_in_cents>\n    <discount_in_cents type=\"integer\">0</discount_in_cents>\n    <due_on type=\"datetime\">2018-01-30T21:11:50Z</due_on>\n    <balance_in_cents type=\"integer\">0</balance_in_cents>\n    <type>charge</type>\n    <origin>purchase</origin>\n    <credit_invoices href=\"https://your-subdomain.recurly.com/v2/invoices/1325/credit_invoices\"/>\n    <refundable_total_in_cents type=\"integer\">2000</refundable_total_in_cents>\n    <credit_payments type=\"array\">\n    </credit_payments>\n    <tax_in_cents type=\"integer\">424</tax_in_cents>\n    <total_in_cents type=\"integer\">5274</total_in_cents>\n    <currency>EUR</currency>\n    <created_at type=\"datetime\">2016-08-03T16:26:26Z</created_at>\n    <updated_at type=\"datetime\">2016-08-03T16:26:26Z</updated_at>\n    <closed_at type=\"datetime\">2016-08-03T16:26:26Z</closed_at>\n    <terms_and_conditions nil=\"nil\"/>\n    <customer_notes nil=\"nil\"/>\n    <tax_type>usst</tax_type>\n    <tax_region>CA</tax_region>\n    <tax_rate type=\"float\">0.0875</tax_rate>\n    <net_terms type=\"integer\">0</net_terms>\n    <collection_method>automatic</collection_method>\n    <redemptions href=\"https://your-subdomain.recurly.com/v2/invoices/1007/redemptions\"/>\n    <line_items type=\"array\">\n      <adjustment href=\"https://your-subdomain.recurly.com/v2/adjustments/37c0057d2a3ace0c3f3d674ae89fdabd\" type=\"charge\">\n        <account href=\"https://your-subdomain.recurly.com/v2/accounts/1\"/>\n        <invoice href=\"https://your-subdomain.recurly.com/v2/invoices/1007\"/>\n        <subscription href=\"https://your-subdomain.recurly.com/v2/subscriptions/37c0057cb105f67b6b8a1146f7b59c41\"/>\n        <uuid>37c0057d2a3ace0c3f3d674ae89fdabd</uuid>\n        <state>invoiced</state>\n        <description>Setup fee: Gold plan</description>\n        <accounting_code nil=\"nil\"/>\n        <product_code>gold</product_code>\n        <origin>setup_fee</origin>\n        <unit_amount_in_cents type=\"integer\">800</unit_amount_in_cents>\n        <quantity type=\"integer\">1</quantity>\n        <discount_in_cents type=\"integer\">0</discount_in_cents>\n        <tax_in_cents type=\"integer\">70</tax_in_cents>\n        <total_in_cents type=\"integer\">870</total_in_cents>\n        <currency>EUR</currency>\n        <taxable type=\"boolean\">false</taxable>\n        <tax_type>usst</tax_type>\n        <tax_region>CA</tax_region>\n        <tax_rate type=\"float\">0.0875</tax_rate>\n        <tax_exempt type=\"boolean\">false</tax_exempt>\n        <tax_code nil=\"nil\"/>\n        <start_date type=\"datetime\">2016-08-03T16:26:26Z</start_date>\n        <end_date nil=\"nil\"/>\n        <created_at type=\"datetime\">2016-08-03T16:26:26Z</created_at>\n        <updated_at type=\"datetime\">2016-08-03T16:26:26Z</updated_at>\n        <revenue_schedule_type>evenly</revenue_schedule_type>\n      </adjustment>\n      <!-- Continued... -->\n    </line_items>\n    <transactions type=\"array\">\n      <!-- Detail. -->\n    </transactions>\n    <a name=\"refund\" href=\"https://your-subdomain.recurly.com/v2/invoices/1007/refund\" method=\"post\"/>\n  </charge_invoice>\n  <credit_invoices type=\"array\">\n  </credit_invoices>\n</invoice_collection>","language":"xml","status":200}]},"method":"post","examples":{"codes":[{"code":"<purchase>\n  <collection_method>automatic</collection_method>\n  <currency>USD</currency>\n  <customer_notes>Some notes for the customer.</customer_notes>\n  <terms_and_conditions>Our company terms and conditions.</terms_and_conditions>\n  <vat_reverse_charge_notes>Vat reverse charge notes.</vat_reverse_charge_notes>\n  <account>\n    <account_code>c442b36c-c64f-41d7-b8e1-9c04e7a6ff82</account_code>\n    <!-- email is required for this endpoint -->\n    <email>benjamin.dumonde@example.com</email>\n    <shipping_addresses>\n      <shipping_address>\n        <first_name>Lon</first_name>\n        <last_name>Doner</last_name>\n        <address1>221B Baker St.</address1>\n        <city>London</city>\n        <state></state>\n        <zip>W1K 6AH</zip>\n        <country>GB</country>\n        <nickname>Home</nickname>\n      </shipping_address>\n    </shipping_addresses>\n    <billing_info>\n      <address1>400 Alabama St</address1>\n      <city>San Francisco</city>\n      <country>US</country>\n      <first_name>Benjamin</first_name>\n      <last_name>Du Monde</last_name>\n      <month>12</month>\n      <number>4111-1111-1111-1111</number>\n      <state>CA</state>\n      <year>2019</year>\n      <zip>94110</zip>\n      <!-- this field tells Recurly which external payment method will be used -->      \n      <external_hpp_type>adyen</external_hpp_type>\n    </billing_info>\n  </account>\n  <adjustments>\n    <adjustment>\n      <product_code>4549449c-5870-4845-b672-1d07f15e87dd</product_code>\n      <quantity>1</quantity>\n      <revenue_schedule_type>at_invoice</revenue_schedule_type>\n      <unit_amount_in_cents>1000</unit_amount_in_cents>\n      <description>Description of this adjustment</description>\n    </adjustment>\n  </adjustments>\n  <subscriptions>\n    <subscription>\n      <plan_code>plan1</plan_code>\n    </subscription>\n  </subscriptions>\n  <coupon_codes>\n  \t<coupon_code>coupon1</coupon_code>\n    <coupon_code>coupon2</coupon_code>\n  </coupon_codes>\n  <gift_card>\n    <redemption_code>ABC1234</redemption_code>\n  </gift_card>\n</purchase>","language":"xml"},{"code":"require 'securerandom'\n\npurchase = Recurly::Purchase.new({\n  currency: 'USD',\n  collection_method: :automatic,\n  account: {\n    account_code: SecureRandom.uuid,\n    billing_info: {\n      first_name: 'Benjamin',\n      last_name: 'Du Monde',\n      address1: '400 Alabama St',\n      city: 'San Francisco',\n      state: 'CA',\n      zip: '94110',\n      country: 'US',\n      number: '4111-1111-1111-1111',\n      month: 12,\n      year: 2019,\n    },\n    shipping_addresses: [\n      {\n        first_name: 'Lon',\n        last_name: 'Dorner',\n        address1: '400 Alabama St',\n        city: 'San Francisco',\n        state: 'CA',\n        zip: '94110',\n        country: 'US',\n        nickname: 'home',\n      }\n    ]\n  },\n  subscriptions: [\n    {\n      plan_code: \"gold\",\n    }\n  ],\n  adjustments: [\n    {product_code: SecureRandom.uuid, unit_amount_in_cents: 1_000, quantity: 1, revenue_schedule_type: :at_invoice},\n  ],\n  coupon_codes: [\n    \"COUPON123\",\n    \"COUPON345\",\n  ],\n  gift_card: {\n    redemption_code: \"BC3749AB38371F273\"\n  }\n})\n\nbegin\n  preview_collection = Recurly::Purchase.authorize!(purchase)\n  puts preview_collection.inspect\nrescue Recurly::Resource::Invalid => e\n  puts e.inspect\n  # Invalid data\nend","language":"ruby"},{"code":"<?php\n\n$purchase = new Recurly_Purchase();\n$purchase->currency = 'USD';\n$purchase->collection_method = 'automatic';\n$purchase->account = new Recurly_Account();\n$purchase->account->account_code = 'aba9209a-aa61-4790-8e61-0a2692435fee';\n$purchase->account->email = \"verena@example.com\";\n$purchase->account->first_name = \"Benjamin\";\n$purchase->account->last_name = \"Du Monde\";\n$purchase->account->address->phone = \"555-555-5555\";\n$purchase->account->address->address1 = \"123 Main St.\";\n$purchase->account->address->city = \"San Francisco\";\n$purchase->account->address->state = \"CA\";\n$purchase->account->address->zip = \"94110\";\n$purchase->account->address->country = \"US\";\n\n$billing_info = new Recurly_BillingInfo();\n$billing_info->number = '4111-1111-1111-1111';\n$billing_info->month = 12;\n$billing_info->year = 2019;\n$billing_info->verification_value = '123';\n$billing_info->address1 = '400 Alabama St';\n$billing_info->city = 'San Francisco';\n$billing_info->state = 'CA';\n$billing_info->country = 'US';\n$billing_info->zip = '94110';\n\n$purchase->account->billing_info = $billing_info;\n\n$shipping_address = new Recurly_ShippingAddress();\n$shipping_address->first_name = 'Lon';\n$shipping_address->last_name = 'Dorner';\n$shipping_address->address1 = '400 Dolores St';\n$shipping_address->city = 'San Francisco';\n$shipping_address->state = 'CA';\n$shipping_address->country = 'US';\n$shipping_address->zip = '94110';\n$shipping_address->nickname = 'Home';\n\n$purchase->account->shipping_addresses = array($shipping_address);\n\n$adjustment = new Recurly_Adjustment();\n$adjustment->unit_amount_in_cents = 1000;\n$adjustment->quantity = 1;\n\n$purchase->adjustments = array($adjustment);\n\n$subscription = new Recurly_Subscription();\n$subscription->plan_code = 'pp';\n\n$purchase->subscriptions = array($subscription);\n\n$purchase->coupon_codes = array('couponcode123', 'rqw311ofo6');\n\n$gift_card = new Recurly_GiftCard();\n$gift_card->redemption_code = \"FCJ7GEY4HO8WR16Q\";\n$purchase->gift_card = $gift_card;\n\n// Create a preview invoice collection\ntry {\n  $previewCollection = Recurly_Purchase::authorize($purchase);\n} catch (Recurly_ValidationError $e) {\n  // You can get an idea why a purchase failed looking at these objects:\n  var_dump($e);\n} ","language":"php"},{"code":"var accountCode = \"benjamin-du-monde\";\nvar currency = \"USD\";\nvar planCode = \"surveillance-pro\";\nvar couponCode = \"surveillance-podcast-promo\";\nvar giftCardRedemptionCode = \"8Z5VE6IRMWJDHU4P\";\n\n// We can create a purchase object from an account code or an Account object (first argument).\n// Use the Account object when you want create a new account. This works similar to Subscription.\nvar purchase = new Purchase(accountCode, currency);\n\nvar shipAddr = new ShippingAddress();\nshipAddr.Address1 = \"400 Alabama St\";\nshipAddr.City = \"San Francisco\";\nshipAddr.State = \"CA\";\nshipAddr.Country = \"US\";\nshipAddr.Zip = \"94110\";\nshipAddr.FirstName = \"Lon\";\nshipAddr.LastName = \"Dorner\";\nshipAddr.Nickname = \"home\";\npurchase.Account.ShippingAddresses.Add(shipAddr);\n\n// Add multiple adjustments (optional if subscription[s] included)\npurchase.Adjustments.Add(new Adjustment(4000, \"HD Camera\", 5));\npurchase.Adjustments.Add(new Adjustment(1000, \"Motion Sensor\", 10));\n\n// Add multiple subscriptions (optional if adjustment[s] included)\npurchase.Subscriptions.Add(new Subscription(planCode));\n\n// Add multiple coupon codes the customer may have (optional)\npurchase.CouponCodes.Add(couponCode);\n\n// Redeem a gift card with this purchase if the customer has redemption code (optional)\npurchase.GiftCardRedemptionCode = giftCardRedemptionCode;\n\n// For manual invoicing\n// purchase.CollectionMethod = Invoice.Collection.Manual;\n// purchase.NetTerms = 30;\n\n// Previewing allows us to run all calculations and validations without running the\n// transactions yet. This allows us to check the information and show the customer\n// the the detailed invoices before they confirm the purchase.\nvar previewCollection = Purchase.Authorize(purchase);","language":"csharp"},{"code":"purchase = recurly.Purchase(\n  currency = 'USD',\n  account = recurly.Account(\n    account_code = 'account-code-123',\n    billing_info = recurly.BillingInfo(\n        first_name = 'Benjamin',\n        last_name = 'DuMonde',\n        number = '4111-1111-1111-1111',\n        verification_value = '123',\n        month = 11,\n        year = 2020,\n        address1 = '123 Main St',\n        city = 'New Orleans',\n        state = 'LA',\n        zip = '70114',\n        country = 'US',\n    ),\n    shipping_addresses = [\n      recurly.ShippingAddress(\n          first_name = 'Lon',\n          last_name = 'Dorner',\n          address1 = '400 Alabama St',\n          city = 'San Francisco',\n          state = 'CA',\n          zip = '94110',\n          country = 'US',\n          nickname = 'home'\n      )\n    ]\n  ),\n  subscriptions = [\n      recurly.Subscription(plan_code = 'gold')\n  ],\n  adjustments = [\n      recurly.Adjustment(unit_amount_in_cents=1000, description='Item 1',\n                         quantity=1),\n      recurly.Adjustment(unit_amount_in_cents=2000, description='Item 2',\n                         quantity=2),\n  ]\n)\n\npreview_collection = purchase.authorize()\nprint(preview_collection)","language":"python"}]},"auth":"required","params":[{"_id":"591b66df7d2cb40f00d471d6","ref":"","in":"body","required":true,"desc":"An account object. This can be an existing account or a new account. If using a new account and adding shipping addresses, the last shipping address in the list will apply to every subscription and adjustment in the purchase.","default":"","type":"object","name":"account"},{"_id":"591b66df7d2cb40f00d471d5","ref":"","in":"body","required":true,"desc":"This should be a list of Adjustment objects. Required if there are no subscriptions.","default":"","type":"array_object","name":"adjustments"},{"_id":"591b66df7d2cb40f00d471d4","ref":"","in":"body","required":false,"desc":"The collection method for the invoice (`automatic` or `manual`).","default":"","type":"string","name":"collection_method"},{"_id":"591b66df7d2cb40f00d471d3","ref":"","in":"body","required":false,"desc":"The 3 letter currency code for the adjustments.","default":"","type":"string","name":"currency"},{"_id":"591b66df7d2cb40f00d471d2","ref":"","in":"body","required":false,"desc":"A po number for the resulting invoice.","default":"","type":"string","name":"po_number"},{"_id":"591b66df7d2cb40f00d471d1","ref":"","in":"body","required":false,"desc":"The net terms for the invoice","default":"","type":"int","name":"net_terms"},{"_id":"5955762bba6cff002966ae31","ref":"","in":"body","required":false,"desc":"A gift card with a redemption code to apply to this purchase","default":"","type":"object","name":"gift_card"},{"_id":"5955762bba6cff002966ae30","ref":"","in":"body","required":false,"desc":"A list of coupon codes to apply to this purchase","default":"","type":"array_string","name":"coupon_codes"},{"_id":"5955762bba6cff002966ae2f","ref":"","in":"body","required":true,"desc":"A list of Subscriptions to invoice in this purchase. Required if there are no adjustments.","default":"","type":"array_object","name":"subscriptions"},{"_id":"59d699316d3f930010333002","ref":"","in":"body","required":false,"desc":"Optional notes to show customer on the invoice. This will default to the Customer Notes text specified on the Invoice Settings page in your Recurly admin. Custom notes made on an invoice for a one time charge will not carry over to subsequent invoices.","default":"","type":"string","name":"customer_notes"},{"_id":"59d699316d3f930010333001","ref":"","in":"body","required":false,"desc":"Optional terms and conditions to show customer on the invoice. This will default to the Terms and Conditions text specified on the Invoice Settings page in your Recurly admin. Custom notes will stay with a subscription on all renewals.","default":"","type":"string","name":"terms_and_conditions"},{"_id":"59d699316d3f930010333000","ref":"","in":"body","required":false,"desc":"Optional VAT reverse charge notes to show the customer on the invoice. Only appears if you have EU VAT enabled or are using your own Avalara AvaTax account and the customer is in the EU, has a VAT number, and is in a different country than your own. This will default to the VAT Reverse Charge Notes text specified on the Tax Settings page in your Recurly admin, unless custom notes were created with the original subscription. Custom notes will stay with a subscription on all renewals.","default":"","type":"string","name":"vat_reverse_charge_notes"},{"_id":"5abbd2f4afef010029981f81","ref":"","in":"body","required":false,"desc":"All subscriptions and adjustments on the purchase will use this shipping address unless they specify one of their own. Any subscriptions for which this address might apply will also use it in future renewals unless changed or removed. Cannot be used if a new shipping address is created at the account level.","default":"","type":"long","name":"shipping_address_id"}],"url":"/purchases/authorize"},"isReference":true,"order":2,"body":"","excerpt":"A purchase is a hybrid checkout containing at least one or more subscriptions or one-time charges (adjustments) and supports both coupon and gift card redemptions. All items purchased will be on one invoice and paid for with one transaction. A purchase is only a request data type and is not persistent in Recurly and an invoice collection will be the returned type.\n\nThe authorize endpoint will create a pending purchase that can be activated at a later time once payment has been completed on an external source (e.g. Adyen's Hosted Payment Pages).","slug":"authorize-purchase","type":"post","title":"Authorize Purchase","__v":14,"childrenPages":[]}

postAuthorize Purchase

A purchase is a hybrid checkout containing at least one or more subscriptions or one-time charges (adjustments) and supports both coupon and gift card redemptions. All items purchased will be on one invoice and paid for with one transaction. A purchase is only a request data type and is not persistent in Recurly and an invoice collection will be the returned type. The authorize endpoint will create a pending purchase that can be activated at a later time once payment has been completed on an external source (e.g. Adyen's Hosted Payment Pages).

Body Params

account:
required
object
An account object. This can be an existing account or a new account. If using a new account and adding shipping addresses, the last shipping address in the list will apply to every subscription and adjustment in the purchase.
adjustments:
required
array of objects
This should be a list of Adjustment objects. Required if there are no subscriptions.
collection_method:
string
The collection method for the invoice (`automatic` or `manual`).
currency:
string
The 3 letter currency code for the adjustments.
po_number:
string
A po number for the resulting invoice.
net_terms:
integer
The net terms for the invoice
gift_card:
object
A gift card with a redemption code to apply to this purchase
coupon_codes:
array of strings
A list of coupon codes to apply to this purchase
subscriptions:
required
array of objects
A list of Subscriptions to invoice in this purchase. Required if there are no adjustments.
customer_notes:
string
Optional notes to show customer on the invoice. This will default to the Customer Notes text specified on the Invoice Settings page in your Recurly admin. Custom notes made on an invoice for a one time charge will not carry over to subsequent invoices.
terms_and_conditions:
string
Optional terms and conditions to show customer on the invoice. This will default to the Terms and Conditions text specified on the Invoice Settings page in your Recurly admin. Custom notes will stay with a subscription on all renewals.
vat_reverse_charge_notes:
string
Optional VAT reverse charge notes to show the customer on the invoice. Only appears if you have EU VAT enabled or are using your own Avalara AvaTax account and the customer is in the EU, has a VAT number, and is in a different country than your own. This will default to the VAT Reverse Charge Notes text specified on the Tax Settings page in your Recurly admin, unless custom notes were created with the original subscription. Custom notes will stay with a subscription on all renewals.
shipping_address_id:
long
All subscriptions and adjustments on the purchase will use this shipping address unless they specify one of their own. Any subscriptions for which this address might apply will also use it in future renewals unless changed or removed. Cannot be used if a new shipping address is created at the account level.

Definition

{{ api_url }}{{ page_api_url }}

Examples

<purchase>
  <collection_method>automatic</collection_method>
  <currency>USD</currency>
  <customer_notes>Some notes for the customer.</customer_notes>
  <terms_and_conditions>Our company terms and conditions.</terms_and_conditions>
  <vat_reverse_charge_notes>Vat reverse charge notes.</vat_reverse_charge_notes>
  <account>
    <account_code>c442b36c-c64f-41d7-b8e1-9c04e7a6ff82</account_code>
    <!-- email is required for this endpoint -->
    <email>benjamin.dumonde@example.com</email>
    <shipping_addresses>
      <shipping_address>
        <first_name>Lon</first_name>
        <last_name>Doner</last_name>
        <address1>221B Baker St.</address1>
        <city>London</city>
        <state></state>
        <zip>W1K 6AH</zip>
        <country>GB</country>
        <nickname>Home</nickname>
      </shipping_address>
    </shipping_addresses>
    <billing_info>
      <address1>400 Alabama St</address1>
      <city>San Francisco</city>
      <country>US</country>
      <first_name>Benjamin</first_name>
      <last_name>Du Monde</last_name>
      <month>12</month>
      <number>4111-1111-1111-1111</number>
      <state>CA</state>
      <year>2019</year>
      <zip>94110</zip>
      <!-- this field tells Recurly which external payment method will be used -->      
      <external_hpp_type>adyen</external_hpp_type>
    </billing_info>
  </account>
  <adjustments>
    <adjustment>
      <product_code>4549449c-5870-4845-b672-1d07f15e87dd</product_code>
      <quantity>1</quantity>
      <revenue_schedule_type>at_invoice</revenue_schedule_type>
      <unit_amount_in_cents>1000</unit_amount_in_cents>
      <description>Description of this adjustment</description>
    </adjustment>
  </adjustments>
  <subscriptions>
    <subscription>
      <plan_code>plan1</plan_code>
    </subscription>
  </subscriptions>
  <coupon_codes>
  	<coupon_code>coupon1</coupon_code>
    <coupon_code>coupon2</coupon_code>
  </coupon_codes>
  <gift_card>
    <redemption_code>ABC1234</redemption_code>
  </gift_card>
</purchase>
require 'securerandom'

purchase = Recurly::Purchase.new({
  currency: 'USD',
  collection_method: :automatic,
  account: {
    account_code: SecureRandom.uuid,
    billing_info: {
      first_name: 'Benjamin',
      last_name: 'Du Monde',
      address1: '400 Alabama St',
      city: 'San Francisco',
      state: 'CA',
      zip: '94110',
      country: 'US',
      number: '4111-1111-1111-1111',
      month: 12,
      year: 2019,
    },
    shipping_addresses: [
      {
        first_name: 'Lon',
        last_name: 'Dorner',
        address1: '400 Alabama St',
        city: 'San Francisco',
        state: 'CA',
        zip: '94110',
        country: 'US',
        nickname: 'home',
      }
    ]
  },
  subscriptions: [
    {
      plan_code: "gold",
    }
  ],
  adjustments: [
    {product_code: SecureRandom.uuid, unit_amount_in_cents: 1_000, quantity: 1, revenue_schedule_type: :at_invoice},
  ],
  coupon_codes: [
    "COUPON123",
    "COUPON345",
  ],
  gift_card: {
    redemption_code: "BC3749AB38371F273"
  }
})

begin
  preview_collection = Recurly::Purchase.authorize!(purchase)
  puts preview_collection.inspect
rescue Recurly::Resource::Invalid => e
  puts e.inspect
  # Invalid data
end
<?php

$purchase = new Recurly_Purchase();
$purchase->currency = 'USD';
$purchase->collection_method = 'automatic';
$purchase->account = new Recurly_Account();
$purchase->account->account_code = 'aba9209a-aa61-4790-8e61-0a2692435fee';
$purchase->account->email = "verena@example.com";
$purchase->account->first_name = "Benjamin";
$purchase->account->last_name = "Du Monde";
$purchase->account->address->phone = "555-555-5555";
$purchase->account->address->address1 = "123 Main St.";
$purchase->account->address->city = "San Francisco";
$purchase->account->address->state = "CA";
$purchase->account->address->zip = "94110";
$purchase->account->address->country = "US";

$billing_info = new Recurly_BillingInfo();
$billing_info->number = '4111-1111-1111-1111';
$billing_info->month = 12;
$billing_info->year = 2019;
$billing_info->verification_value = '123';
$billing_info->address1 = '400 Alabama St';
$billing_info->city = 'San Francisco';
$billing_info->state = 'CA';
$billing_info->country = 'US';
$billing_info->zip = '94110';

$purchase->account->billing_info = $billing_info;

$shipping_address = new Recurly_ShippingAddress();
$shipping_address->first_name = 'Lon';
$shipping_address->last_name = 'Dorner';
$shipping_address->address1 = '400 Dolores St';
$shipping_address->city = 'San Francisco';
$shipping_address->state = 'CA';
$shipping_address->country = 'US';
$shipping_address->zip = '94110';
$shipping_address->nickname = 'Home';

$purchase->account->shipping_addresses = array($shipping_address);

$adjustment = new Recurly_Adjustment();
$adjustment->unit_amount_in_cents = 1000;
$adjustment->quantity = 1;

$purchase->adjustments = array($adjustment);

$subscription = new Recurly_Subscription();
$subscription->plan_code = 'pp';

$purchase->subscriptions = array($subscription);

$purchase->coupon_codes = array('couponcode123', 'rqw311ofo6');

$gift_card = new Recurly_GiftCard();
$gift_card->redemption_code = "FCJ7GEY4HO8WR16Q";
$purchase->gift_card = $gift_card;

// Create a preview invoice collection
try {
  $previewCollection = Recurly_Purchase::authorize($purchase);
} catch (Recurly_ValidationError $e) {
  // You can get an idea why a purchase failed looking at these objects:
  var_dump($e);
} 
var accountCode = "benjamin-du-monde";
var currency = "USD";
var planCode = "surveillance-pro";
var couponCode = "surveillance-podcast-promo";
var giftCardRedemptionCode = "8Z5VE6IRMWJDHU4P";

// We can create a purchase object from an account code or an Account object (first argument).
// Use the Account object when you want create a new account. This works similar to Subscription.
var purchase = new Purchase(accountCode, currency);

var shipAddr = new ShippingAddress();
shipAddr.Address1 = "400 Alabama St";
shipAddr.City = "San Francisco";
shipAddr.State = "CA";
shipAddr.Country = "US";
shipAddr.Zip = "94110";
shipAddr.FirstName = "Lon";
shipAddr.LastName = "Dorner";
shipAddr.Nickname = "home";
purchase.Account.ShippingAddresses.Add(shipAddr);

// Add multiple adjustments (optional if subscription[s] included)
purchase.Adjustments.Add(new Adjustment(4000, "HD Camera", 5));
purchase.Adjustments.Add(new Adjustment(1000, "Motion Sensor", 10));

// Add multiple subscriptions (optional if adjustment[s] included)
purchase.Subscriptions.Add(new Subscription(planCode));

// Add multiple coupon codes the customer may have (optional)
purchase.CouponCodes.Add(couponCode);

// Redeem a gift card with this purchase if the customer has redemption code (optional)
purchase.GiftCardRedemptionCode = giftCardRedemptionCode;

// For manual invoicing
// purchase.CollectionMethod = Invoice.Collection.Manual;
// purchase.NetTerms = 30;

// Previewing allows us to run all calculations and validations without running the
// transactions yet. This allows us to check the information and show the customer
// the the detailed invoices before they confirm the purchase.
var previewCollection = Purchase.Authorize(purchase);
purchase = recurly.Purchase(
  currency = 'USD',
  account = recurly.Account(
    account_code = 'account-code-123',
    billing_info = recurly.BillingInfo(
        first_name = 'Benjamin',
        last_name = 'DuMonde',
        number = '4111-1111-1111-1111',
        verification_value = '123',
        month = 11,
        year = 2020,
        address1 = '123 Main St',
        city = 'New Orleans',
        state = 'LA',
        zip = '70114',
        country = 'US',
    ),
    shipping_addresses = [
      recurly.ShippingAddress(
          first_name = 'Lon',
          last_name = 'Dorner',
          address1 = '400 Alabama St',
          city = 'San Francisco',
          state = 'CA',
          zip = '94110',
          country = 'US',
          nickname = 'home'
      )
    ]
  ),
  subscriptions = [
      recurly.Subscription(plan_code = 'gold')
  ],
  adjustments = [
      recurly.Adjustment(unit_amount_in_cents=1000, description='Item 1',
                         quantity=1),
      recurly.Adjustment(unit_amount_in_cents=2000, description='Item 2',
                         quantity=2),
  ]
)

preview_collection = purchase.authorize()
print(preview_collection)

Result Format

<invoice_collection>
  <charge_invoice>
    <account href="https://your-subdomain.recurly.com/v2/accounts/1"/>
    <subscriptions href="https://your-subdomain.recurly.com/v2/invoices/1007/subscriptions"/>
    <address>
      <address1>123 Main St.</address1>
      <address2 nil="nil"/>
      <city>San Francisco</city>
      <state>CA</state>
      <zip>94105</zip>
      <country>US</country>
      <phone nil="nil"/>
    </address>
    <shipping_address>
      <first_name>Lon</first_name>
      <last_name>Doner</last_name>
      <address1>221B Baker St.</address1>
      <address2></address2>
      <city>London</city>
      <state></state>
      <zip>W1K 6AH</zip>
      <country>GB</country>
      <phone></phone>
    </shipping_address>
    <uuid>37c0057d2f641f4e2fcbda4b5b833633</uuid>
    <state>paid</state>
    <invoice_number_prefix/>
    <invoice_number type="integer">1007</invoice_number>
    <po_number nil="nil"/>
    <vat_number nil="nil"/>
    <subtotal_in_cents type="integer">2000</subtotal_in_cents>
    <discount_in_cents type="integer">0</discount_in_cents>
    <due_on type="datetime">2018-01-30T21:11:50Z</due_on>
    <balance_in_cents type="integer">0</balance_in_cents>
    <type>charge</type>
    <origin>purchase</origin>
    <credit_invoices href="https://your-subdomain.recurly.com/v2/invoices/1325/credit_invoices"/>
    <refundable_total_in_cents type="integer">2000</refundable_total_in_cents>
    <credit_payments type="array">
    </credit_payments>
    <tax_in_cents type="integer">424</tax_in_cents>
    <total_in_cents type="integer">5274</total_in_cents>
    <currency>EUR</currency>
    <created_at type="datetime">2016-08-03T16:26:26Z</created_at>
    <updated_at type="datetime">2016-08-03T16:26:26Z</updated_at>
    <closed_at type="datetime">2016-08-03T16:26:26Z</closed_at>
    <terms_and_conditions nil="nil"/>
    <customer_notes nil="nil"/>
    <tax_type>usst</tax_type>
    <tax_region>CA</tax_region>
    <tax_rate type="float">0.0875</tax_rate>
    <net_terms type="integer">0</net_terms>
    <collection_method>automatic</collection_method>
    <redemptions href="https://your-subdomain.recurly.com/v2/invoices/1007/redemptions"/>
    <line_items type="array">
      <adjustment href="https://your-subdomain.recurly.com/v2/adjustments/37c0057d2a3ace0c3f3d674ae89fdabd" type="charge">
        <account href="https://your-subdomain.recurly.com/v2/accounts/1"/>
        <invoice href="https://your-subdomain.recurly.com/v2/invoices/1007"/>
        <subscription href="https://your-subdomain.recurly.com/v2/subscriptions/37c0057cb105f67b6b8a1146f7b59c41"/>
        <uuid>37c0057d2a3ace0c3f3d674ae89fdabd</uuid>
        <state>invoiced</state>
        <description>Setup fee: Gold plan</description>
        <accounting_code nil="nil"/>
        <product_code>gold</product_code>
        <origin>setup_fee</origin>
        <unit_amount_in_cents type="integer">800</unit_amount_in_cents>
        <quantity type="integer">1</quantity>
        <discount_in_cents type="integer">0</discount_in_cents>
        <tax_in_cents type="integer">70</tax_in_cents>
        <total_in_cents type="integer">870</total_in_cents>
        <currency>EUR</currency>
        <taxable type="boolean">false</taxable>
        <tax_type>usst</tax_type>
        <tax_region>CA</tax_region>
        <tax_rate type="float">0.0875</tax_rate>
        <tax_exempt type="boolean">false</tax_exempt>
        <tax_code nil="nil"/>
        <start_date type="datetime">2016-08-03T16:26:26Z</start_date>
        <end_date nil="nil"/>
        <created_at type="datetime">2016-08-03T16:26:26Z</created_at>
        <updated_at type="datetime">2016-08-03T16:26:26Z</updated_at>
        <revenue_schedule_type>evenly</revenue_schedule_type>
      </adjustment>
      <!-- Continued... -->
    </line_items>
    <transactions type="array">
      <!-- Detail. -->
    </transactions>
    <a name="refund" href="https://your-subdomain.recurly.com/v2/invoices/1007/refund" method="post"/>
  </charge_invoice>
  <credit_invoices type="array">
  </credit_invoices>
</invoice_collection>


{"_id":"5b2d60111235f10003177401","project":"555fbba928249c1900618a82","version":"5b2d60111235f10003177402","category":"5b2d60111235f1000317734e","user":"55957fd09b8d0a25005a7d30","updates":[],"next":{"pages":[],"description":""},"createdAt":"2018-05-18T16:27:35.960Z","link_external":false,"link_url":"","githubsync":"","sync_unique":"","hidden":false,"api":{"examples":{"codes":[{"language":"xml","code":"<purchase>\n  <collection_method>automatic</collection_method>\n  <currency>USD</currency>\n  <customer_notes>Some notes for the customer.</customer_notes>\n  <terms_and_conditions>Our company terms and conditions.</terms_and_conditions>\n  <vat_reverse_charge_notes>Vat reverse charge notes.</vat_reverse_charge_notes>\n  <account>\n    <account_code>c442b36c-c64f-41d7-b8e1-9c04e7a6ff82</account_code>\n    <!-- email is required for this endpoint -->\n    <email>benjamin.dumonde@example.com</email>\n    <shipping_addresses>\n      <shipping_address>\n        <first_name>Lon</first_name>\n        <last_name>Doner</last_name>\n        <address1>221B Baker St.</address1>\n        <city>London</city>\n        <state></state>\n        <zip>W1K 6AH</zip>\n        <country>GB</country>\n        <nickname>Home</nickname>\n      </shipping_address>\n    </shipping_addresses>\n    <billing_info>\n      <address1>400 Alabama St</address1>\n      <city>San Francisco</city>\n      <country>US</country>\n      <first_name>Benjamin</first_name>\n      <last_name>Du Monde</last_name>\n      <month>12</month>\n      <number>4111-1111-1111-1111</number>\n      <state>CA</state>\n      <year>2019</year>\n      <zip>94110</zip>\n      <!-- this field tells Recurly which external payment method will be used -->      \n      <external_hpp_type>adyen</external_hpp_type>\n    </billing_info>\n  </account>\n  <adjustments>\n    <adjustment>\n      <product_code>4549449c-5870-4845-b672-1d07f15e87dd</product_code>\n      <quantity>1</quantity>\n      <revenue_schedule_type>at_invoice</revenue_schedule_type>\n      <unit_amount_in_cents>1000</unit_amount_in_cents>\n      <description>Description of this adjustment</description>\n    </adjustment>\n  </adjustments>\n  <subscriptions>\n    <subscription>\n      <plan_code>plan1</plan_code>\n    </subscription>\n  </subscriptions>\n  <coupon_codes>\n  \t<coupon_code>coupon1</coupon_code>\n    <coupon_code>coupon2</coupon_code>\n  </coupon_codes>\n  <gift_card>\n    <redemption_code>ABC1234</redemption_code>\n  </gift_card>\n</purchase>"},{"language":"ruby","code":"require 'securerandom'\n\npurchase = Recurly::Purchase.new({\n  currency: 'USD',\n  collection_method: :automatic,\n  account: {\n    account_code: SecureRandom.uuid,\n    billing_info: {\n      first_name: 'Benjamin',\n      last_name: 'Du Monde',\n      address1: '400 Alabama St',\n      city: 'San Francisco',\n      state: 'CA',\n      zip: '94110',\n      country: 'US',\n      number: '4111-1111-1111-1111',\n      month: 12,\n      year: 2019,\n    },\n    shipping_addresses: [\n      {\n        first_name: 'Lon',\n        last_name: 'Dorner',\n        address1: '400 Alabama St',\n        city: 'San Francisco',\n        state: 'CA',\n        zip: '94110',\n        country: 'US',\n        nickname: 'home',\n      }\n    ]\n  },\n  subscriptions: [\n    {\n      plan_code: \"gold\",\n    }\n  ],\n  adjustments: [\n    {product_code: SecureRandom.uuid, unit_amount_in_cents: 1_000, quantity: 1, revenue_schedule_type: :at_invoice},\n  ],\n  coupon_codes: [\n    \"COUPON123\",\n    \"COUPON345\",\n  ],\n  gift_card: {\n    redemption_code: \"BC3749AB38371F273\"\n  }\n})\n\nbegin\n  preview_collection = Recurly::Purchase.pending!(purchase)\n  puts preview_collection.inspect\nrescue Recurly::Resource::Invalid => e\n  puts e.inspect\n  # Invalid data\nend"},{"language":"php","code":"<?php\n\n$purchase = new Recurly_Purchase();\n$purchase->currency = 'USD';\n$purchase->collection_method = 'automatic';\n$purchase->account = new Recurly_Account();\n$purchase->account->account_code = 'aba9209a-aa61-4790-8e61-0a2692435fee';\n$purchase->account->email = \"verena@example.com\";\n$purchase->account->first_name = \"Benjamin\";\n$purchase->account->last_name = \"Du Monde\";\n$purchase->account->address->phone = \"555-555-5555\";\n$purchase->account->address->address1 = \"123 Main St.\";\n$purchase->account->address->city = \"San Francisco\";\n$purchase->account->address->state = \"CA\";\n$purchase->account->address->zip = \"94110\";\n$purchase->account->address->country = \"US\";\n\n$billing_info = new Recurly_BillingInfo();\n$billing_info->number = '4111-1111-1111-1111';\n$billing_info->month = 12;\n$billing_info->year = 2019;\n$billing_info->verification_value = '123';\n$billing_info->address1 = '400 Alabama St';\n$billing_info->city = 'San Francisco';\n$billing_info->state = 'CA';\n$billing_info->country = 'US';\n$billing_info->zip = '94110';\n\n$purchase->account->billing_info = $billing_info;\n\n$shipping_address = new Recurly_ShippingAddress();\n$shipping_address->first_name = 'Lon';\n$shipping_address->last_name = 'Dorner';\n$shipping_address->address1 = '400 Dolores St';\n$shipping_address->city = 'San Francisco';\n$shipping_address->state = 'CA';\n$shipping_address->country = 'US';\n$shipping_address->zip = '94110';\n$shipping_address->nickname = 'Home';\n\n$purchase->account->shipping_addresses = array($shipping_address);\n\n$adjustment = new Recurly_Adjustment();\n$adjustment->unit_amount_in_cents = 1000;\n$adjustment->quantity = 1;\n\n$purchase->adjustments = array($adjustment);\n\n$subscription = new Recurly_Subscription();\n$subscription->plan_code = 'pp';\n\n$purchase->subscriptions = array($subscription);\n\n$purchase->coupon_codes = array('couponcode123', 'rqw311ofo6');\n\n$gift_card = new Recurly_GiftCard();\n$gift_card->redemption_code = \"FCJ7GEY4HO8WR16Q\";\n$purchase->gift_card = $gift_card;\n\n// Create a preview invoice collection\ntry {\n  $previewCollection = Recurly_Purchase::pending($purchase);\n} catch (Recurly_ValidationError $e) {\n  // You can get an idea why a purchase failed looking at these objects:\n  var_dump($e);\n} "},{"language":"csharp","code":"var accountCode = \"benjamin-du-monde\";\nvar currency = \"USD\";\nvar planCode = \"surveillance-pro\";\nvar couponCode = \"surveillance-podcast-promo\";\nvar giftCardRedemptionCode = \"8Z5VE6IRMWJDHU4P\";\n\n// We can create a purchase object from an account code or an Account object (first argument).\n// Use the Account object when you want create a new account. This works similar to Subscription.\nvar purchase = new Purchase(accountCode, currency);\n\nvar shipAddr = new ShippingAddress();\nshipAddr.Address1 = \"400 Alabama St\";\nshipAddr.City = \"San Francisco\";\nshipAddr.State = \"CA\";\nshipAddr.Country = \"US\";\nshipAddr.Zip = \"94110\";\nshipAddr.FirstName = \"Lon\";\nshipAddr.LastName = \"Dorner\";\nshipAddr.Nickname = \"home\";\npurchase.Account.ShippingAddresses.Add(shipAddr);\n\n// Add multiple adjustments (optional if subscription[s] included)\npurchase.Adjustments.Add(new Adjustment(4000, \"HD Camera\", 5));\npurchase.Adjustments.Add(new Adjustment(1000, \"Motion Sensor\", 10));\n\n// Add multiple subscriptions (optional if adjustment[s] included)\npurchase.Subscriptions.Add(new Subscription(planCode));\n\n// Add multiple coupon codes the customer may have (optional)\npurchase.CouponCodes.Add(couponCode);\n\n// Redeem a gift card with this purchase if the customer has redemption code (optional)\npurchase.GiftCardRedemptionCode = giftCardRedemptionCode;\n\n// For manual invoicing\n// purchase.CollectionMethod = Invoice.Collection.Manual;\n// purchase.NetTerms = 30;\n\n// Previewing allows us to run all calculations and validations without running the\n// transactions yet. This allows us to check the information and show the customer\n// the the detailed invoices before they confirm the purchase.\nvar previewCollection = Purchase.Pending(purchase);"},{"language":"python","code":"purchase = recurly.Purchase(\n  currency = 'USD',\n  account = recurly.Account(\n    account_code = 'account-code-123',\n    billing_info = recurly.BillingInfo(\n        first_name = 'Benjamin',\n        last_name = 'DuMonde',\n        number = '4111-1111-1111-1111',\n        verification_value = '123',\n        month = 11,\n        year = 2020,\n        address1 = '123 Main St',\n        city = 'New Orleans',\n        state = 'LA',\n        zip = '70114',\n        country = 'US',\n    ),\n    shipping_addresses = [\n      recurly.ShippingAddress(\n          first_name = 'Lon',\n          last_name = 'Dorner',\n          address1 = '400 Alabama St',\n          city = 'San Francisco',\n          state = 'CA',\n          zip = '94110',\n          country = 'US',\n          nickname = 'home'\n      )\n    ]\n  ),\n  subscriptions = [\n      recurly.Subscription(plan_code = 'gold')\n  ],\n  adjustments = [\n      recurly.Adjustment(unit_amount_in_cents=1000, description='Item 1',\n                         quantity=1),\n      recurly.Adjustment(unit_amount_in_cents=2000, description='Item 2',\n                         quantity=2),\n  ]\n)\n\npreview_collection = purchase.pending()\nprint(preview_collection)"}]},"method":"post","results":{"codes":[{"name":"","code":"<invoice_collection>\n  <charge_invoice>\n    <account href=\"https://your-subdomain.recurly.com/v2/accounts/1\"/>\n    <subscriptions href=\"https://your-subdomain.recurly.com/v2/invoices/1007/subscriptions\"/>\n    <address>\n      <address1>123 Main St.</address1>\n      <address2 nil=\"nil\"/>\n      <city>San Francisco</city>\n      <state>CA</state>\n      <zip>94105</zip>\n      <country>US</country>\n      <phone nil=\"nil\"/>\n    </address>\n    <shipping_address>\n      <first_name>Lon</first_name>\n      <last_name>Doner</last_name>\n      <address1>221B Baker St.</address1>\n      <address2></address2>\n      <city>London</city>\n      <state></state>\n      <zip>W1K 6AH</zip>\n      <country>GB</country>\n      <phone></phone>\n    </shipping_address>\n    <uuid>37c0057d2f641f4e2fcbda4b5b833633</uuid>\n    <state>paid</state>\n    <invoice_number_prefix/>\n    <invoice_number type=\"integer\">1007</invoice_number>\n    <po_number nil=\"nil\"/>\n    <vat_number nil=\"nil\"/>\n    <subtotal_in_cents type=\"integer\">2000</subtotal_in_cents>\n    <discount_in_cents type=\"integer\">0</discount_in_cents>\n    <due_on type=\"datetime\">2018-01-30T21:11:50Z</due_on>\n    <balance_in_cents type=\"integer\">0</balance_in_cents>\n    <type>charge</type>\n    <origin>purchase</origin>\n    <credit_invoices href=\"https://your-subdomain.recurly.com/v2/invoices/1325/credit_invoices\"/>\n    <refundable_total_in_cents type=\"integer\">2000</refundable_total_in_cents>\n    <credit_payments type=\"array\">\n    </credit_payments>\n    <tax_in_cents type=\"integer\">424</tax_in_cents>\n    <total_in_cents type=\"integer\">5274</total_in_cents>\n    <currency>EUR</currency>\n    <created_at type=\"datetime\">2016-08-03T16:26:26Z</created_at>\n    <updated_at type=\"datetime\">2016-08-03T16:26:26Z</updated_at>\n    <closed_at type=\"datetime\">2016-08-03T16:26:26Z</closed_at>\n    <terms_and_conditions nil=\"nil\"/>\n    <customer_notes nil=\"nil\"/>\n    <tax_type>usst</tax_type>\n    <tax_region>CA</tax_region>\n    <tax_rate type=\"float\">0.0875</tax_rate>\n    <net_terms type=\"integer\">0</net_terms>\n    <collection_method>automatic</collection_method>\n    <redemptions href=\"https://your-subdomain.recurly.com/v2/invoices/1007/redemptions\"/>\n    <line_items type=\"array\">\n      <adjustment href=\"https://your-subdomain.recurly.com/v2/adjustments/37c0057d2a3ace0c3f3d674ae89fdabd\" type=\"charge\">\n        <account href=\"https://your-subdomain.recurly.com/v2/accounts/1\"/>\n        <invoice href=\"https://your-subdomain.recurly.com/v2/invoices/1007\"/>\n        <subscription href=\"https://your-subdomain.recurly.com/v2/subscriptions/37c0057cb105f67b6b8a1146f7b59c41\"/>\n        <uuid>37c0057d2a3ace0c3f3d674ae89fdabd</uuid>\n        <state>invoiced</state>\n        <description>Setup fee: Gold plan</description>\n        <accounting_code nil=\"nil\"/>\n        <product_code>gold</product_code>\n        <origin>setup_fee</origin>\n        <unit_amount_in_cents type=\"integer\">800</unit_amount_in_cents>\n        <quantity type=\"integer\">1</quantity>\n        <discount_in_cents type=\"integer\">0</discount_in_cents>\n        <tax_in_cents type=\"integer\">70</tax_in_cents>\n        <total_in_cents type=\"integer\">870</total_in_cents>\n        <currency>EUR</currency>\n        <taxable type=\"boolean\">false</taxable>\n        <tax_type>usst</tax_type>\n        <tax_region>CA</tax_region>\n        <tax_rate type=\"float\">0.0875</tax_rate>\n        <tax_exempt type=\"boolean\">false</tax_exempt>\n        <tax_code nil=\"nil\"/>\n        <start_date type=\"datetime\">2016-08-03T16:26:26Z</start_date>\n        <end_date nil=\"nil\"/>\n        <created_at type=\"datetime\">2016-08-03T16:26:26Z</created_at>\n        <updated_at type=\"datetime\">2016-08-03T16:26:26Z</updated_at>\n        <revenue_schedule_type>evenly</revenue_schedule_type>\n      </adjustment>\n      <!-- Continued... -->\n    </line_items>\n    <transactions type=\"array\">\n      <!-- Detail. -->\n    </transactions>\n    <a name=\"refund\" href=\"https://your-subdomain.recurly.com/v2/invoices/1007/refund\" method=\"post\"/>\n  </charge_invoice>\n  <credit_invoices type=\"array\">\n  </credit_invoices>\n</invoice_collection>","language":"xml","status":200}]},"settings":"","auth":"required","params":[{"_id":"591b66df7d2cb40f00d471d6","ref":"","in":"body","required":true,"desc":"An account object. This can be an existing account or a new account. If using a new account and adding shipping addresses, the last shipping address in the list will apply to every subscription and adjustment in the purchase.","default":"","type":"object","name":"account"},{"_id":"591b66df7d2cb40f00d471d5","ref":"","in":"body","required":true,"desc":"This should be a list of Adjustment objects. Required if there are no subscriptions.","default":"","type":"array_object","name":"adjustments"},{"_id":"591b66df7d2cb40f00d471d4","ref":"","in":"body","required":false,"desc":"The collection method for the invoice (`automatic` or `manual`).","default":"","type":"string","name":"collection_method"},{"_id":"591b66df7d2cb40f00d471d3","ref":"","in":"body","required":false,"desc":"The 3 letter currency code for the adjustments.","default":"","type":"string","name":"currency"},{"_id":"591b66df7d2cb40f00d471d2","ref":"","in":"body","required":false,"desc":"A po number for the resulting invoice.","default":"","type":"string","name":"po_number"},{"_id":"591b66df7d2cb40f00d471d1","ref":"","in":"body","required":false,"desc":"The net terms for the invoice","default":"","type":"int","name":"net_terms"},{"_id":"5955762bba6cff002966ae31","ref":"","in":"body","required":false,"desc":"A gift card with a redemption code to apply to this purchase","default":"","type":"object","name":"gift_card"},{"_id":"5955762bba6cff002966ae30","ref":"","in":"body","required":false,"desc":"A list of coupon codes to apply to this purchase","default":"","type":"array_string","name":"coupon_codes"},{"_id":"5955762bba6cff002966ae2f","ref":"","in":"body","required":true,"desc":"A list of Subscriptions to invoice in this purchase. Required if there are no adjustments.","default":"","type":"array_object","name":"subscriptions"},{"_id":"59d699316d3f930010333002","ref":"","in":"body","required":false,"desc":"Optional notes to show customer on the invoice. This will default to the Customer Notes text specified on the Invoice Settings page in your Recurly admin. Custom notes made on an invoice for a one time charge will not carry over to subsequent invoices.","default":"","type":"string","name":"customer_notes"},{"_id":"59d699316d3f930010333001","ref":"","in":"body","required":false,"desc":"Optional terms and conditions to show customer on the invoice. This will default to the Terms and Conditions text specified on the Invoice Settings page in your Recurly admin. Custom notes will stay with a subscription on all renewals.","default":"","type":"string","name":"terms_and_conditions"},{"_id":"59d699316d3f930010333000","ref":"","in":"body","required":false,"desc":"Optional VAT reverse charge notes to show the customer on the invoice. Only appears if you have EU VAT enabled or are using your own Avalara AvaTax account and the customer is in the EU, has a VAT number, and is in a different country than your own. This will default to the VAT Reverse Charge Notes text specified on the Tax Settings page in your Recurly admin, unless custom notes were created with the original subscription. Custom notes will stay with a subscription on all renewals.","default":"","type":"string","name":"vat_reverse_charge_notes"},{"_id":"5abbd2f4afef010029981f81","ref":"","in":"body","required":false,"desc":"All subscriptions and adjustments on the purchase will use this shipping address unless they specify one of their own. Any subscriptions for which this address might apply will also use it in future renewals unless changed or removed. Cannot be used if a new shipping address is created at the account level.","default":"","type":"long","name":"shipping_address_id"}],"url":"/purchases/pending"},"isReference":true,"order":999,"body":"","excerpt":"A purchase is a hybrid checkout containing at least one or more subscriptions or one-time charges (adjustments) and supports both coupon and gift card redemptions. All items purchased will be on one invoice and paid for with one transaction. A purchase is only a request data type and is not persistent in Recurly and an invoice collection will be the returned type.\n\nUse for Adyen HPP transaction requests. This runs the validations but not the transactions.","slug":"pending-purchase","type":"post","title":"Pending Purchase","__v":3,"childrenPages":[]}

postPending Purchase

A purchase is a hybrid checkout containing at least one or more subscriptions or one-time charges (adjustments) and supports both coupon and gift card redemptions. All items purchased will be on one invoice and paid for with one transaction. A purchase is only a request data type and is not persistent in Recurly and an invoice collection will be the returned type. Use for Adyen HPP transaction requests. This runs the validations but not the transactions.

Body Params

account:
required
object
An account object. This can be an existing account or a new account. If using a new account and adding shipping addresses, the last shipping address in the list will apply to every subscription and adjustment in the purchase.
adjustments:
required
array of objects
This should be a list of Adjustment objects. Required if there are no subscriptions.
collection_method:
string
The collection method for the invoice (`automatic` or `manual`).
currency:
string
The 3 letter currency code for the adjustments.
po_number:
string
A po number for the resulting invoice.
net_terms:
integer
The net terms for the invoice
gift_card:
object
A gift card with a redemption code to apply to this purchase
coupon_codes:
array of strings
A list of coupon codes to apply to this purchase
subscriptions:
required
array of objects
A list of Subscriptions to invoice in this purchase. Required if there are no adjustments.
customer_notes:
string
Optional notes to show customer on the invoice. This will default to the Customer Notes text specified on the Invoice Settings page in your Recurly admin. Custom notes made on an invoice for a one time charge will not carry over to subsequent invoices.
terms_and_conditions:
string
Optional terms and conditions to show customer on the invoice. This will default to the Terms and Conditions text specified on the Invoice Settings page in your Recurly admin. Custom notes will stay with a subscription on all renewals.
vat_reverse_charge_notes:
string
Optional VAT reverse charge notes to show the customer on the invoice. Only appears if you have EU VAT enabled or are using your own Avalara AvaTax account and the customer is in the EU, has a VAT number, and is in a different country than your own. This will default to the VAT Reverse Charge Notes text specified on the Tax Settings page in your Recurly admin, unless custom notes were created with the original subscription. Custom notes will stay with a subscription on all renewals.
shipping_address_id:
long
All subscriptions and adjustments on the purchase will use this shipping address unless they specify one of their own. Any subscriptions for which this address might apply will also use it in future renewals unless changed or removed. Cannot be used if a new shipping address is created at the account level.

Definition

{{ api_url }}{{ page_api_url }}

Examples

<purchase>
  <collection_method>automatic</collection_method>
  <currency>USD</currency>
  <customer_notes>Some notes for the customer.</customer_notes>
  <terms_and_conditions>Our company terms and conditions.</terms_and_conditions>
  <vat_reverse_charge_notes>Vat reverse charge notes.</vat_reverse_charge_notes>
  <account>
    <account_code>c442b36c-c64f-41d7-b8e1-9c04e7a6ff82</account_code>
    <!-- email is required for this endpoint -->
    <email>benjamin.dumonde@example.com</email>
    <shipping_addresses>
      <shipping_address>
        <first_name>Lon</first_name>
        <last_name>Doner</last_name>
        <address1>221B Baker St.</address1>
        <city>London</city>
        <state></state>
        <zip>W1K 6AH</zip>
        <country>GB</country>
        <nickname>Home</nickname>
      </shipping_address>
    </shipping_addresses>
    <billing_info>
      <address1>400 Alabama St</address1>
      <city>San Francisco</city>
      <country>US</country>
      <first_name>Benjamin</first_name>
      <last_name>Du Monde</last_name>
      <month>12</month>
      <number>4111-1111-1111-1111</number>
      <state>CA</state>
      <year>2019</year>
      <zip>94110</zip>
      <!-- this field tells Recurly which external payment method will be used -->      
      <external_hpp_type>adyen</external_hpp_type>
    </billing_info>
  </account>
  <adjustments>
    <adjustment>
      <product_code>4549449c-5870-4845-b672-1d07f15e87dd</product_code>
      <quantity>1</quantity>
      <revenue_schedule_type>at_invoice</revenue_schedule_type>
      <unit_amount_in_cents>1000</unit_amount_in_cents>
      <description>Description of this adjustment</description>
    </adjustment>
  </adjustments>
  <subscriptions>
    <subscription>
      <plan_code>plan1</plan_code>
    </subscription>
  </subscriptions>
  <coupon_codes>
  	<coupon_code>coupon1</coupon_code>
    <coupon_code>coupon2</coupon_code>
  </coupon_codes>
  <gift_card>
    <redemption_code>ABC1234</redemption_code>
  </gift_card>
</purchase>
require 'securerandom'

purchase = Recurly::Purchase.new({
  currency: 'USD',
  collection_method: :automatic,
  account: {
    account_code: SecureRandom.uuid,
    billing_info: {
      first_name: 'Benjamin',
      last_name: 'Du Monde',
      address1: '400 Alabama St',
      city: 'San Francisco',
      state: 'CA',
      zip: '94110',
      country: 'US',
      number: '4111-1111-1111-1111',
      month: 12,
      year: 2019,
    },
    shipping_addresses: [
      {
        first_name: 'Lon',
        last_name: 'Dorner',
        address1: '400 Alabama St',
        city: 'San Francisco',
        state: 'CA',
        zip: '94110',
        country: 'US',
        nickname: 'home',
      }
    ]
  },
  subscriptions: [
    {
      plan_code: "gold",
    }
  ],
  adjustments: [
    {product_code: SecureRandom.uuid, unit_amount_in_cents: 1_000, quantity: 1, revenue_schedule_type: :at_invoice},
  ],
  coupon_codes: [
    "COUPON123",
    "COUPON345",
  ],
  gift_card: {
    redemption_code: "BC3749AB38371F273"
  }
})

begin
  preview_collection = Recurly::Purchase.pending!(purchase)
  puts preview_collection.inspect
rescue Recurly::Resource::Invalid => e
  puts e.inspect
  # Invalid data
end
<?php

$purchase = new Recurly_Purchase();
$purchase->currency = 'USD';
$purchase->collection_method = 'automatic';
$purchase->account = new Recurly_Account();
$purchase->account->account_code = 'aba9209a-aa61-4790-8e61-0a2692435fee';
$purchase->account->email = "verena@example.com";
$purchase->account->first_name = "Benjamin";
$purchase->account->last_name = "Du Monde";
$purchase->account->address->phone = "555-555-5555";
$purchase->account->address->address1 = "123 Main St.";
$purchase->account->address->city = "San Francisco";
$purchase->account->address->state = "CA";
$purchase->account->address->zip = "94110";
$purchase->account->address->country = "US";

$billing_info = new Recurly_BillingInfo();
$billing_info->number = '4111-1111-1111-1111';
$billing_info->month = 12;
$billing_info->year = 2019;
$billing_info->verification_value = '123';
$billing_info->address1 = '400 Alabama St';
$billing_info->city = 'San Francisco';
$billing_info->state = 'CA';
$billing_info->country = 'US';
$billing_info->zip = '94110';

$purchase->account->billing_info = $billing_info;

$shipping_address = new Recurly_ShippingAddress();
$shipping_address->first_name = 'Lon';
$shipping_address->last_name = 'Dorner';
$shipping_address->address1 = '400 Dolores St';
$shipping_address->city = 'San Francisco';
$shipping_address->state = 'CA';
$shipping_address->country = 'US';
$shipping_address->zip = '94110';
$shipping_address->nickname = 'Home';

$purchase->account->shipping_addresses = array($shipping_address);

$adjustment = new Recurly_Adjustment();
$adjustment->unit_amount_in_cents = 1000;
$adjustment->quantity = 1;

$purchase->adjustments = array($adjustment);

$subscription = new Recurly_Subscription();
$subscription->plan_code = 'pp';

$purchase->subscriptions = array($subscription);

$purchase->coupon_codes = array('couponcode123', 'rqw311ofo6');

$gift_card = new Recurly_GiftCard();
$gift_card->redemption_code = "FCJ7GEY4HO8WR16Q";
$purchase->gift_card = $gift_card;

// Create a preview invoice collection
try {
  $previewCollection = Recurly_Purchase::pending($purchase);
} catch (Recurly_ValidationError $e) {
  // You can get an idea why a purchase failed looking at these objects:
  var_dump($e);
} 
var accountCode = "benjamin-du-monde";
var currency = "USD";
var planCode = "surveillance-pro";
var couponCode = "surveillance-podcast-promo";
var giftCardRedemptionCode = "8Z5VE6IRMWJDHU4P";

// We can create a purchase object from an account code or an Account object (first argument).
// Use the Account object when you want create a new account. This works similar to Subscription.
var purchase = new Purchase(accountCode, currency);

var shipAddr = new ShippingAddress();
shipAddr.Address1 = "400 Alabama St";
shipAddr.City = "San Francisco";
shipAddr.State = "CA";
shipAddr.Country = "US";
shipAddr.Zip = "94110";
shipAddr.FirstName = "Lon";
shipAddr.LastName = "Dorner";
shipAddr.Nickname = "home";
purchase.Account.ShippingAddresses.Add(shipAddr);

// Add multiple adjustments (optional if subscription[s] included)
purchase.Adjustments.Add(new Adjustment(4000, "HD Camera", 5));
purchase.Adjustments.Add(new Adjustment(1000, "Motion Sensor", 10));

// Add multiple subscriptions (optional if adjustment[s] included)
purchase.Subscriptions.Add(new Subscription(planCode));

// Add multiple coupon codes the customer may have (optional)
purchase.CouponCodes.Add(couponCode);

// Redeem a gift card with this purchase if the customer has redemption code (optional)
purchase.GiftCardRedemptionCode = giftCardRedemptionCode;

// For manual invoicing
// purchase.CollectionMethod = Invoice.Collection.Manual;
// purchase.NetTerms = 30;

// Previewing allows us to run all calculations and validations without running the
// transactions yet. This allows us to check the information and show the customer
// the the detailed invoices before they confirm the purchase.
var previewCollection = Purchase.Pending(purchase);
purchase = recurly.Purchase(
  currency = 'USD',
  account = recurly.Account(
    account_code = 'account-code-123',
    billing_info = recurly.BillingInfo(
        first_name = 'Benjamin',
        last_name = 'DuMonde',
        number = '4111-1111-1111-1111',
        verification_value = '123',
        month = 11,
        year = 2020,
        address1 = '123 Main St',
        city = 'New Orleans',
        state = 'LA',
        zip = '70114',
        country = 'US',
    ),
    shipping_addresses = [
      recurly.ShippingAddress(
          first_name = 'Lon',
          last_name = 'Dorner',
          address1 = '400 Alabama St',
          city = 'San Francisco',
          state = 'CA',
          zip = '94110',
          country = 'US',
          nickname = 'home'
      )
    ]
  ),
  subscriptions = [
      recurly.Subscription(plan_code = 'gold')
  ],
  adjustments = [
      recurly.Adjustment(unit_amount_in_cents=1000, description='Item 1',
                         quantity=1),
      recurly.Adjustment(unit_amount_in_cents=2000, description='Item 2',
                         quantity=2),
  ]
)

preview_collection = purchase.pending()
print(preview_collection)

Result Format

<invoice_collection>
  <charge_invoice>
    <account href="https://your-subdomain.recurly.com/v2/accounts/1"/>
    <subscriptions href="https://your-subdomain.recurly.com/v2/invoices/1007/subscriptions"/>
    <address>
      <address1>123 Main St.</address1>
      <address2 nil="nil"/>
      <city>San Francisco</city>
      <state>CA</state>
      <zip>94105</zip>
      <country>US</country>
      <phone nil="nil"/>
    </address>
    <shipping_address>
      <first_name>Lon</first_name>
      <last_name>Doner</last_name>
      <address1>221B Baker St.</address1>
      <address2></address2>
      <city>London</city>
      <state></state>
      <zip>W1K 6AH</zip>
      <country>GB</country>
      <phone></phone>
    </shipping_address>
    <uuid>37c0057d2f641f4e2fcbda4b5b833633</uuid>
    <state>paid</state>
    <invoice_number_prefix/>
    <invoice_number type="integer">1007</invoice_number>
    <po_number nil="nil"/>
    <vat_number nil="nil"/>
    <subtotal_in_cents type="integer">2000</subtotal_in_cents>
    <discount_in_cents type="integer">0</discount_in_cents>
    <due_on type="datetime">2018-01-30T21:11:50Z</due_on>
    <balance_in_cents type="integer">0</balance_in_cents>
    <type>charge</type>
    <origin>purchase</origin>
    <credit_invoices href="https://your-subdomain.recurly.com/v2/invoices/1325/credit_invoices"/>
    <refundable_total_in_cents type="integer">2000</refundable_total_in_cents>
    <credit_payments type="array">
    </credit_payments>
    <tax_in_cents type="integer">424</tax_in_cents>
    <total_in_cents type="integer">5274</total_in_cents>
    <currency>EUR</currency>
    <created_at type="datetime">2016-08-03T16:26:26Z</created_at>
    <updated_at type="datetime">2016-08-03T16:26:26Z</updated_at>
    <closed_at type="datetime">2016-08-03T16:26:26Z</closed_at>
    <terms_and_conditions nil="nil"/>
    <customer_notes nil="nil"/>
    <tax_type>usst</tax_type>
    <tax_region>CA</tax_region>
    <tax_rate type="float">0.0875</tax_rate>
    <net_terms type="integer">0</net_terms>
    <collection_method>automatic</collection_method>
    <redemptions href="https://your-subdomain.recurly.com/v2/invoices/1007/redemptions"/>
    <line_items type="array">
      <adjustment href="https://your-subdomain.recurly.com/v2/adjustments/37c0057d2a3ace0c3f3d674ae89fdabd" type="charge">
        <account href="https://your-subdomain.recurly.com/v2/accounts/1"/>
        <invoice href="https://your-subdomain.recurly.com/v2/invoices/1007"/>
        <subscription href="https://your-subdomain.recurly.com/v2/subscriptions/37c0057cb105f67b6b8a1146f7b59c41"/>
        <uuid>37c0057d2a3ace0c3f3d674ae89fdabd</uuid>
        <state>invoiced</state>
        <description>Setup fee: Gold plan</description>
        <accounting_code nil="nil"/>
        <product_code>gold</product_code>
        <origin>setup_fee</origin>
        <unit_amount_in_cents type="integer">800</unit_amount_in_cents>
        <quantity type="integer">1</quantity>
        <discount_in_cents type="integer">0</discount_in_cents>
        <tax_in_cents type="integer">70</tax_in_cents>
        <total_in_cents type="integer">870</total_in_cents>
        <currency>EUR</currency>
        <taxable type="boolean">false</taxable>
        <tax_type>usst</tax_type>
        <tax_region>CA</tax_region>
        <tax_rate type="float">0.0875</tax_rate>
        <tax_exempt type="boolean">false</tax_exempt>
        <tax_code nil="nil"/>
        <start_date type="datetime">2016-08-03T16:26:26Z</start_date>
        <end_date nil="nil"/>
        <created_at type="datetime">2016-08-03T16:26:26Z</created_at>
        <updated_at type="datetime">2016-08-03T16:26:26Z</updated_at>
        <revenue_schedule_type>evenly</revenue_schedule_type>
      </adjustment>
      <!-- Continued... -->
    </line_items>
    <transactions type="array">
      <!-- Detail. -->
    </transactions>
    <a name="refund" href="https://your-subdomain.recurly.com/v2/invoices/1007/refund" method="post"/>
  </charge_invoice>
  <credit_invoices type="array">
  </credit_invoices>
</invoice_collection>


{"_id":"5b2d60111235f1000317738e","category":"5b2d60111235f1000317734f","parentDoc":null,"project":"555fbba928249c1900618a82","user":"55648cf93b87582b003ab8b1","version":"5b2d60111235f10003177402","updates":["56cec52444c5700b0095c02b"],"next":{"pages":[],"description":""},"createdAt":"2015-08-31T20:16:33.273Z","link_external":false,"link_url":"","githubsync":"","sync_unique":"","hidden":false,"api":{"examples":{"codes":[{"code":"","language":"text"}]},"method":"get","results":{"codes":[{"language":"xml","code":"<account href=\"https://your-subdomain.recurly.com/v2/accounts/1\">\n  <adjustments href=\"https://your-subdomain.recurly.com/v2/accounts/1/adjustments\"/>\n  <billing_info href=\"https://your-subdomain.recurly.com/v2/accounts/1/billing_info\"/>\n  <invoices href=\"https://your-subdomain.recurly.com/v2/accounts/1/invoices\"/>\n  <redemptions href=\"https://your-subdomain.recurly.com/v2/accounts/1/redemptions\"/>\n  <subscriptions href=\"https://your-subdomain.recurly.com/v2/accounts/1/subscriptions\"/>\n  <transactions href=\"https://your-subdomain.recurly.com/v2/accounts/1/transactions\"/>\n  <account_code>1</account_code>\n  <state>active</state>\n  <username>verena1234</username>\n  <email>verena@example.com</email>\n  <cc_emails>bob@example.com,susan@example.com</cc_emails>\n  <first_name>Verena</first_name>\n  <last_name>Example</last_name>\n  <company_name>New Company Name</company_name>\n  <vat_number nil=\"nil\"/>\n  <tax_exempt type=\"boolean\">false</tax_exempt>\n  <address>\n    <address1>123 Main St.</address1>\n    <address2 nil=\"nil\"/>\n    <city>San Francisco</city>\n    <state>CA</state>\n    <zip>94105</zip>\n    <country>US</country>\n    <phone nil=\"nil\"/>\n  </address>\n  <accept_language nil=\"nil\"/>\n  <has_live_subscription type=\"boolean\">true</has_live_subscription>\n  <has_active_subscription type=\"boolean\">true</has_active_subscription>\n  <has_future_subscription type=\"boolean\">false</has_future_subscription>\n  <has_canceled_subscription type=\"boolean\">false</has_canceled_subscription>\n  <has_past_due_invoice type=\"boolean\">false</has_past_due_invoice>\n  <hosted_login_token>96e74bd5e14d18e6da463a0d638a2621</hosted_login_token>\n  <created_at type=\"datetime\">2016-07-08T20:59:43Z</created_at>\n  <updated_at type=\"datetime\">2016-07-11T17:56:24Z</updated_at>\n  <closed_at nil=\"nil\"/>\n</account>","name":"","status":200}]},"settings":"","auth":"required","params":[{"_id":"557f45d07eafa719001d1c2b","ref":"","in":"body","required":false,"desc":"The URL of adjustments for the specified account.","default":"","type":"string","name":"adjustments"},{"_id":"57a21cf65220910e002a1764","ref":"","in":"body","required":false,"desc":"The URL of the account balance for the specified account.","default":"","type":"string","name":"account_balance"},{"_id":"557f45d07eafa719001d1c2a","ref":"","in":"body","required":false,"desc":"The URL of billing info for the specified account.","default":"","type":"string","name":"billing_info"},{"_id":"557f45d07eafa719001d1c29","ref":"","in":"body","required":false,"desc":"The URL of invoices for the specified account.","default":"","type":"string","name":"invoices"},{"_id":"55e4aa556f190c1900a40881","ref":"","in":"body","required":false,"desc":"The URL of the coupon redemption for the specified account.","default":"","type":"string","name":"redemption"},{"_id":"55e4aa556f190c1900a40880","ref":"","in":"body","required":false,"desc":"The URL of subscriptions for the specified account.","default":"","type":"string","name":"subscriptions"},{"_id":"55e4aa556f190c1900a4087f","ref":"","in":"body","required":false,"desc":"The URL of transactions for the specified account.","default":"","type":"string","name":"transactions"},{"_id":"55e4aa556f190c1900a4087e","ref":"","in":"body","required":false,"desc":"The unique identifier of the account.","default":"","type":"string","name":"account_code"},{"_id":"55e4aa556f190c1900a4087d","ref":"","in":"body","required":false,"desc":"The state of accounts to return: `active` or `closed`.","default":"","type":"string","name":"state"},{"_id":"55e4aa556f190c1900a4087c","ref":"","in":"body","required":false,"desc":"The username of the account.","default":"","type":"string","name":"username"},{"_id":"55e4aa556f190c1900a4087b","ref":"","in":"body","required":false,"desc":"The email address of the account.","default":"","type":"string","name":"email"},{"_id":"560b18973bcbd80d0077d0c0","ref":"","in":"body","required":false,"desc":"Additional email address that should receive account correspondence. These should be separated only by commas. These CC emails will receive all emails that the `email` field also receives.","default":"","type":"array_string","name":"cc_emails"},{"_id":"55e4aa556f190c1900a4087a","ref":"","in":"body","required":false,"desc":"The first name of the account.","default":"","type":"string","name":"first_name"},{"_id":"55e4aa556f190c1900a40879","ref":"","in":"body","required":false,"desc":"The last name of the account.","default":"","type":"string","name":"last_name"},{"_id":"55e4aa556f190c1900a40878","ref":"","in":"body","required":false,"desc":"The company name of the account.","default":"","type":"string","name":"company_name"},{"_id":"55e4aa556f190c1900a40877","ref":"","in":"body","required":false,"desc":"The VAT number of the account (to avoid having the VAT applied).","default":"","type":"string","name":"vat_number"},{"_id":"55e4aa556f190c1900a40876","ref":"","in":"body","required":false,"desc":"The tax status of the account. `true` exempts tax on the account, `false` applies tax on the account.","default":"","type":"boolean","name":"tax_exempt"},{"_id":"55e4aa556f190c1900a40875","ref":"","in":"body","required":false,"desc":"The nested address information of the account: `address1`, `address2`, `city`, `state`, `zip`, `country`, `phone`.","default":"","type":"object","name":"address"},{"_id":"57fffdd8c7609a0f0063caaf","ref":"","in":"body","required":false,"desc":"The nested shipping address information of the account: `first_name`, `last_name`, `company_name`, `email`, `phone`, `vat_number`,  `address1`, `address2`, `city`, `state`, `zip`, `country`, `nickname`. You can pass in up to 20 account shipping addresses along with the request to create a new account. When providing a shipping address, the following are required: first_name, last_name, address1, city, state, zip, and country.","default":"","type":"object","name":"shipping_address"},{"_id":"55e4aa556f190c1900a40874","ref":"","in":"body","required":false,"desc":"The ISO 639-1 language code from the user's browser, indicating their preferred language and locale. This attribute is different from `preferred_locale` and does not determine which language emails sent on behalf of the merchant.","default":"","type":"string","name":"accept_language"},{"_id":"55e4aa556f190c1900a40873","ref":"","in":"body","required":false,"desc":"The unique token for automatically logging the account in to the hosted management pages. You may automatically log the user into their hosted management pages by directing the user to: `https://:subdomain.recurly.com/account/:hosted_login_token`.","default":"","type":"string","name":"hosted_login_token"},{"_id":"55e4aa556f190c1900a40872","ref":"","in":"body","required":false,"desc":"The date and time the account was created in Recurly.","default":"","type":"datetime","name":"created_at"},{"_id":"5783dc55359cd219005453ec","ref":"","in":"body","required":false,"desc":"The date and time the account or its billing info was last updated.","default":"","type":"datetime","name":"updated_at"},{"_id":"5783dcff359cd219005453ee","ref":"","in":"body","required":false,"desc":"For closed accounts, the date and time it was closed.","default":"","type":"datetime","name":"closed_at"},{"_id":"58c8255f5cb4fe1b00ec5679","ref":"","in":"body","required":false,"desc":"True if the account has at least one live subscription.","default":"","type":"boolean","name":"has_live_subscription"},{"_id":"58c8255f5cb4fe1b00ec5678","ref":"","in":"body","required":false,"desc":"True if the account has at least one active subscription.","default":"","type":"boolean","name":"has_active_subscription"},{"_id":"58c8255f5cb4fe1b00ec5677","ref":"","in":"body","required":false,"desc":"True if the account has at least one future subscription.","default":"","type":"boolean","name":"has_future_subscription"},{"_id":"58c8255f5cb4fe1b00ec5676","ref":"","in":"body","required":false,"desc":"True if the account has at least one canceled subscription.","default":"","type":"boolean","name":"has_canceled_subscription"},{"_id":"5ac2830272317b00330f50d6","ref":"","in":"body","required":false,"desc":"True if the account has at least one paused subscription.","default":"","type":"string","name":"has_paused_subscription"},{"_id":"58c8255f5cb4fe1b00ec5675","ref":"","in":"body","required":false,"desc":"True if the account has at least one past due invoice.","default":"","type":"boolean","name":"has_past_due_invoice"},{"_id":"5ad79af57097f700030f683c","ref":"","in":"body","required":false,"desc":"Used to determine the language and locale of emails sent on behalf of the merchant to the customer. The list of locales is restricted to those the merchant has enabled on the site.","default":"","type":"string","name":"preferred_locale"}],"url":"/accounts"},"isReference":true,"order":0,"body":"","excerpt":"Accounts are core to managing your customers inside of Recurly. The account object stores the entire Recurly history of your customer and acts as the entry point for working with a customer's billing information, subscription data, transactions, invoices and more.","slug":"account-object","type":"get","title":"Account Object","__v":3,"childrenPages":[]}

getAccount Object

Accounts are core to managing your customers inside of Recurly. The account object stores the entire Recurly history of your customer and acts as the entry point for working with a customer's billing information, subscription data, transactions, invoices and more.

Body Params

adjustments:
string
The URL of adjustments for the specified account.
account_balance:
string
The URL of the account balance for the specified account.
billing_info:
string
The URL of billing info for the specified account.
invoices:
string
The URL of invoices for the specified account.
redemption:
string
The URL of the coupon redemption for the specified account.
subscriptions:
string
The URL of subscriptions for the specified account.
transactions:
string
The URL of transactions for the specified account.
account_code:
string
The unique identifier of the account.
state:
string
The state of accounts to return: `active` or `closed`.
username:
string
The username of the account.
email:
string
The email address of the account.
cc_emails:
array of strings
Additional email address that should receive account correspondence. These should be separated only by commas. These CC emails will receive all emails that the `email` field also receives.
first_name:
string
The first name of the account.
last_name:
string
The last name of the account.
company_name:
string
The company name of the account.
vat_number:
string
The VAT number of the account (to avoid having the VAT applied).
tax_exempt:
boolean
The tax status of the account. `true` exempts tax on the account, `false` applies tax on the account.
address:
object
The nested address information of the account: `address1`, `address2`, `city`, `state`, `zip`, `country`, `phone`.
shipping_address:
object
The nested shipping address information of the account: `first_name`, `last_name`, `company_name`, `email`, `phone`, `vat_number`, `address1`, `address2`, `city`, `state`, `zip`, `country`, `nickname`. You can pass in up to 20 account shipping addresses along with the request to create a new account. When providing a shipping address, the following are required: first_name, last_name, address1, city, state, zip, and country.
accept_language:
string
The ISO 639-1 language code from the user's browser, indicating their preferred language and locale. This attribute is different from `preferred_locale` and does not determine which language emails sent on behalf of the merchant.
hosted_login_token:
string
The unique token for automatically logging the account in to the hosted management pages. You may automatically log the user into their hosted management pages by directing the user to: `https://:subdomain.recurly.com/account/:hosted_login_token`.
created_at:
datetime
The date and time the account was created in Recurly.
updated_at:
datetime
The date and time the account or its billing info was last updated.
closed_at:
datetime
For closed accounts, the date and time it was closed.
has_live_subscription:
boolean
True if the account has at least one live subscription.
has_active_subscription:
boolean
True if the account has at least one active subscription.
has_future_subscription:
boolean
True if the account has at least one future subscription.
has_canceled_subscription:
boolean
True if the account has at least one canceled subscription.
has_paused_subscription:
string
True if the account has at least one paused subscription.
has_past_due_invoice:
boolean
True if the account has at least one past due invoice.
preferred_locale:
string
Used to determine the language and locale of emails sent on behalf of the merchant to the customer. The list of locales is restricted to those the merchant has enabled on the site.

Definition

{{ api_url }}{{ page_api_url }}

Result Format

<account href="https://your-subdomain.recurly.com/v2/accounts/1">
  <adjustments href="https://your-subdomain.recurly.com/v2/accounts/1/adjustments"/>
  <billing_info href="https://your-subdomain.recurly.com/v2/accounts/1/billing_info"/>
  <invoices href="https://your-subdomain.recurly.com/v2/accounts/1/invoices"/>
  <redemptions href="https://your-subdomain.recurly.com/v2/accounts/1/redemptions"/>
  <subscriptions href="https://your-subdomain.recurly.com/v2/accounts/1/subscriptions"/>
  <transactions href="https://your-subdomain.recurly.com/v2/accounts/1/transactions"/>
  <account_code>1</account_code>
  <state>active</state>
  <username>verena1234</username>
  <email>verena@example.com</email>
  <cc_emails>bob@example.com,susan@example.com</cc_emails>
  <first_name>Verena</first_name>
  <last_name>Example</last_name>
  <company_name>New Company Name</company_name>
  <vat_number nil="nil"/>
  <tax_exempt type="boolean">false</tax_exempt>
  <address>
    <address1>123 Main St.</address1>
    <address2 nil="nil"/>
    <city>San Francisco</city>
    <state>CA</state>
    <zip>94105</zip>
    <country>US</country>
    <phone nil="nil"/>
  </address>
  <accept_language nil="nil"/>
  <has_live_subscription type="boolean">true</has_live_subscription>
  <has_active_subscription type="boolean">true</has_active_subscription>
  <has_future_subscription type="boolean">false</has_future_subscription>
  <has_canceled_subscription type="boolean">false</has_canceled_subscription>
  <has_past_due_invoice type="boolean">false</has_past_due_invoice>
  <hosted_login_token>96e74bd5e14d18e6da463a0d638a2621</hosted_login_token>
  <created_at type="datetime">2016-07-08T20:59:43Z</created_at>
  <updated_at type="datetime">2016-07-11T17:56:24Z</updated_at>
  <closed_at nil="nil"/>
</account>


{"_id":"5b2d60111235f1000317738f","category":"5b2d60111235f1000317734f","parentDoc":null,"user":"55648cf93b87582b003ab8b1","project":"555fbba928249c1900618a82","version":"5b2d60111235f10003177402","updates":["55f1f9abd4d3160d00439b6c"],"next":{"pages":[],"description":""},"createdAt":"2015-06-15T21:38:24.720Z","link_external":false,"link_url":"","githubsync":"","sync_unique":"","hidden":false,"api":{"results":{"codes":[{"name":"","status":200,"language":"xml","code":"<accounts type=\"array\">\n  <account href=\"https://your-subdomain.recurly.com/v2/accounts/1\">\n    <adjustments href=\"https://your-subdomain.recurly.com/v2/accounts/1/adjustments\"/>\n    <account_acquisition href=\"https://your-subdomain.recurly.com/v2/accounts/1/acquisition\"/>\n    <account_balance href=\"https://your-subdomain.recurly.com/v2/accounts/1/balance\"/>\n    <billing_info href=\"https://your-subdomain.recurly.com/v2/accounts/1/billing_info\"/>\n    <invoices href=\"https://your-subdomain.recurly.com/v2/accounts/1/invoices\"/>\n    <shipping_addresses href=\"https://your-subdomain.recurly.com/v2/accounts/1/shipping_addresses\"/>\n    <subscriptions href=\"https://your-subdomain.recurly.com/v2/accounts/1/subscriptions\"/>\n    <transactions href=\"https://your-subdomain.recurly.com/v2/accounts/1/transactions\"/>\n    <account_code>1</account_code>\n    <state>active</state>\n    <username>verena1234</username>\n    <email>verena@example.com</email>\n    <cc_emails>bob@example.com,susan@example.com</cc_emails>\n    <first_name>Verena</first_name>\n    <last_name>Example</last_name>\n    <company_name>New Company Name</company_name>\n    <vat_number nil=\"nil\"/>\n    <tax_exempt type=\"boolean\">false</tax_exempt>\n    <address>\n      <address1>123 Main St.</address1>\n      <address2 nil=\"nil\"/>\n      <city>San Francisco</city>\n      <state>CA</state>\n      <zip>94105</zip>\n      <country>US</country>\n      <phone nil=\"nil\"/>\n    </address>\n    <accept_language nil=\"nil\"/>\n    <hosted_login_token>71c122cb16fc90252ff845eacf5d7814</hosted_login_token>\n    <created_at type=\"datetime\">2016-08-03T15:44:05Z</created_at>\n    <updated_at type=\"datetime\">2017-03-15T21:22:18Z</updated_at>\n    <closed_at nil=\"nil\"/>\n    <has_live_subscription type=\"boolean\">false</has_live_subscription>\n    <has_active_subscription type=\"boolean\">false</has_active_subscription>\n    <has_future_subscription type=\"boolean\">false</has_future_subscription>\n    <has_canceled_subscription type=\"boolean\">false</has_canceled_subscription>\n    <has_past_due_invoice type=\"boolean\">false</has_past_due_invoice>\n  </account>\n</accounts>"}]},"settings":"","examples":{"codes":[{"language":"php","code":"<?php\n\n$accounts = Recurly_AccountList::getActive();\nforeach ($accounts as $account) {\n  print \"Account: $account\\n\";\n}\n","name":""},{"language":"ruby","code":"Recurly::Account.find_each do |account|\n  puts \"Account: #{account.inspect}\"\nend"},{"language":"python","code":"#client version 2.1.6+\nfor account in Account.all():\n    print 'Account: %s' % account\n\n#client version <= 2.1.5\naccounts = Account.all()\nwhile accounts:\n    for account in accounts:\n        print 'Account: %s' % account\n    try:\n        accounts = accounts.next_page()\n    except PageError:\n        accounts = ()"},{"code":"using System.Linq;\n\nvar accounts = Accounts.List();\nwhile (accounts.Any())\n{\n\tforeach (var account in accounts)\n\t\tConsole.WriteLine(account);\n\taccounts = accounts.Next;\n}","name":null,"language":"csharp"}]},"method":"get","auth":"required","params":[{"_id":"56465088054d8f0d00bc76aa","ref":"","in":"query","required":false,"desc":"The state of accounts to return: `active`, `closed`, `subscriber`, `non_subscriber`, `past_due`.","default":"","type":"string","name":"state"},{"_id":"578ea5b0c93aac0e00ec8899","ref":"","in":"query","required":false,"desc":"The attribute that will be used to order records: `created_at`, `updated_at`.","default":"created_at","type":"string","name":"sort"},{"_id":"578ea5b0c93aac0e00ec8898","ref":"","in":"query","required":false,"desc":"The order in which products will be returned: `asc` for ascending order, `desc` for descending order.","default":"desc","type":"string","name":"order"},{"_id":"578ea5b0c93aac0e00ec8897","ref":"","in":"query","required":false,"desc":"Operates on the attribute specified by the sort parameter. Filters records to only include those with datetimes greater than or equal to the supplied datetime. Accepts an ISO 8601 date or date and time.","default":"","type":"datetime","name":"begin_time"},{"_id":"578ea5b0c93aac0e00ec8896","ref":"","in":"query","required":false,"desc":"Operates on the attribute specified by the sort parameter. Filters records to only include those with datetimes less than or equal to the supplied datetime. Accepts an ISO 8601 date or date and time.","default":"","type":"datetime","name":"end_time"},{"_id":"56d8bace7ce7550b00c81d77","ref":"","in":"query","required":false,"desc":"Number of records to return per page, up to a maximum of 200.","default":"50","type":"int","name":"per_page"},{"_id":"56d8bace7ce7550b00c81d78","ref":"","in":"query","required":false,"desc":"Splits records across pages. Leave blank to return the first page. Follow the URI in the first page's Link header to fetch the next page.","default":"","type":"int","name":"cursor"}],"url":"/accounts"},"isReference":true,"order":1,"body":"###Account Query States\n[block:parameters]\n{\n  \"data\": {\n    \"h-0\": \"state\",\n    \"h-1\": \"description\",\n    \"0-0\": \"`active`\",\n    \"1-0\": \"`closed`\",\n    \"0-1\": \"Open accounts.\",\n    \"1-1\": \"Accounts that are not open.\",\n    \"2-0\": \"`subscriber`\",\n    \"2-1\": \"Accounts with subscriptions that are valid for the current time. This includes subscriptions in a trial period.\",\n    \"3-0\": \"`non_subscriber`\",\n    \"3-1\": \"Accounts without subscriptions that are valid for the current time.\",\n    \"4-0\": \"`past_due`\",\n    \"4-1\": \"Accounts with invoices that have failed initial collection but still have collection attempts remaining.\"\n  },\n  \"cols\": 2,\n  \"rows\": 5\n}\n[/block]\n\n[block:callout]\n{\n  \"type\": \"warning\",\n  \"body\": \"Please note: a queried state and the base state of a returned account may differ. For example, querying for `past_due` account will not result in a list of accounts with a `past_due` state (they will either be `active` or `closed`). Only base states (`active`, `closed`) will be present in the returned account records.\"\n}\n[/block]","excerpt":"Returns a list of accounts on your site. Results are ordered by the time created, sorted by newest first.","slug":"list-accounts","type":"get","title":"List Accounts","__v":0,"childrenPages":[]}

getList Accounts

Returns a list of accounts on your site. Results are ordered by the time created, sorted by newest first.

Query Params

state:
string
The state of accounts to return: `active`, `closed`, `subscriber`, `non_subscriber`, `past_due`.
sort:
stringcreated_at
The attribute that will be used to order records: `created_at`, `updated_at`.
order:
stringdesc
The order in which products will be returned: `asc` for ascending order, `desc` for descending order.
begin_time:
datetime
Operates on the attribute specified by the sort parameter. Filters records to only include those with datetimes greater than or equal to the supplied datetime. Accepts an ISO 8601 date or date and time.
end_time:
datetime
Operates on the attribute specified by the sort parameter. Filters records to only include those with datetimes less than or equal to the supplied datetime. Accepts an ISO 8601 date or date and time.
per_page:
integer50
Number of records to return per page, up to a maximum of 200.
cursor:
integer
Splits records across pages. Leave blank to return the first page. Follow the URI in the first page's Link header to fetch the next page.

Account Query States

state
description

active

Open accounts.

closed

Accounts that are not open.

subscriber

Accounts with subscriptions that are valid for the current time. This includes subscriptions in a trial period.

non_subscriber

Accounts without subscriptions that are valid for the current time.

past_due

Accounts with invoices that have failed initial collection but still have collection attempts remaining.

Please note: a queried state and the base state of a returned account may differ. For example, querying for past_due account will not result in a list of accounts with a past_due state (they will either be active or closed). Only base states (active, closed) will be present in the returned account records.

Definition

{{ api_url }}{{ page_api_url }}

Examples

<?php

$accounts = Recurly_AccountList::getActive();
foreach ($accounts as $account) {
  print "Account: $account\n";
}
Recurly::Account.find_each do |account|
  puts "Account: #{account.inspect}"
end
#client version 2.1.6+
for account in Account.all():
    print 'Account: %s' % account

#client version <= 2.1.5
accounts = Account.all()
while accounts:
    for account in accounts:
        print 'Account: %s' % account
    try:
        accounts = accounts.next_page()
    except PageError:
        accounts = ()
using System.Linq;

var accounts = Accounts.List();
while (accounts.Any())
{
	foreach (var account in accounts)
		Console.WriteLine(account);
	accounts = accounts.Next;
}

Result Format

<accounts type="array">
  <account href="https://your-subdomain.recurly.com/v2/accounts/1">
    <adjustments href="https://your-subdomain.recurly.com/v2/accounts/1/adjustments"/>
    <account_acquisition href="https://your-subdomain.recurly.com/v2/accounts/1/acquisition"/>
    <account_balance href="https://your-subdomain.recurly.com/v2/accounts/1/balance"/>
    <billing_info href="https://your-subdomain.recurly.com/v2/accounts/1/billing_info"/>
    <invoices href="https://your-subdomain.recurly.com/v2/accounts/1/invoices"/>
    <shipping_addresses href="https://your-subdomain.recurly.com/v2/accounts/1/shipping_addresses"/>
    <subscriptions href="https://your-subdomain.recurly.com/v2/accounts/1/subscriptions"/>
    <transactions href="https://your-subdomain.recurly.com/v2/accounts/1/transactions"/>
    <account_code>1</account_code>
    <state>active</state>
    <username>verena1234</username>
    <email>verena@example.com</email>
    <cc_emails>bob@example.com,susan@example.com</cc_emails>
    <first_name>Verena</first_name>
    <last_name>Example</last_name>
    <company_name>New Company Name</company_name>
    <vat_number nil="nil"/>
    <tax_exempt type="boolean">false</tax_exempt>
    <address>
      <address1>123 Main St.</address1>
      <address2 nil="nil"/>
      <city>San Francisco</city>
      <state>CA</state>
      <zip>94105</zip>
      <country>US</country>
      <phone nil="nil"/>
    </address>
    <accept_language nil="nil"/>
    <hosted_login_token>71c122cb16fc90252ff845eacf5d7814</hosted_login_token>
    <created_at type="datetime">2016-08-03T15:44:05Z</created_at>
    <updated_at type="datetime">2017-03-15T21:22:18Z</updated_at>
    <closed_at nil="nil"/>
    <has_live_subscription type="boolean">false</has_live_subscription>
    <has_active_subscription type="boolean">false</has_active_subscription>
    <has_future_subscription type="boolean">false</has_future_subscription>
    <has_canceled_subscription type="boolean">false</has_canceled_subscription>
    <has_past_due_invoice type="boolean">false</has_past_due_invoice>
  </account>
</accounts>


{"_id":"5b2d60111235f10003177390","category":"5b2d60111235f1000317734f","project":"555fbba928249c1900618a82","parentDoc":null,"user":"55648cf93b87582b003ab8b1","version":"5b2d60111235f10003177402","updates":["562908002c0fd9190067da26"],"next":{"pages":[],"description":""},"createdAt":"2015-06-15T20:12:03.880Z","link_external":false,"link_url":"","githubsync":"","sync_unique":"","hidden":false,"api":{"examples":{"codes":[{"language":"php","code":"<?php\n  \ntry {\n  $account = new Recurly_Account('b6f5783');\n  $account->email = 'verena@example.com';\n  $account->first_name = 'Verena';\n  $account->last_name = 'Example';\n  $account->create();\n\n  print \"Account: $account\\n\";\n\n} catch (Recurly_ValidationError $e) {\n  print \"Invalid Account: $e\";\n}","name":""},{"language":"ruby","code":"account = Recurly::Account.create(\n  :account_code => '1',\n  :email        => 'verena@example.com',\n  :first_name   => 'Verena',\n  :last_name    => 'Example',\n    :shipping_addresses => [\n      {\n          :nickname => 'Work',\n            :first_name => 'Verena',\n            :last_name => 'Example',\n            :company => 'Recurly Inc',\n            :phone => '555-222-1212',\n            :email => 'verena@example.com',\n            :address1 => '123 Main St.',\n            :address2 => 'Suite 101',\n            :city => 'San Francisco',\n            :state => 'CA',\n            :zip => '94105',\n            :country => 'US'\n        },\n        {\n          :nickname => 'Home',\n            :first_name => 'Verena',\n            :last_name => 'Example',\n            :phone => '555-867-5309',\n            :email => 'verena@example.com',\n            :address1 => '123 Fourth St.',\n            :address2 => 'Apt. 101',\n            :city => 'San Francisco',\n            :state => 'CA',\n            :zip => '94105',\n            :country => 'US'\n        }\n    ]\n)"},{"language":"python","code":"account = recurly.Account(account_code='1')\naccount.email = 'verena@example.com'\naccount.first_name = 'Verena'\naccount.last_name = 'Example'\naccount.save()"},{"language":"csharp","code":"var account = new Account(\"1\")\n{\n  Email = \"verena@example.com\",\n  FirstName = \"Verena\",\n  LastName = \"Example\"\n};\naccount.Create();"},{"code":"<account>\n  <account_code>1</account_code>\n  <email>verena@example.com</email>\n  <first_name>Verena</first_name>\n  <last_name>Example</last_name>\n  <username>verena1234</username>\n  <cc_emails>bob@example.com,susan@example.com</cc_emails>\n  <company_name>Recurly Inc</company_name>\n  <preferred_locale>en-US</preferred_locale>\n  <address>\n    <address1>123 Main St.</address1>\n    <city>San Francisco</city>\n    <state>CA</state>\n    <zip>94105</zip>\n    <country>US</country>\n  </address>\n  <shipping_addresses>\n    <shipping_address>\n      <nickname>Work</nickname>\n      <first_name>Verena</first_name>\n      <last_name>Example</last_name>\n      <company>Recurly Inc</company>\n      <phone>555-222-1212</phone>\n      <email>verena@example.com</email>\n      <address1>123 Main St.</address1>\n      <address2>Suite 101</address2>\n      <city>San Francisco</city>\n      <state>CA</state>\n      <zip>94105</zip>\n      <country>US</country>\n    </shipping_address>\n    <shipping_address>\n      <nickname>Home</nickname>\n      <first_name>Verena</first_name>\n      <last_name>Example</last_name>\n      <phone>555-867-5309</phone>\n      <email>verena@example.com</email>\n      <address1>123 Fourth St.</address1>\n      <address2>Apt. 101</address2>\n      <city>San Francisco</city>\n      <state>CA</state>\n      <zip>94105</zip>\n      <country>US</country>\n    </shipping_address>\n  </shipping_addresses>\n</account>","language":"xml"}]},"method":"post","results":{"codes":[{"status":201,"language":"xml","code":"<account href=\"https://your-subdomain.recurly.com/v2/accounts/1\">\n  <adjustments href=\"https://your-subdomain.recurly.com/v2/accounts/1/adjustments\"/>\n  <billing_info href=\"https://your-subdomain.recurly.com/v2/accounts/1/billing_info\"/>\n  <invoices href=\"https://your-subdomain.recurly.com/v2/accounts/1/invoices\"/>\n  <redemption href=\"https://your-subdomain.recurly.com/v2/accounts/1/redemption\"/>\n  <shipping_addresses href=\"https://your-subdomain.recurly.com/v2/accounts/1/shipping_addresses\"/>\n  <subscriptions href=\"https://your-subdomain.recurly.com/v2/accounts/1/subscriptions\"/>\n  <transactions href=\"https://your-subdomain.recurly.com/v2/accounts/1/transactions\"/>\n  <account_code>1</account_code>\n  <state>active</state>\n  <username>verena1234</username>\n  <email>verena@example.com</email>\n  <cc_emails>bob@example.com,susan@example.com</cc_emails>\n  <first_name>Verena</first_name>\n  <last_name>Example</last_name>\n  <company_name>Recurly Inc</company_name>\n  <vat_number nil=\"nil\"/>\n  <address>\n    <address1>123 Main St.</address1>\n    <address2 nil=\"nil\"/>\n    <city>San Francisco</city>\n    <state>CA</state>\n    <zip>94105</zip>\n    <country>US</country>\n    <phone nil=\"nil\"/>\n  </address>\n  <accept_language nil=\"nil\"/>\n  <hosted_login_token>3ed66441313a90bd7e8039b31985dee8</hosted_login_token>\n  <created_at type=\"datetime\">2016-06-14T16:08:41Z</created_at>\n  <closed_at nil=\"nil\"/>\n</account>","name":""}]},"settings":"","auth":"required","params":[{"_id":"557f3209e211d20d00601425","ref":"","in":"body","required":true,"desc":"A unique identifier used by your application to identify the account. This code may only contain the following characters: [a-z 0-9 @ - _ .] but it may not begin with a dot or hyphen character. Max of 50 characters.","default":"","type":"string","name":"account_code"},{"_id":"557f3209e211d20d00601424","ref":"","in":"body","required":false,"desc":"The username for the account, ignore if you do not use usernames. Max of 255 characters.","default":"","type":"string","name":"username"},{"_id":"557f3209e211d20d00601423","ref":"","in":"body","required":false,"desc":"The email address for the account.","default":"","type":"string","name":"email"},{"_id":"557f32d1e211d20d00601430","ref":"","in":"body","required":false,"desc":"The first name for the account. Max of 255 characters.","default":"","type":"string","name":"first_name"},{"_id":"557f32d1e211d20d0060142f","ref":"","in":"body","required":false,"desc":"The last name for the account.  Max of 255 characters.","default":"","type":"string","name":"last_name"},{"_id":"557f32d1e211d20d0060142e","ref":"","in":"body","required":false,"desc":"The company name for the account. Max of 50 characters.","default":"","type":"string","name":"company_name"},{"_id":"557f32d1e211d20d0060142d","ref":"","in":"body","required":false,"desc":"The VAT number to avoid having the VAT applied (if applicable).","default":"","type":"string","name":"vat_number"},{"_id":"557f32d1e211d20d0060142c","ref":"","in":"body","required":false,"desc":"The tax status for the account.","default":"","type":"boolean","name":"tax_exempt"},{"_id":"557f32d1e211d20d0060142b","ref":"","in":"body","required":false,"desc":"The Avalara AvaTax value that can be passed to identify the customer type for tax purposes. The range of values can be A - R (more info at Avalara). Value is case-sensitive.","default":"","type":"string","name":"entity_use_code"},{"_id":"58cffafa2cb80d1b005486a8","ref":"","in":"body","required":false,"desc":"The nested account acquisition information: `cost_in_cents`, `currency`, `channel`, `subchannel`, `campaign`","default":"","type":"object","name":"account_acquisition"},{"_id":"557f32d1e211d20d0060142a","ref":"","in":"body","required":false,"desc":"The nested billing information. If present, the account will only be created after the billing information is validated.","default":"","type":"object","name":"billing_info"},{"_id":"557f32d1e211d20d00601429","ref":"","in":"body","required":false,"desc":"The nested address information for the account: `address1`, `address2`, `city`, `state`, `zip`, `country`, `phone`.","default":"","type":"object","name":"address"},{"_id":"58010a4657be4b1900eaf2a6","ref":"","in":"body","required":false,"desc":"The nested shipping address information of the account: `first_name`, `last_name`, `company_name`, `email`, `phone`, `vat_number`,  `address1`, `address2`, `city`, `state`, `zip`, `country`, `nickname`. You can pass in up to 20 account shipping addresses along with the request to create a new account. When providing a shipping address, the following are required: first_name, last_name, address1, city, state, zip, and country.","default":"","type":"object","name":"shipping_address"},{"_id":"557f32d1e211d20d00601428","ref":"","in":"body","required":false,"desc":"The ISO 639-1 language code from the user's browser, indicating their preferred language and locale.","default":"","type":"string","name":"accept_language"},{"_id":"561c362cd308ee0d00749370","ref":"","in":"body","required":false,"desc":"Additional email address that should receive account correspondence. These should be separated only by commas. These CC emails will receive all emails that the `email` field also receives.","default":"","type":"array_string","name":"cc_emails"},{"_id":"5ad79b55f7096b0003956a9d","ref":"","in":"body","required":false,"desc":"Used to determine the language and locale of emails sent on behalf of the merchant to the customer. The list of locales is restricted to those the merchant has enabled on the site.","default":"","type":"string","name":"preferred_locale"}],"url":"/accounts"},"isReference":true,"order":2,"body":"","excerpt":"Creates a new account. You may optionally include billing information.","slug":"create-an-account","type":"post","title":"Create Account","__v":1,"childrenPages":[]}

postCreate Account

Creates a new account. You may optionally include billing information.

Body Params

account_code:
required
string
A unique identifier used by your application to identify the account. This code may only contain the following characters: [a-z 0-9 @ - _ .] but it may not begin with a dot or hyphen character. Max of 50 characters.
username:
string
The username for the account, ignore if you do not use usernames. Max of 255 characters.
email:
string
The email address for the account.
first_name:
string
The first name for the account. Max of 255 characters.
last_name:
string
The last name for the account. Max of 255 characters.
company_name:
string
The company name for the account. Max of 50 characters.
vat_number:
string
The VAT number to avoid having the VAT applied (if applicable).
tax_exempt:
boolean
The tax status for the account.
entity_use_code:
string
The Avalara AvaTax value that can be passed to identify the customer type for tax purposes. The range of values can be A - R (more info at Avalara). Value is case-sensitive.
account_acquisition:
object
The nested account acquisition information: `cost_in_cents`, `currency`, `channel`, `subchannel`, `campaign`
billing_info:
object
The nested billing information. If present, the account will only be created after the billing information is validated.
address:
object
The nested address information for the account: `address1`, `address2`, `city`, `state`, `zip`, `country`, `phone`.
shipping_address:
object
The nested shipping address information of the account: `first_name`, `last_name`, `company_name`, `email`, `phone`, `vat_number`, `address1`, `address2`, `city`, `state`, `zip`, `country`, `nickname`. You can pass in up to 20 account shipping addresses along with the request to create a new account. When providing a shipping address, the following are required: first_name, last_name, address1, city, state, zip, and country.
accept_language:
string
The ISO 639-1 language code from the user's browser, indicating their preferred language and locale.
cc_emails:
array of strings
Additional email address that should receive account correspondence. These should be separated only by commas. These CC emails will receive all emails that the `email` field also receives.
preferred_locale:
string
Used to determine the language and locale of emails sent on behalf of the merchant to the customer. The list of locales is restricted to those the merchant has enabled on the site.

Definition

{{ api_url }}{{ page_api_url }}

Examples

<?php
  
try {
  $account = new Recurly_Account('b6f5783');
  $account->email = 'verena@example.com';
  $account->first_name = 'Verena';
  $account->last_name = 'Example';
  $account->create();

  print "Account: $account\n";

} catch (Recurly_ValidationError $e) {
  print "Invalid Account: $e";
}
account = Recurly::Account.create(
  :account_code => '1',
  :email        => 'verena@example.com',
  :first_name   => 'Verena',
  :last_name    => 'Example',
    :shipping_addresses => [
      {
          :nickname => 'Work',
            :first_name => 'Verena',
            :last_name => 'Example',
            :company => 'Recurly Inc',
            :phone => '555-222-1212',
            :email => 'verena@example.com',
            :address1 => '123 Main St.',
            :address2 => 'Suite 101',
            :city => 'San Francisco',
            :state => 'CA',
            :zip => '94105',
            :country => 'US'
        },
        {
          :nickname => 'Home',
            :first_name => 'Verena',
            :last_name => 'Example',
            :phone => '555-867-5309',
            :email => 'verena@example.com',
            :address1 => '123 Fourth St.',
            :address2 => 'Apt. 101',
            :city => 'San Francisco',
            :state => 'CA',
            :zip => '94105',
            :country => 'US'
        }
    ]
)
account = recurly.Account(account_code='1')
account.email = 'verena@example.com'
account.first_name = 'Verena'
account.last_name = 'Example'
account.save()
var account = new Account("1")
{
  Email = "verena@example.com",
  FirstName = "Verena",
  LastName = "Example"
};
account.Create();
<account>
  <account_code>1</account_code>
  <email>verena@example.com</email>
  <first_name>Verena</first_name>
  <last_name>Example</last_name>
  <username>verena1234</username>
  <cc_emails>bob@example.com,susan@example.com</cc_emails>
  <company_name>Recurly Inc</company_name>
  <preferred_locale>en-US</preferred_locale>
  <address>
    <address1>123 Main St.</address1>
    <city>San Francisco</city>
    <state>CA</state>
    <zip>94105</zip>
    <country>US</country>
  </address>
  <shipping_addresses>
    <shipping_address>
      <nickname>Work</nickname>
      <first_name>Verena</first_name>
      <last_name>Example</last_name>
      <company>Recurly Inc</company>
      <phone>555-222-1212</phone>
      <email>verena@example.com</email>
      <address1>123 Main St.</address1>
      <address2>Suite 101</address2>
      <city>San Francisco</city>
      <state>CA</state>
      <zip>94105</zip>
      <country>US</country>
    </shipping_address>
    <shipping_address>
      <nickname>Home</nickname>
      <first_name>Verena</first_name>
      <last_name>Example</last_name>
      <phone>555-867-5309</phone>
      <email>verena@example.com</email>
      <address1>123 Fourth St.</address1>
      <address2>Apt. 101</address2>
      <city>San Francisco</city>
      <state>CA</state>
      <zip>94105</zip>
      <country>US</country>
    </shipping_address>
  </shipping_addresses>
</account>

Result Format

<account href="https://your-subdomain.recurly.com/v2/accounts/1">
  <adjustments href="https://your-subdomain.recurly.com/v2/accounts/1/adjustments"/>
  <billing_info href="https://your-subdomain.recurly.com/v2/accounts/1/billing_info"/>
  <invoices href="https://your-subdomain.recurly.com/v2/accounts/1/invoices"/>
  <redemption href="https://your-subdomain.recurly.com/v2/accounts/1/redemption"/>
  <shipping_addresses href="https://your-subdomain.recurly.com/v2/accounts/1/shipping_addresses"/>
  <subscriptions href="https://your-subdomain.recurly.com/v2/accounts/1/subscriptions"/>
  <transactions href="https://your-subdomain.recurly.com/v2/accounts/1/transactions"/>
  <account_code>1</account_code>
  <state>active</state>
  <username>verena1234</username>
  <email>verena@example.com</email>
  <cc_emails>bob@example.com,susan@example.com</cc_emails>
  <first_name>Verena</first_name>
  <last_name>Example</last_name>
  <company_name>Recurly Inc</company_name>
  <vat_number nil="nil"/>
  <address>
    <address1>123 Main St.</address1>
    <address2 nil="nil"/>
    <city>San Francisco</city>
    <state>CA</state>
    <zip>94105</zip>
    <country>US</country>
    <phone nil="nil"/>
  </address>
  <accept_language nil="nil"/>
  <hosted_login_token>3ed66441313a90bd7e8039b31985dee8</hosted_login_token>
  <created_at type="datetime">2016-06-14T16:08:41Z</created_at>
  <closed_at nil="nil"/>
</account>


{"_id":"5b2d60111235f10003177391","category":"5b2d60111235f1000317734f","parentDoc":null,"project":"555fbba928249c1900618a82","user":"55648cf93b87582b003ab8b1","version":"5b2d60111235f10003177402","updates":["55bbdd4e1067fc1700510eed"],"next":{"pages":[],"description":""},"createdAt":"2015-06-15T21:45:49.420Z","link_external":false,"link_url":"","githubsync":"","sync_unique":"","hidden":false,"api":{"examples":{"codes":[{"code":"<?php\n\ntry {\n  $account = Recurly_Account::get('1');\n  print \"Account: $account\\n\";\n} catch (Recurly_NotFoundError $e) {\n  print \"Account not found.\\n\";\n}","language":"php","name":""},{"code":"begin\n  account = Recurly::Account.find '1'\n  puts \"Account: #{account.inspect}\"\nrescue Recurly::Resource::NotFound => e\n  puts e.message\nend","language":"ruby"},{"code":"try:\n  account = recurly.Account.get('1')\n  print \"Account: %s\" % account\nexcept NotFoundError:\n  print \"Account not found.\\n\"","language":"python"},{"code":"try\n{\n\tvar account = Accounts.Get(\"1\");\n\tConsole.WriteLine(\"Account \" + account);\n}\ncatch (NotFoundException e)\n{\n\tConsole.WriteLine(\"Account not found.\");\n}","language":"csharp"}]},"method":"get","results":{"codes":[{"name":"","code":"<account href=\"https://your-subdomain.recurly.com/v2/accounts/1\">\n  <adjustments href=\"https://your-subdomain.recurly.com/v2/accounts/1/adjustments\"/>\n  <account_acquisition href=\"https://your-subdomain.recurly.com/v2/accounts/1/acquisition\"/>\n  <account_balance href=\"https://your-subdomain.recurly.com/v2/accounts/1/balance\"/>\n  <billing_info href=\"https://your-subdomain.recurly.com/v2/accounts/1/billing_info\"/>\n  <invoices href=\"https://your-subdomain.recurly.com/v2/accounts/1/invoices\"/>\n  <shipping_addresses href=\"https://your-subdomain.recurly.com/v2/accounts/1/shipping_addresses\"/>\n  <subscriptions href=\"https://your-subdomain.recurly.com/v2/accounts/1/subscriptions\"/>\n  <transactions href=\"https://your-subdomain.recurly.com/v2/accounts/1/transactions\"/>\n  <account_code>1</account_code>\n  <state>active</state>\n  <username>verena1234</username>\n  <email>verena@example.com</email>\n  <cc_emails>bob@example.com,susan@example.com</cc_emails>\n  <first_name>Verena</first_name>\n  <last_name>Example</last_name>\n  <company_name>New Company Name</company_name>\n  <vat_number nil=\"nil\"/>\n  <tax_exempt type=\"boolean\">false</tax_exempt>\n  <address>\n    <address1>123 Main St.</address1>\n    <address2 nil=\"nil\"/>\n    <city>San Francisco</city>\n    <state>CA</state>\n    <zip>94105</zip>\n    <country>US</country>\n    <phone nil=\"nil\"/>\n  </address>\n  <accept_language nil=\"nil\"/>\n  <hosted_login_token>71c122cb16fc90252ff845eacf5d7814</hosted_login_token>\n  <created_at type=\"datetime\">2016-08-03T15:44:05Z</created_at>\n  <updated_at type=\"datetime\">2017-03-15T21:22:18Z</updated_at>\n  <closed_at nil=\"nil\"/>\n  <has_live_subscription type=\"boolean\">false</has_live_subscription>\n  <has_active_subscription type=\"boolean\">false</has_active_subscription>\n  <has_future_subscription type=\"boolean\">false</has_future_subscription>\n  <has_canceled_subscription type=\"boolean\">false</has_canceled_subscription>\n  <has_past_due_invoice type=\"boolean\">false</has_past_due_invoice>\n</account>","language":"xml","status":200}]},"settings":"","auth":"required","params":[{"_id":"557f478deb75d80d00af4086","ref":"","in":"path","required":true,"desc":"Account's unique code.","default":"","type":"string","name":"account_code"}],"url":"/accounts/:account_code"},"isReference":true,"order":3,"body":"","excerpt":"Returns information about a single account.","slug":"get-account","type":"get","title":"Lookup Account","__v":0,"childrenPages":[]}

getLookup Account

Returns information about a single account.

Path Params

account_code:
required
string
Account's unique code.

Definition

{{ api_url }}{{ page_api_url }}

Examples

<?php

try {
  $account = Recurly_Account::get('1');
  print "Account: $account\n";
} catch (Recurly_NotFoundError $e) {
  print "Account not found.\n";
}
begin
  account = Recurly::Account.find '1'
  puts "Account: #{account.inspect}"
rescue Recurly::Resource::NotFound => e
  puts e.message
end
try:
  account = recurly.Account.get('1')
  print "Account: %s" % account
except NotFoundError:
  print "Account not found.\n"
try
{
	var account = Accounts.Get("1");
	Console.WriteLine("Account " + account);
}
catch (NotFoundException e)
{
	Console.WriteLine("Account not found.");
}

Result Format

<account href="https://your-subdomain.recurly.com/v2/accounts/1">
  <adjustments href="https://your-subdomain.recurly.com/v2/accounts/1/adjustments"/>
  <account_acquisition href="https://your-subdomain.recurly.com/v2/accounts/1/acquisition"/>
  <account_balance href="https://your-subdomain.recurly.com/v2/accounts/1/balance"/>
  <billing_info href="https://your-subdomain.recurly.com/v2/accounts/1/billing_info"/>
  <invoices href="https://your-subdomain.recurly.com/v2/accounts/1/invoices"/>
  <shipping_addresses href="https://your-subdomain.recurly.com/v2/accounts/1/shipping_addresses"/>
  <subscriptions href="https://your-subdomain.recurly.com/v2/accounts/1/subscriptions"/>
  <transactions href="https://your-subdomain.recurly.com/v2/accounts/1/transactions"/>
  <account_code>1</account_code>
  <state>active</state>
  <username>verena1234</username>
  <email>verena@example.com</email>
  <cc_emails>bob@example.com,susan@example.com</cc_emails>
  <first_name>Verena</first_name>
  <last_name>Example</last_name>
  <company_name>New Company Name</company_name>
  <vat_number nil="nil"/>
  <tax_exempt type="boolean">false</tax_exempt>
  <address>
    <address1>123 Main St.</address1>
    <address2 nil="nil"/>
    <city>San Francisco</city>
    <state>CA</state>
    <zip>94105</zip>
    <country>US</country>
    <phone nil="nil"/>
  </address>
  <accept_language nil="nil"/>
  <hosted_login_token>71c122cb16fc90252ff845eacf5d7814</hosted_login_token>
  <created_at type="datetime">2016-08-03T15:44:05Z</created_at>
  <updated_at type="datetime">2017-03-15T21:22:18Z</updated_at>
  <closed_at nil="nil"/>
  <has_live_subscription type="boolean">false</has_live_subscription>
  <has_active_subscription type="boolean">false</has_active_subscription>
  <has_future_subscription type="boolean">false</has_future_subscription>
  <has_canceled_subscription type="boolean">false</has_canceled_subscription>
  <has_past_due_invoice type="boolean">false</has_past_due_invoice>
</account>


{"_id":"5b2d60111235f10003177392","category":"5b2d60111235f1000317734f","parentDoc":null,"user":"55648cf93b87582b003ab8b1","project":"555fbba928249c1900618a82","version":"5b2d60111235f10003177402","updates":["568ffb69769f210d00132584"],"next":{"pages":[],"description":""},"createdAt":"2015-06-15T21:57:38.556Z","link_external":false,"link_url":"","githubsync":"","sync_unique":"","hidden":false,"api":{"results":{"codes":[{"name":"","code":"<account href=\"https://your-subdomain.recurly.com/v2/accounts/1\">\n  <adjustments href=\"https://your-subdomain.recurly.com/v2/accounts/1/adjustments\"/>\n  <account_balance href=\"https://your-subdomain.recurly.com/v2/accounts/1/balance\"/>\n  <billing_info href=\"https://your-subdomain.recurly.com/v2/accounts/1/billing_info\"/>\n  <invoices href=\"https://your-subdomain.recurly.com/v2/accounts/1/invoices\"/>\n  <redemptions href=\"https://your-subdomain.recurly.com/v2/accounts/1/redemptions\"/>\n  <subscriptions href=\"https://your-subdomain.recurly.com/v2/accounts/1/subscriptions\"/>\n  <transactions href=\"https://your-subdomain.recurly.com/v2/accounts/1/transactions\"/>\n  <account_code>1</account_code>\n  <state>active</state>\n  <username>verena1234</username>\n  <email>verena@example.com</email>\n  <cc_emails>bob@example.com,susan@example.com</cc_emails>\n  <first_name>Verena</first_name>\n  <last_name>Example</last_name>\n  <company_name>New Company Name</company_name>\n  <vat_number nil=\"nil\"/>\n  <tax_exempt type=\"boolean\">false</tax_exempt>\n  <address>\n    <address1>123 Main St.</address1>\n    <address2 nil=\"nil\"/>\n    <city>San Francisco</city>\n    <state>CA</state>\n    <zip>94105</zip>\n    <country>US</country>\n    <phone nil=\"nil\"/>\n  </address>\n  <accept_language nil=\"nil\"/>\n  <hosted_login_token>71c122cb16fc90252ff845eacf5d7814</hosted_login_token>\n  <created_at type=\"datetime\">2016-08-03T15:44:05Z</created_at>\n  <updated_at type=\"datetime\">2016-08-03T16:30:50Z</updated_at>\n  <closed_at nil=\"nil\"/>\n</account>","language":"xml","status":200}]},"settings":"","examples":{"codes":[{"code":"<?php\n\ntry {\n  $account = Recurly_Account::get('b6f5783');\n  $account->company_name = 'New Company Name';\n  $account->update();\n\n  print \"Account: $account\\n\";\n} catch (Recurly_NotFoundError $e) {\n  print \"Invalid account code: $e\";\n}","name":"","language":"php"},{"language":"ruby","code":"account = Recurly::Account.find('account_1')\naccount.company_name = 'New Company Name'\naccount.save"},{"language":"python","code":"account = recurly.Account.get('account_1')\naccount.company_name = 'New Company Name'\naccount.save()"},{"language":"csharp","code":"var account = Account.Get(\"account_1\");\naccount.CompanyName = 'New Company Name'\naccount.Update();"},{"language":"xml","code":"<account>\n  <company_name>New Company Name</company_name>\n</account>"}]},"method":"put","auth":"required","params":[{"_id":"557f4a527eafa719001d1c43","ref":"","in":"path","required":true,"desc":"Account's unique code.","default":"","type":"string","name":"account_code"},{"_id":"557f4a527eafa719001d1c42","ref":"","in":"body","required":false,"desc":"The username for the account, ignore if you do not use usernames. Max of 255 characters.","default":"","type":"string","name":"username"},{"_id":"557f4a527eafa719001d1c41","ref":"","in":"body","required":false,"desc":"The email address for the account.","default":"","type":"string","name":"email"},{"_id":"557f4a527eafa719001d1c40","ref":"","in":"body","required":false,"desc":"The first name for the account. Max of 255 characters.","default":"","type":"string","name":"first_name"},{"_id":"557f4a527eafa719001d1c3f","ref":"","in":"body","required":false,"desc":"The last name for the account. Max of 255 characters.","default":"","type":"string","name":"last_name"},{"_id":"557f4a527eafa719001d1c3e","ref":"","in":"body","required":false,"desc":"The company name for the account. Max of 50 characters.","default":"","type":"string","name":"company_name"},{"_id":"557f4a527eafa719001d1c3d","ref":"","in":"body","required":false,"desc":"The VAT number to avoid having the VAT applied (if applicable).","default":"","type":"string","name":"vat_number"},{"_id":"557f4a527eafa719001d1c3c","ref":"","in":"body","required":false,"desc":"The tax status of the account. `true` exempts tax on the account, `false` applies tax on the account.","default":"","type":"boolean","name":"tax_exempt"},{"_id":"557f4a527eafa719001d1c3b","ref":"","in":"body","required":false,"desc":"The Avalara AvaTax value that can be passed to identify the customer type for tax purposes. The range of values can be A - R (more info at Avalara). Value is case-sensitive.","default":"","type":"string","name":"entity_use_code"},{"_id":"58cffb3be865c00f00f93dfb","ref":"","in":"body","required":false,"desc":"The nested account acquisition information: `cost_in_cents`, currency`, `channel`, `subchannel`, `campaign`","default":"","type":"object","name":"account_acquisition"},{"_id":"557f4a527eafa719001d1c3a","ref":"","in":"body","required":false,"desc":"The nested billing information. If present, the account will only be created after the billing information is validated.","default":"","type":"object","name":"billing_info"},{"_id":"557f4a527eafa719001d1c39","ref":"","in":"body","required":false,"desc":"The nested address information for the account: `address1`, `address2`, `city`, `state`, `zip`, `country`, `phone`.","default":"","type":"object","name":"address"},{"_id":"557f4a527eafa719001d1c38","ref":"","in":"body","required":false,"desc":"The ISO 639-1 language code from the user's browser, indicating their preferred language and locale.","default":"","type":"string","name":"accept_language"},{"_id":"561c3606d468a60d00f51ebe","ref":"","in":"body","required":false,"desc":"Additional email address that should receive account correspondence. These should be separated only by commas. These CC emails will receive all emails that the `email` field also receives.","default":"","type":"array_string","name":"cc_emails"},{"_id":"5ad79b74f7096b0003956a9e","ref":"","in":"body","required":false,"desc":"Used to determine the language and locale of emails sent on behalf of the merchant to the customer. The list of locales is restricted to those the merchant has enabled on the site.","default":"","type":"string","name":"preferred_locale"}],"url":"/accounts/:account_code"},"isReference":true,"order":4,"body":"[block:callout]\n{\n  \"type\": \"success\",\n  \"title\": \"Please note\",\n  \"body\": \"You may optionally include billing information when updating an account. If the billing information is provided, the billing information will be validated. The account will only be updated if the billing information is valid.\"\n}\n[/block]","excerpt":"Updates an existing account.","slug":"update-account","type":"put","title":"Update Account","__v":1,"childrenPages":[]}

putUpdate Account

Updates an existing account.

Path Params

account_code:
required
string
Account's unique code.

Body Params

username:
string
The username for the account, ignore if you do not use usernames. Max of 255 characters.
email:
string
The email address for the account.
first_name:
string
The first name for the account. Max of 255 characters.
last_name:
string
The last name for the account. Max of 255 characters.
company_name:
string
The company name for the account. Max of 50 characters.
vat_number:
string
The VAT number to avoid having the VAT applied (if applicable).
tax_exempt:
boolean
The tax status of the account. `true` exempts tax on the account, `false` applies tax on the account.
entity_use_code:
string
The Avalara AvaTax value that can be passed to identify the customer type for tax purposes. The range of values can be A - R (more info at Avalara). Value is case-sensitive.
account_acquisition:
object
The nested account acquisition information: `cost_in_cents`, currency`, `channel`, `subchannel`, `campaign`
billing_info:
object
The nested billing information. If present, the account will only be created after the billing information is validated.
address:
object
The nested address information for the account: `address1`, `address2`, `city`, `state`, `zip`, `country`, `phone`.
accept_language:
string
The ISO 639-1 language code from the user's browser, indicating their preferred language and locale.
cc_emails:
array of strings
Additional email address that should receive account correspondence. These should be separated only by commas. These CC emails will receive all emails that the `email` field also receives.
preferred_locale:
string
Used to determine the language and locale of emails sent on behalf of the merchant to the customer. The list of locales is restricted to those the merchant has enabled on the site.

Please note

You may optionally include billing information when updating an account. If the billing information is provided, the billing information will be validated. The account will only be updated if the billing information is valid.

Definition

{{ api_url }}{{ page_api_url }}

Examples

<?php

try {
  $account = Recurly_Account::get('b6f5783');
  $account->company_name = 'New Company Name';
  $account->update();

  print "Account: $account\n";
} catch (Recurly_NotFoundError $e) {
  print "Invalid account code: $e";
}
account = Recurly::Account.find('account_1')
account.company_name = 'New Company Name'
account.save
account = recurly.Account.get('account_1')
account.company_name = 'New Company Name'
account.save()
var account = Account.Get("account_1");
account.CompanyName = 'New Company Name'
account.Update();
<account>
  <company_name>New Company Name</company_name>
</account>

Result Format

<account href="https://your-subdomain.recurly.com/v2/accounts/1">
  <adjustments href="https://your-subdomain.recurly.com/v2/accounts/1/adjustments"/>
  <account_balance href="https://your-subdomain.recurly.com/v2/accounts/1/balance"/>
  <billing_info href="https://your-subdomain.recurly.com/v2/accounts/1/billing_info"/>
  <invoices href="https://your-subdomain.recurly.com/v2/accounts/1/invoices"/>
  <redemptions href="https://your-subdomain.recurly.com/v2/accounts/1/redemptions"/>
  <subscriptions href="https://your-subdomain.recurly.com/v2/accounts/1/subscriptions"/>
  <transactions href="https://your-subdomain.recurly.com/v2/accounts/1/transactions"/>
  <account_code>1</account_code>
  <state>active</state>
  <username>verena1234</username>
  <email>verena@example.com</email>
  <cc_emails>bob@example.com,susan@example.com</cc_emails>
  <first_name>Verena</first_name>
  <last_name>Example</last_name>
  <company_name>New Company Name</company_name>
  <vat_number nil="nil"/>
  <tax_exempt type="boolean">false</tax_exempt>
  <address>
    <address1>123 Main St.</address1>
    <address2 nil="nil"/>
    <city>San Francisco</city>
    <state>CA</state>
    <zip>94105</zip>
    <country>US</country>
    <phone nil="nil"/>
  </address>
  <accept_language nil="nil"/>
  <hosted_login_token>71c122cb16fc90252ff845eacf5d7814</hosted_login_token>
  <created_at type="datetime">2016-08-03T15:44:05Z</created_at>
  <updated_at type="datetime">2016-08-03T16:30:50Z</updated_at>
  <closed_at nil="nil"/>
</account>


{"_id":"5b2d60111235f10003177393","category":"5b2d60111235f1000317734f","parentDoc":null,"project":"555fbba928249c1900618a82","user":"55648cf93b87582b003ab8b1","version":"5b2d60111235f10003177402","updates":[],"next":{"pages":[],"description":""},"createdAt":"2015-06-15T22:00:42.004Z","link_external":false,"link_url":"","githubsync":"","sync_unique":"","hidden":false,"api":{"examples":{"codes":[{"name":"","code":"<?php\n\ntry {\n  $account = Recurly_Account::get('b6f5783');\n  $account->close();\n\n  print \"Account: $account\";\n} catch (Recurly_NotFoundError $e) {\n  print \"Invalid account code: $e\";\n}","language":"php"},{"language":"ruby","code":"account = Recurly::Account.find('1')\naccount.destroy"},{"code":"account = recurly.Account.get('1')\naccount.delete()","language":"python"},{"code":"var account = Accounts.Get(\"1\");\naccount.Close();","language":"csharp"}]},"method":"delete","results":{"codes":[{"name":"","code":"","language":"xml","status":200}]},"settings":"","auth":"required","params":[{"_id":"55944ebb5c9eaa2300a86337","ref":"","in":"path","required":true,"desc":"Account's unique code.","default":"","type":"string","name":"account_code"}],"url":"/accounts/:account_code"},"isReference":true,"order":5,"body":"[block:callout]\n{\n  \"type\": \"success\",\n  \"title\": \"Please note\",\n  \"body\": \"Closing an account permanently deletes its billing information and cancels any active subscriptions (canceled subscriptions will remain active until the end of the current billing cycle before expiring).\"\n}\n[/block]","excerpt":"Marks an account as closed and cancels any active subscriptions. Paused subscriptions will be expired.","slug":"close-account","type":"delete","title":"Close Account","__v":1,"childrenPages":[]}

deleteClose Account

Marks an account as closed and cancels any active subscriptions. Paused subscriptions will be expired.

Path Params

account_code:
required
string
Account's unique code.

Please note

Closing an account permanently deletes its billing information and cancels any active subscriptions (canceled subscriptions will remain active until the end of the current billing cycle before expiring).

Definition

{{ api_url }}{{ page_api_url }}

Examples

<?php

try {
  $account = Recurly_Account::get('b6f5783');
  $account->close();

  print "Account: $account";
} catch (Recurly_NotFoundError $e) {
  print "Invalid account code: $e";
}
account = Recurly::Account.find('1')
account.destroy
account = recurly.Account.get('1')
account.delete()
var account = Accounts.Get("1");
account.Close();


{"_id":"5b2d60111235f10003177394","category":"5b2d60111235f1000317734f","parentDoc":null,"project":"555fbba928249c1900618a82","user":"55648cf93b87582b003ab8b1","version":"5b2d60111235f10003177402","updates":[],"next":{"pages":[],"description":""},"createdAt":"2015-06-15T22:03:14.174Z","link_external":false,"link_url":"","githubsync":"","sync_unique":"","hidden":false,"api":{"examples":{"codes":[{"language":"php","name":"","code":"<?php\n\ntry {\n  $account = Recurly_Account::get('b6f5783');\n  $account->reopen();\n\n  // Or to fetch and reopen in one call\n  // $account = Recurly_Account::reopenAccount('b6f5783');\n\n  print \"Account: $account\";\n} catch (Recurly_NotFoundError $e) {\n  print \"Invalid account code: $e\";\n} catch (Recurly_ValidationError $e) {\n  print \"Account already open: $e\";\n}"},{"code":"account = Recurly::Account.find '1'\naccount.reopen","language":"ruby"},{"code":"account = recurly.Account.get('1')\naccount.reopen() ","language":"python"},{"code":"var account = Accounts.Get(\"1\");\naccount.Reopen();","language":"csharp"}]},"method":"put","results":{"codes":[{"name":"","status":200,"language":"xml","code":"<account href=\"https://your-subdomain.recurly.com/v2/accounts/1\">\n  <adjustments href=\"https://your-subdomain.recurly.com/v2/accounts/1/adjustments\"/>\n  <account_balance href=\"https://your-subdomain.recurly.com/v2/accounts/1/balance\"/>\n  <invoices href=\"https://your-subdomain.recurly.com/v2/accounts/1/invoices\"/>\n  <redemptions href=\"https://your-subdomain.recurly.com/v2/accounts/1/redemptions\"/>\n  <subscriptions href=\"https://your-subdomain.recurly.com/v2/accounts/1/subscriptions\"/>\n  <transactions href=\"https://your-subdomain.recurly.com/v2/accounts/1/transactions\"/>\n  <account_code>1</account_code>\n  <state>active</state>\n  <username>verena1234</username>\n  <email>verena@example.com</email>\n  <cc_emails>bob@example.com,susan@example.com</cc_emails>\n  <first_name>Verena</first_name>\n  <last_name>Example</last_name>\n  <company_name>New Company Name</company_name>\n  <vat_number nil=\"nil\"/>\n  <tax_exempt type=\"boolean\">false</tax_exempt>\n  <address>\n    <address1>123 Main St.</address1>\n    <address2 nil=\"nil\"/>\n    <city>San Francisco</city>\n    <state>CA</state>\n    <zip>94105</zip>\n    <country>US</country>\n    <phone nil=\"nil\"/>\n  </address>\n  <accept_language nil=\"nil\"/>\n  <hosted_login_token>71c122cb16fc90252ff845eacf5d7814</hosted_login_token>\n  <created_at type=\"datetime\">2016-08-03T15:44:05Z</created_at>\n  <updated_at type=\"datetime\">2016-08-03T16:31:25Z</updated_at>\n  <closed_at nil=\"nil\"/>\n</account>"}]},"settings":"","auth":"required","params":[{"_id":"55944ed45c9eaa2300a86339","ref":"","in":"path","required":true,"desc":"Account's unique code.","default":"","type":"string","name":"account_code"}],"url":"/accounts/:account_code/reopen"},"isReference":true,"order":6,"body":"[block:callout]\n{\n  \"type\": \"success\",\n  \"title\": \"Please note\",\n  \"body\": \"Editing an account, creating an account with the same `account_code` as the deleted account, or creating a new transaction or subscription will also reopen an account. Reopening an account will restore its history. Reopening an account does not modify any previously canceled or expired subscriptions and billing information will need to be provided by the customer to continue billing.\"\n}\n[/block]","excerpt":"Transitions a closed account back to active.","slug":"reopen-account","type":"put","title":"Reopen Account","__v":0,"childrenPages":[]}

putReopen Account

Transitions a closed account back to active.

Path Params

account_code:
required
string
Account's unique code.

Please note

Editing an account, creating an account with the same account_code as the deleted account, or creating a new transaction or subscription will also reopen an account. Reopening an account will restore its history. Reopening an account does not modify any previously canceled or expired subscriptions and billing information will need to be provided by the customer to continue billing.

Definition

{{ api_url }}{{ page_api_url }}

Examples

<?php

try {
  $account = Recurly_Account::get('b6f5783');
  $account->reopen();

  // Or to fetch and reopen in one call
  // $account = Recurly_Account::reopenAccount('b6f5783');

  print "Account: $account";
} catch (Recurly_NotFoundError $e) {
  print "Invalid account code: $e";
} catch (Recurly_ValidationError $e) {
  print "Account already open: $e";
}
account = Recurly::Account.find '1'
account.reopen
account = recurly.Account.get('1')
account.reopen() 
var account = Accounts.Get("1");
account.Reopen();

Result Format

<account href="https://your-subdomain.recurly.com/v2/accounts/1">
  <adjustments href="https://your-subdomain.recurly.com/v2/accounts/1/adjustments"/>
  <account_balance href="https://your-subdomain.recurly.com/v2/accounts/1/balance"/>
  <invoices href="https://your-subdomain.recurly.com/v2/accounts/1/invoices"/>
  <redemptions href="https://your-subdomain.recurly.com/v2/accounts/1/redemptions"/>
  <subscriptions href="https://your-subdomain.recurly.com/v2/accounts/1/subscriptions"/>
  <transactions href="https://your-subdomain.recurly.com/v2/accounts/1/transactions"/>
  <account_code>1</account_code>
  <state>active</state>
  <username>verena1234</username>
  <email>verena@example.com</email>
  <cc_emails>bob@example.com,susan@example.com</cc_emails>
  <first_name>Verena</first_name>
  <last_name>Example</last_name>
  <company_name>New Company Name</company_name>
  <vat_number nil="nil"/>
  <tax_exempt type="boolean">false</tax_exempt>
  <address>
    <address1>123 Main St.</address1>
    <address2 nil="nil"/>
    <city>San Francisco</city>
    <state>CA</state>
    <zip>94105</zip>
    <country>US</country>
    <phone nil="nil"/>
  </address>
  <accept_language nil="nil"/>
  <hosted_login_token>71c122cb16fc90252ff845eacf5d7814</hosted_login_token>
  <created_at type="datetime">2016-08-03T15:44:05Z</created_at>
  <updated_at type="datetime">2016-08-03T16:31:25Z</updated_at>
  <closed_at nil="nil"/>
</account>


{"_id":"5b2d60111235f10003177395","category":"5b2d60111235f1000317734f","user":"559d85d26b21311700fb0b7b","parentDoc":null,"project":"555fbba928249c1900618a82","version":"5b2d60111235f10003177402","updates":[],"next":{"pages":[],"description":""},"createdAt":"2016-07-19T19:51:58.991Z","link_external":false,"link_url":"","githubsync":"","sync_unique":"","hidden":false,"api":{"examples":{"codes":[]},"method":"get","results":{"codes":[{"code":"<account_balance href=\"https://your-subdomain.recurly.com/v2/accounts/1/balance\">\n  <account href=\"https://your-subdomain.recurly.com/v2/accounts/1\"/>\n  <past_due type=\"boolean\">false</past_due>\n  <balance_in_cents>\n    <USD type=\"integer\">3000</USD>\n    <EUR type=\"integer\">0</EUR>\n  </balance_in_cents>\n</account_balance>","name":"","status":200,"language":"xml"},{"language":"json","code":"<error>\n  <symbol>unavailable_in_api_version</symbol>\n  <description>This request cannot be completed using this version of the API. It was added in version '2.3'.</description>\n</error>","name":"","status":400},{"code":"<error>\n  <symbol>not_found</symbol>\n  <description lang=\"en-US\">Couldn't find Account with account_code = not-1</description>\n</error>","status":404,"language":"text"}]},"settings":"","auth":"required","params":[{"_id":"578e888a36baeb17003fd5fb","ref":"","in":"query","required":true,"desc":"Account's unique code.","default":"","type":"string","name":"account_code"}],"url":"/accounts/:account_code/balance"},"isReference":true,"order":7,"body":"","excerpt":"Returns the account's past due status and balance in each of the site's supported currencies.","slug":"lookup-account-balance","type":"get","title":"Lookup Account Balance","__v":0,"childrenPages":[]}

getLookup Account Balance

Returns the account's past due status and balance in each of the site's supported currencies.

Query Params

account_code:
required
string
Account's unique code.

Definition

{{ api_url }}{{ page_api_url }}

Result Format

<account_balance href="https://your-subdomain.recurly.com/v2/accounts/1/balance">
  <account href="https://your-subdomain.recurly.com/v2/accounts/1"/>
  <past_due type="boolean">false</past_due>
  <balance_in_cents>
    <USD type="integer">3000</USD>
    <EUR type="integer">0</EUR>
  </balance_in_cents>
</account_balance>
<error>
  <symbol>unavailable_in_api_version</symbol>
  <description>This request cannot be completed using this version of the API. It was added in version '2.3'.</description>
</error>
<error>
  <symbol>not_found</symbol>
  <description lang="en-US">Couldn't find Account with account_code = not-1</description>
</error>


{"_id":"5b2d60111235f10003177396","category":"5b2d60111235f1000317734f","user":"55648cf93b87582b003ab8b1","parentDoc":null,"project":"555fbba928249c1900618a82","version":"5b2d60111235f10003177402","updates":[],"next":{"pages":[],"description":""},"createdAt":"2015-06-15T22:04:40.352Z","link_external":false,"link_url":"","githubsync":"","sync_unique":"","hidden":false,"api":{"examples":{"codes":[{"name":"","code":"<?php\n\ntry {\n  $notes = Recurly_NoteList::get('b6f5783');\n  foreach ($notes as $note) {\n    print \"Note: {$note->message}\\n\";\n  }\n} catch (Recurly_NotFoundError $e) {\n  print \"Invalid account code: $e\";\n}","language":"php"},{"code":"try:\n  account = recurly.Account.get('1')\n  for note in account.notes():\n   print \"Note: %s\" % note.message\nexcept NotFoundError:\n  print \"Account not found.\\n\"","language":"python"},{"code":"using System.Linq;\n\nvar account = Accounts.Get(\"1\");\nvar notes = account.GetNotes();\nwhile (notes.Any())\n{\n\tforeach (var note in notes)\n\t\tConsole.WriteLine(\"Note: \" + note.Message);\n\tnotes = notes.Next;\n}","language":"csharp"}]},"method":"get","results":{"codes":[{"name":"","code":"<notes type=\"array\">\n  <note>\n    <account href=\"https://your-subdomain.recurly.com/v2/accounts/1\"/>\n    <message>This is my second note</message>\n    <created_at type=\"datetime\">2015-06-14T16:08:41Z</created_at>\n  </note>\n  <note>\n    <account href=\"https://your-subdomain.recurly.com/v2/accounts/1\"/>\n    <message>This is my first note</message>\n    <created_at type=\"datetime\">2016-06-13T16:06:21Z</created_at>\n  </note>\n  <!-- Continued... -->\n</notes>","language":"xml","status":200}]},"settings":"","auth":"required","params":[{"_id":"55944eddccc3052300569882","ref":"","in":"path","required":true,"desc":"Account's unique code.","default":"","type":"string","name":"account_code"},{"_id":"5783c946ce802f0e0087d4bb","ref":"","in":"query","required":false,"desc":"Splits records across pages. Leave blank to return the first page. Follow the URI in the first page's Link header to fetch the next page.","default":"","type":"string","name":"cursor"},{"_id":"578ea620c93aac0e00ec889d","ref":"","in":"query","required":false,"desc":"The attribute that will be used to order records: `created_at`, `updated_at`.","default":"created_at","type":"string","name":"sort"},{"_id":"578ea620c93aac0e00ec889c","ref":"","in":"query","required":false,"desc":"The order in which products will be returned: `asc` for ascending order, `desc` for descending order.","default":"desc","type":"string","name":"order"},{"_id":"578ea620c93aac0e00ec889b","ref":"","in":"query","required":false,"desc":"Operates on the attribute specified by the sort parameter. Filters records to only include those with datetimes greater than or equal to the supplied datetime. Accepts an ISO 8601 date or date and time.","default":"","type":"datetime","name":"begin_time"},{"_id":"578ea620c93aac0e00ec889a","ref":"","in":"query","required":false,"desc":"","default":"","type":"datetime","name":"end_time"},{"_id":"5783c946ce802f0e0087d4ba","ref":"","in":"query","required":false,"desc":"Number of records to return per page, up to a maximum of 200.","default":"50","type":"int","name":"per_page"}],"url":"/accounts/:account_code/notes"},"isReference":true,"order":8,"body":"","excerpt":"Returns a list of the notes on an account sorted in descending order (most recently created first).","slug":"list-account-notes","type":"get","title":"List Account Notes","__v":0,"childrenPages":[]}

getList Account Notes

Returns a list of the notes on an account sorted in descending order (most recently created first).

Path Params

account_code:
required
string
Account's unique code.

Query Params

cursor:
string
Splits records across pages. Leave blank to return the first page. Follow the URI in the first page's Link header to fetch the next page.
sort:
stringcreated_at
The attribute that will be used to order records: `created_at`, `updated_at`.
order:
stringdesc
The order in which products will be returned: `asc` for ascending order, `desc` for descending order.
begin_time:
datetime
Operates on the attribute specified by the sort parameter. Filters records to only include those with datetimes greater than or equal to the supplied datetime. Accepts an ISO 8601 date or date and time.
end_time:
datetime
per_page:
integer50
Number of records to return per page, up to a maximum of 200.

Definition

{{ api_url }}{{ page_api_url }}

Examples

<?php

try {
  $notes = Recurly_NoteList::get('b6f5783');
  foreach ($notes as $note) {
    print "Note: {$note->message}\n";
  }
} catch (Recurly_NotFoundError $e) {
  print "Invalid account code: $e";
}
try:
  account = recurly.Account.get('1')
  for note in account.notes():
   print "Note: %s" % note.message
except NotFoundError:
  print "Account not found.\n"
using System.Linq;

var account = Accounts.Get("1");
var notes = account.GetNotes();
while (notes.Any())
{
	foreach (var note in notes)
		Console.WriteLine("Note: " + note.Message);
	notes = notes.Next;
}

Result Format

<notes type="array">
  <note>
    <account href="https://your-subdomain.recurly.com/v2/accounts/1"/>
    <message>This is my second note</message>
    <created_at type="datetime">2015-06-14T16:08:41Z</created_at>
  </note>
  <note>
    <account href="https://your-subdomain.recurly.com/v2/accounts/1"/>
    <message>This is my first note</message>
    <created_at type="datetime">2016-06-13T16:06:21Z</created_at>
  </note>
  <!-- Continued... -->
</notes>


{"_id":"5b2d60111235f100031773c2","category":"5b2d60111235f10003177350","parentDoc":null,"project":"555fbba928249c1900618a82","user":"55648cf93b87582b003ab8b1","version":"5b2d60111235f10003177402","updates":["56799b95239fac0d00c7e019"],"next":{"pages":[],"description":""},"createdAt":"2015-06-17T19:47:32.787Z","link_external":false,"link_url":"","githubsync":"","sync_unique":"","hidden":false,"api":{"examples":{"codes":[{"name":"","code":"<?php\n\ntry {\n  $billing_info = new Recurly_BillingInfo();\n  $billing_info->account_code = 'b6f5783';\n  $billing_info->token_id = '7z6furn4jvb9'; // From Recurly.js\n  $billing_info->create();\n\n  print \"Billing Info: $billing_info\";\n} catch (Recurly_NotFoundError $e) {\n  // Could not find account or token is invalid or expired\n  print \"Not Found: $e\";\n}","language":"php"},{"language":"ruby","code":"account = Recurly::Account.find('1')\naccount.billing_info = {\n  token_id: 'TOKEN_ID'\n}\naccount.billing_info.save!"},{"code":"account = Account.get('1')\nbilling_info = account.billing_info\nbilling_info.token_id = 'TOKEN_ID'\naccount.update_billing_info(billing_info)","language":"python"},{"code":"var account = Accounts.Get(\"1\");\nvar info = new BillingInfo(account);\ninfo.TokenId = \"TOKEN_ID\";\ninfo.Create();","language":"csharp"},{"language":"xml","code":"<billing_info>\n  <token_id>TOKEN_ID</token_id>\n</billing_info>"}]},"method":"post","results":{"codes":[{"language":"xml","status":201,"name":"","code":"<billing_info href=\"https://your-subdomain.recurly.com/v2/accounts/1/billing_info\" type=\"credit_card\">\n  <account href=\"https://your-subdomain.recurly.com/v2/accounts/1\"/>\n  <first_name>Verena</first_name>\n  <last_name>Example</last_name>\n  <company nil=\"nil\"></company>\n  <address1>123 Main St.</address1>\n  <address2 nil=\"nil\"></address2>\n  <city>San Francisco</city>\n  <state>CA</state>\n  <zip>94105</zip>\n  <country>US</country>\n  <phone nil=\"nil\"></phone>\n  <vat_number>US1234567890</vat_number>\n  <ip_address>127.0.0.1</ip_address>\n  <ip_address_country>US</ip_address_country>\n  <card_type>Visa</card_type>\n  <year type=\"integer\">2019</year>\n  <month type=\"integer\">11</month>\n  <first_six>411111</first_six>\n  <last_four>1111</last_four>\n  <updated_at type=\"datetime\">2017-02-17T15:38:53Z</updated_at>\n</billing_info>"},{"status":404,"language":"xml","code":"<error>\n  <symbol>token_invalid</symbol>\n  <description>Token is either invalid or expired</description>\n</error>"}]},"settings":"","auth":"required","params":[{"_id":"55944f99ccc3052300569885","ref":"","in":"path","required":true,"desc":"Account's unique code.","default":"","type":"string","name":"account_code"},{"_id":"5581ced4a5474a0d00d946a5","ref":"","in":"body","required":true,"desc":"A token [generated by Recurly.js](https://docs.recurly.com/js/#getting-a-token)","default":"","type":"string","name":"token_id"},{"_id":"56d0e86f40d36e1d00bc14c9","ref":"","in":"body","required":false,"desc":"Currency in which invoices will be posted. Only applicable if this account is enrolled in a plan has a different currency than your site's default.","default":"","type":"string","name":"currency"}],"url":"/accounts/:account_code/billing_info"},"isReference":true,"order":0,"body":"","excerpt":"Creates an account's Billing Information using a [token generated by Recurly.js](https://docs.recurly.com/js/#getting-a-token). Returns the account's created Billing Information.","slug":"create-an-accounts-billing-info-token","type":"post","title":"Create Account's Billing Info (Token)","__v":0,"childrenPages":[]}

postCreate Account's Billing Info (Token)

Creates an account's Billing Information using a [token generated by Recurly.js](https://docs.recurly.com/js/#getting-a-token). Returns the account's created Billing Information.

Path Params

account_code:
required
string
Account's unique code.

Body Params

token_id:
required
string
A token [generated by Recurly.js](https://docs.recurly.com/js/#getting-a-token)
currency:
string
Currency in which invoices will be posted. Only applicable if this account is enrolled in a plan has a different currency than your site's default.

Definition

{{ api_url }}{{ page_api_url }}

Examples

<?php

try {
  $billing_info = new Recurly_BillingInfo();
  $billing_info->account_code = 'b6f5783';
  $billing_info->token_id = '7z6furn4jvb9'; // From Recurly.js
  $billing_info->create();

  print "Billing Info: $billing_info";
} catch (Recurly_NotFoundError $e) {
  // Could not find account or token is invalid or expired
  print "Not Found: $e";
}
account = Recurly::Account.find('1')
account.billing_info = {
  token_id: 'TOKEN_ID'
}
account.billing_info.save!
account = Account.get('1')
billing_info = account.billing_info
billing_info.token_id = 'TOKEN_ID'
account.update_billing_info(billing_info)
var account = Accounts.Get("1");
var info = new BillingInfo(account);
info.TokenId = "TOKEN_ID";
info.Create();
<billing_info>
  <token_id>TOKEN_ID</token_id>
</billing_info>

Result Format

<billing_info href="https://your-subdomain.recurly.com/v2/accounts/1/billing_info" type="credit_card">
  <account href="https://your-subdomain.recurly.com/v2/accounts/1"/>
  <first_name>Verena</first_name>
  <last_name>Example</last_name>
  <company nil="nil"></company>
  <address1>123 Main St.</address1>
  <address2 nil="nil"></address2>
  <city>San Francisco</city>
  <state>CA</state>
  <zip>94105</zip>
  <country>US</country>
  <phone nil="nil"></phone>
  <vat_number>