Subscriptions

With Rapyd Collect you can create subscriptions (also called subscription billing), recurring billing or recurring payments.

Easier Subscription Billing

Subscriptions work well for businesses that offer a service that can be renewed on a regular basis. Rapyd Collect helps you integrate this functionality into your website or application and manage all of your subscriptions.

A customer would like to use your digital service indefinitely. They decide to opt in and create a recurring payment in order to access your digital service as much as they choose.

Subscription Creation Workflow

Let’s look at the highlights of your workflow.

Stage 1 - Registering a Customer

  1. On your website or mobile application, the customer registers for your Acme music streaming service.
  2. The website back end asks Rapyd to create a customer ID.
  3. Rapyd creates a unique customer ID.

Stage 2 - Selecting a Payment Method

  1. From options displayed on your website, the customer selects a payment method.
  2. The website back end asks Rapyd to add the payment method to the customer.
  3. Rapyd adds the selected payment method to the customer ID.

Stage 3 - Processing the Subscription

  1. The customer subscribes to a basic plan that costs 3 Singapore dollars a month.
  2. The website back end asks Rapyd to create a subscription for the customer.
  3. Rapyd creates the subscription.
  4. Rapyd collects the payment from the customer and generates an invoice.
  5. You view the invoice, and direct to the customer.

Implementing the Workflow

Let's take a quick look at how you'll use Rapyd's API to implement the workflow.
For your website's subscription page:

  1. Find payment methods that you'll accept.
  2. Find the required fields for each payment method.
  3. Create a product that represents your streaming service.
  4. Create a plan that represents the pricing structure for your streaming service.

When a customer registers:

  1. Ask Rapyd to create a unique customer ID.
  2. Ask Rapyd to add the customer’s payment method to the customer ID.

When a customer subscribes to a plan:

  1. Ask Rapyd to create a subscription.
  2. View the subscription invoice.
    -->

How It Works

Find Available Payment Methods

  • Note: For illustration purposes, we will use SG (Singapore) and SGD (Singapore Dollar) for country and currency in the sample codes below.

Decide the payment methods you will accept so your customer can specify the payment methods for their subscriptions, on your payment page. To do that, use List Payment Methods by Country with the following parameters:

Query Parameter

Description

country

Enter SG as the country code for Singapore.

currency

Enter SGD as the currency code for Singapore dollar.

List Payment Methods by Country request

Request a list of all available payment methods (Singapore dollar in this case).

// Request URL: GET https://sandboxapi.rapyd.net/v1/payment_methods/country?country=SG&currency=SGD

// Message body absent
using System;

 namespace RapydApiRequestSample
 {
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                string country = "CN";
                string currency = "CNY";

                string result = RapydApiRequestSample.Utilities.MakeRequest("GET", $"/v1/payment_methods/country?country={country}&currency={currency}");

                Console.WriteLine(result);
            }
            catch (Exception e)
            {
                Console.WriteLine("Error completing request: " + e.Message);
            }
        }
    }
 }
const makeRequest = require('<path-to-your-utility-file>/utilities').makeRequest;

async function main() {
  try {
    const result = await makeRequest(
      'GET',
      '/v1/payment_methods/country?country=CN&currency=CNY
    );

    console.log(result);
  } catch (error) {
    console.error('Error completing request', error);
  }
}
<?php
$path = $_SERVER['DOCUMENT_ROOT'];
$path .= "/<path-to-your-utility-file>/utilities.php";
include($path);

try {
    $object = make_request('get', '/v1/payment_methods/country?country=CN&currency=CNY');
    echo $object;
} catch (Exception $e) {
    echo "Error: $e";
}
?>
from pprint import pprint

from utilities import make_request

country = 'CN'
currency = 'CNY'
results = make_request(method='get',
                       path=f'/v1/payment_methods/country?country={country}&currency={currency}')
pprint(results)

List Payment Methods by Country response

The response below is generated. Payment Method Type Object describes the response fields.

"data": [  
          {
            "type": "sg_credit_visa_card",
            "name": "Visa",
            "category": "card",
            "image": "https://iconslib.rapyd.net/checkout/sg_credit_visa_card.png",
            "country": "sg",
            "payment_flow_type": "",
            "currencies": [
                "SGD",
                 ...
             // 
            ],
            "status": 1,
            "is_cancelable": true,
            "payment_options": 
              [
                {
                    "name": "complete_payment_url",
                    "type": "string",
                    "regex": "",
                    "description": "the complete_payment_url field must be filled in.",
                    "is_required": true,
                    "is_updatable": false
                },
                {
                    "name": "error_payment_url",
                    "type": "string",
                    "regex": "",
                    "description": "the error_payment_url field must be filled in.",
                    "is_required": true,
                    "is_updatable": false
                }
              ],
            }
         ]

The data section of this response shows that sg_credit_visa_card is an acceptable payment method in Singapore, for example.

  • Note: A real response usually lists many payment methods.

Find Required Fields for the Payment

Identify the fields that your customer needs to complete for the payment method. To do that, use Get Payment Method Required Fields with the following parameter:

Path Parameter

Description

type

Enter sg_credit_visa_card as the payment method type.

Get Payment Method Required Fields request

Request a set of required fields for the payment method (sg_credit_visa_card, in this case).

// Request URL: GET https://sandboxapi.rapyd.net/v1/payment_methods/required_fields/sg_credit_visa_card

// Message body absent
using System;

namespace RapydApiRequestSample
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                string type = "sg_credit_visa_card";

                string result = RapydApiRequestSample.Utilities.MakeRequest("GET", $"/v1/payment_methods/required_fields/{type}");

                Console.WriteLine(result);
            }
            catch (Exception e)
            {
                Console.WriteLine("Error completing request: " + e.Message);
            }
        }
    }
}
const makeRequest = require('<path-to-your-utility-file>/utilities').makeRequest;

async function main() {
  try {
    const result = await makeRequest('GET', '/v1/payment_methods/required_fields/sg_credit_visa_card');

    console.log(result);
  } catch (error) {
    console.error('Error completing request', error);
  }
}
<?php
$path = $_SERVER['DOCUMENT_ROOT'];
$path .= "/<path-to-your-utility-file>/utilities.php";
include($path);

try {
    $object = make_request('get', '/v1/payment_methods/required_fields/sg_credit_visa_card');
    echo $object;
} catch (Exception $e) {
    echo "Error: $e";
}
?>
from pprint import pprint

from utilities import make_request

payment_method = 'sg_credit_visa_card'
results = make_request(method='get',
                       path=f'/v1/payment_methods/required_fields/{payment_method}')
pprint(results)

Get Payment Method Required Fields response

The response below is generated. Payment Method Type Object describes the fields in the response.

{
    "status": {
        "error_code": "",
        "status": "SUCCESS",
        "message": "",
        "response_code": "",
        "operation_id": "40e1e34d-65e5-4046-b400-dac33a36f52a"
    },
    "data": {
        "type": "sg_credit_visa_card",
        "fields": [
            {
                "name": "name",
                "type": "string",
                "regex": "",
                "is_required": true,
                "instructions": "card holder name"
            },
            {
                "name": "number",
                "type": "string",
                "regex": "",
                "is_required": true,
                "instructions": "card number"
            },
            {
                "name": "expiration_month",
                "type": "string",
                "regex": "",
                "is_required": true,
                "instructions": "expiration month as string, 01-12"
            },
            {
                "name": "expiration_year",
                "type": "string",
                "regex": "",
                "is_required": true,
                "instructions": "expiration year in to digits as string, 18-99"
            },
            {
                "name": "cvv",
                "type": "string",
                "regex": "",
                "is_required": true,
                "instructions": "card cvv"
            }
        ],
        "payment_method_options": [
            {
                "name": "3d_required",
                "type": "boolean",
                "regex": "",
                "description": "Allows the client to determine whether the customer is required to complete 3DS authentication for the transaction",
                "is_required": false,
                "is_updatable": false
            }
        ],
        "payment_options": [
            {
                "name": "capture",
                "type": "boolean",
                "regex": "",
                "description": "Determines when the payment is processed for capture.",
                "is_required": false,
                "is_updatable": false
            },
            {
                "name": "complete_payment_url",
                "type": "string",
                "regex": "",
                "description": "the complete_payment_url field must be filled in.",
                "is_required": true,
                "is_updatable": false
            },
            {
                "name": "error_payment_url",
                "type": "string",
                "regex": "",
                "description": "the error_payment_url field must be filled in.",
                "is_required": true,
                "is_updatable": false
            }
        ],
        "minimum_expiration_seconds": null,
        "maximum_expiration_seconds": null
    }
}

The data section of this response shows that no fields are required for a sg_credit_visa_card payment.

Create a Product

To offer a subscription for your service, you need a product to represent the service. To do that, use Create Product with the following parameters:

Body Parameter

Description

name

Enter your product name (for example, Acme music stream).

type

Enter your product type (for example, services).

Create Product request

Request Rapyd to create a Product ID for your product (Acme music stream in this case).

// Request URL: POST https://sandboxapi.rapyd.net/v1/products

// Message body: 
{
  "name": "Acme music stream",
  "type": "services"
}
using System;
 using System.Text.Json;

 namespace RapydApiRequestSample
 {
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                var requestObj = new
                {
                    name = "Acme music stream",
                    type = "services",
                };

                string request = JsonSerializer.Serialize(requestObj);

                string result = RapydApiRequestSample.Utilities.MakeRequest("POST", "/v1/products", request);

                Console.WriteLine(result);
            }
            catch (Exception e)
            {
                Console.WriteLine("Error completing request: " + e.Message);
            }
        }
    }
 }
const makeRequest = require('<path-to-your-utility-file>/utilities').makeRequest;

async function main() {
  try {
    const body = {
      name: 'Acme music stream',
      type: 'services'
    };
    const result = await makeRequest('POST', '/v1/products', body);

    console.log(result);
  } catch (error) {
    console.error('Error completing request', error);
  }
}
<?php
$path = $_SERVER['DOCUMENT_ROOT'];
$path .= "/<path-to-your-utility-file>/utilities.php";
include($path);

$body = [
    "name" => "Acme music stream",
    "type" => "services"
];

try {
    $object = make_request('post', '/v1/products', $body);
    var_dump($object);
} catch (Exception $e) {
    echo "Error: $e";
}
?>
from pprint import pprint

from utilities import make_request

product = {
    "name": "Acme music stream",
    "type": "services"
}

results = make_request(method='post',
                       path=f'/v1/products',
                       body=product)
pprint(results)

Create Product response

The response below is generated. Product Object describes the fields in the response.

{
    "status": {
        "error_code": "",
        "status": "SUCCESS",
        "message": "",
        "response_code": "",
        "operation_id": "8b7ef818-8030-4d63-96ed-25c1a4eb862e"
    },
    "data": {
        "id": "product_e2a72b19f064e58265e8bbc0f421d545",
        "active": true,
        "attributes": [],
        "created_at": 1617924279,
       
//      ...          
          
        "name": "Acme music stream",
    
//      ...          
          
        "type": "services",
    
//      ...          
          
        "updated_at": 1617924279
    }
}

The data section of this response shows that:

  • The product id for your product (Acme music stream) is product_e2a72b19f064e58265e8bbc0f421d545. When you run this example in your own sandbox, you will get a different ID, which you will need for a later step.
  • The product name is Acme music stream.
  • The product type is services.

Create a Plan

The next step in offering a subscription is to create a plan, which indicates the pricing settings (for your music streaming product, in this case). Use the following parameters to create a plan:

Body Parameter

Description

amount

Enter 3.00 as the monthly amount for the plan.

currency

Enter SGD as the currency code for Singapore dollar.

interval

Enter Month as the billing cycle interval.

product

Enter the product ID that you received when you created the product in your sandbox. In this instance, we are using product_e2a72b19f064e58265e8bbc0f421d545, which is the product ID we created in our sandbox.

nickname

Enter Basic as the name of the plan.

usage_type

Enter licensed as the usage type, indicating that the customer is billed even when the service is not used.

Create Plan request

Request Rapyd to create the plan chosen by the customer for the product.

// Request URL: POST https://sandboxapi.rapyd.net/v1/plans

// Message body
{
    "currency": "SGD",
    "interval": "month",
    "product": "product_4a93b26d55c5c68d085effbdf14f5e10",
    "amount": 3,
    "nickname": "Basic",
    "usage_type": "licensed"
}
using System;
 using System.Text.Json;

 namespace RapydApiRequestSample
 {
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                var requestObj = new
                {
                    currency = "CNY",
                    interval = "month",
                    product = "product_4a93b26d55c5c68d085effbdf14f5e10",
                    amount = 3,
                    nickname = "Basic",
                    usage_type = "licensed",
                };

                string request = JsonSerializer.Serialize(requestObj);

                string result = RapydApiRequestSample.Utilities.MakeRequest("POST", "/v1/plans", request);

                Console.WriteLine(result);
            }
            catch (Exception e)
            {
                Console.WriteLine("Error completing request: " + e.Message);
            }
        }
    }
 }
const makeRequest = require('<path-to-your-utility-file>/utilities').makeRequest;

async function main() {
  try {
    const body = {
      currency: 'CNY',
      interval: 'month',
      product: 'product_4a93b26d55c5c68d085effbdf14f5e10',
      amount: 3,
      nickname: 'Basic',
      usage_type: 'licensed'
    };
    const result = await makeRequest('POST', '/v1/plans', body);

    console.log(result);
  } catch (error) {
    console.error('Error completing request', error);
  }
}
<?php
$path = $_SERVER['DOCUMENT_ROOT'];
$path .= "/<path-to-your-utility-file>/utilities.php";
include($path);

$body = [
    "currency" => "CNY",
    "interval" => "month",
    "product" => "product_4a93b26d55c5c68d085effbdf14f5e10",
    "amount" => 3,
    "nickname" => "Basic",
    "usage_type" => "licensed"
];

try {
    $object = make_request('post', '/v1/plans', $body);
    var_dump($object);
} catch (Exception $e) {
    echo "Error: $e";
}
?>
from pprint import pprint

from utilities import make_request

# Create Plan request
plan = {
    "currency": "CNY",
    "interval": "month",
    "product": "product_03ec16ef9a3de2779276c86cac15d8c0",
    "amount": 3,
    "nickname": "Basic",
    "usage_type": "licensed"
}
result = make_request(method='post',
                      path='/v1/plans',
                      body=plan)
pprint(result)

Create Plan response

The response below is generated. Plan Object describes the fields in the response.

{
    "status": {
        "error_code": "",
        "status": "SUCCESS",
        "message": "",
        "response_code": "",
        "operation_id": "21c67168-3aca-42a0-b786-da0974c7548d"
    },
    "data": {
        "id": "plan_f338b9d6221a014b2c75d17963357210",
        "aggregate_usage": "sum",
        "amount": 3,
        "billing_scheme": "per_unit",
        "created_at": 1581250014,
        "currency": "SGD",
        "interval": "month",
        "interval_count": 1,
        "metadata": {},
        "product": {
            "id": "product_e2a72b19f064e58265e8bbc0f421d545",
            "active": true,
            "attributes": [],
            "created_at": 1581249912,
            "description": "",
            "images": [],
            "metadata": {},
            "name": "Acme music stream",
            "package_dimensions": {
                "height": 0,
                "length": 0,
                "weight": 0,
                "width": 0
            },
            "shippable": false,
            "skus": [],
            "statement_descriptor": "",
            "type": "service",
            "unit_label": "",
            "updated_at": 1581249912
        },
        "nickname": "Basic",
          
//      ...      
          
        "trial_period_days": 0,
        "usage_type": "licensed"
    }
}

The data section of this response shows that Rapyd created a plan ID for the Basic plan and linked it to the Product ID of the product (Acme music stream):

The ID of the Basic plan is plan_f338b9d6221a014b2c75d17963357210. When you run this example in your own sandbox, you get a different ID, which you will need for a later step.

  • Note: You can create multiple plans for the same product.

Create a Customer ID

When your customer registers for a product, you need to ask Rapyd to create a unique customer ID for your customer. Make sure that you use this ID whenever you need Rapyd to handle a request for this customer.

To create a unique customer ID for your customer, use Create Customer with the following parameters:

Body Parameter

Description

name

Enter your customer's name.

email

Enter your customer's email address.

Create Customer request

Request Rapyd to create a customer ID for your customer.

// Request URL: POST https://sandboxapi.rapyd.net/v1/customers

// Message body
{
    "name": "Test Customer",
    "email": "[email protected]"    
}
using System;
 using System.Text.Json;

 namespace RapydApiRequestSample
 {
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                var requestObj = new
                {
                    name = "Test Customer",
                    email = "[email protected]",
                };

                string request = JsonSerializer.Serialize(requestObj);

                string result = RapydApiRequestSample.Utilities.MakeRequest("POST", "/v1/customers", request);

                Console.WriteLine(result);
            }
            catch (Exception e)
            {
                Console.WriteLine("Error completing request: " + e.Message);
            }
        }
    }
 }
const makeRequest = require('<path-to-your-utility-file>/utilities').makeRequest;

async function main() {
  try {
    const body = {
      email: '[email protected]',
      name: 'Test Customer'
    };
    const result = await makeRequest('POST', '/v1/customers', body);

    console.log(result);
  } catch (error) {
    console.error('Error completing request', error);
  }
}
<?php
$path = $_SERVER['DOCUMENT_ROOT'];
$path .= "/<path-to-your-utility-file>/utilities.php";
include($path);

$body = [
    "name" => "Test Customer",
    "email" => "[email protected]"
];

try {
    $object = make_request('post', '/v1/customers', $body);
    var_dump($object);
} catch (Exception $e) {
    echo "Error: $e";
}
?>
from pprint import pprint

from utilities import make_request

# Create Customer request
costumer = {
    "name": "Test Customer",
    "email": "[email protected]"
}
result = make_request(method='post',
                      path='/v1/customers',
                      body=costumer)
pprint(result)

Create Customer response

The response below is generated. Customer Object describes the fields in the response.

{
    "status": {
        "error_code": "",
        "status": "SUCCESS",
        "message": "",
        "response_code": "",
        "operation_id": "51f3b04e-6851-4e68-ab7c-2557930b70ab"
    },
    "data": {
        "id": "cus_7511c8b024a7cf8467ee49850e14d903",
        "delinquent": false,
        "discount": null,
        "name": "Test Customer",
        "default_payment_method": "",
        "description": "",
        "email": "[email protected]",
        "phone_number": "",
        "invoice_prefix": "",
        "addresses": [],
        "payment_methods": null,
        "subscriptions": null,
        "created_at": 1581250109,
        "metadata": {},
        "business_vat_id": "",
        "ewallet": ""
    }
}

The data section of this response shows that Rapyd created a Customer ID for your customer (John Doe in this case). The Customer ID starts with cus_. Your customer's ID is cus_7511c8b024a7cf8467ee49850e14d903. When you run this example in your own sandbox, you will get a different ID, which you will need for a later step.

Add a Payment Method to your Customer

Your customer selects a preferred payment method for the product they want to subscribe to. Rapyd stores the payment method, and links it to your customer's customer ID. To do that, use Add Payment Method to Customer request with the following parameters:

Query Parameter

Description

customer

Enter the customer_id that you received when you created the customer in your sandbox. In this instance, we are using cus_7511c8b024a7cf8467ee49850e14d903, which is the customer ID we created in our sandbox.

Body Parameter

Description

type

Enter the payment method type chosen by your customer (for example, sg_credit_visa_card).

Add a Payment Method to your Customer request

Request Rapyd to add a payment method to your customer's customer ID.

// Request URL: POST https://sandboxapi.rapyd.net/v1/customers/cus_7511c8b024a7cf8467ee49850e14d903/payment_methods

// Message body: 
{
    "type": "sg_credit_visa_card"
}
using System;
 using System.Text.Json;

 namespace RapydApiRequestSample
 {
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                string customer = "cus_7b4cd1f607a0b5df13eb1871834c4480";

                var requestObj = new
                {
                    type = "sg_credit_visa_card",
                };

                string request = JsonSerializer.Serialize(requestObj);

                string result = RapydApiRequestSample.Utilities.MakeRequest("POST", $"/v1/customers/${customer}/payment_methods", request);

                Console.WriteLine(result);
            }
            catch (Exception e)
            {
                Console.WriteLine("Error completing request: " + e.Message);
            }
        }
    }
 }
const makeRequest = require('<path-to-your-utility-file>/utilities').makeRequest;

async function main() {
  try {
    const body = {
      type: 'sg_credit_visa_card'
    };
    const result = await makeRequest(
      'POST',
      '/v1/customers/cus_f3923ec56a56578b6a18df24d4f32d54/payment_methods',
      body
    );

    console.log(result);
  } catch (error) {
    console.error('Error completing request', error);
  }
}
<?php
$path = $_SERVER['DOCUMENT_ROOT'];
$path .= "/<path-to-your-utility-file>/utilities.php";
include($path);

$body = [
    "type" => "sg_credit_visa_card"
];

try {
    $object = make_request('post', '/v1/customers/cus_7511c8b024a7cf8467ee49850e14d903/payment_methods', $body);
    var_dump($object);
} catch (Exception $e) {
    echo "Error: $e";
}
?>
from pprint import pprint

from utilities import make_request

payment_method = {
    "type": "sg_credit_visa_card"
}
result = make_request(method='post',
                      path='/v1/customers/cus_ab0ffcfb3115e659788c4cecbf561a3d/payment_methods',
                      body=payment_method)
pprint(result)

Add a Payment Method to your Customer response

The response below is generated. Payment Object describes the fields in the response.

{
    "status": {
        "error_code": "",
        "status": "SUCCESS",
        "message": "",
        "response_code": "",
        "operation_id": "ee206c55-de3c-4b30-997d-723cfd0137bb"
    },
    "data": {
        "id": "other_df52ab205a95f016e0c9fd48cd7b27e7",
        "type": "sg_credit_visa_card",
        "category": "ewallet",
        "metadata": {},
        "image": ""
    }
}

The data section of this response shows:

  • Rapyd added the payment method (sg_credit_visa_card in this case) to your customer's customer ID.
  • The payment method ID is other_df52ab205a95f016e0c9fd48cd7b27e7. When you run this in your own sandbox, you will get a different ID, which you will need for a later step.

Create a Subscription

When your customer subscribes to the (Basic in this case) plan of a product, you need to ask Rapyd to create a subscription for the customer. Rapyd stores this subscription and links it to your customer's customer ID. To do that, use Create Subscription with the following parameters:

Body Parameter

Description

customer

Enter the 'customer_id' that you received when you created the customer in your sandbox. In this instance, we are using cus_7511c8b024a7cf8467ee49850e14d903, which is the customer ID we created in our sandbox.

billing

Enter pay_automatically to allow Rapyd to collect payment for each billing cycle.

cancel_at_period_end

Enter false to indicate that the subscription will continue from month to month.

payment_method

Enter the payment method 'id' that you received when you created the payment method in your sandbox. In this instance, we are using other_df52ab205a95f016e0c9fd48cd7b27e7, which is the payment method ID we created in our sandbox.

subscription_items

Enter an array that contains only one object. The object contains the following fields:

plan - Enter the plan 'id' that you received when you created the plan in your sandbox. In this instance, we are using plan_c25b26adb287fc0cbee126ef728490cd, which is the plan ID we created for our sandbox.
quantity - Enter 1, since your customer is subscribing to one instance of this plan (for example).

Create a Subscription request

Request Rapyd to create a subscription for your customer's customer ID.

// Request URL: POST /v1/subscriptions/

// Message body: 
{
    "customer": "cus_7511c8b024a7cf8467ee49850e14d903",
    "billing": "pay_automatically",
    "cancel_at_period_end": false,
    "payment_method": "other_df52ab205a95f016e0c9fd48cd7b27e7",
    "subscription_items": [
    {
            "plan": "plan_c25b26adb287fc0cbee126ef728490cd",
            "quantity": 1
        }
    ]
}
using System;
 using System.Text.Json;

 namespace RapydApiRequestSample
 {
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                var requestObj = new
                {
                    customer = "cus_159c0b21c6d50b05da31f99cde4447a6",
                    billing = "pay_automatically",
                    cancel_at_period_end = false,
                    payment_method = "other_df52ab205a95f016e0c9fd48cd7b27e7",
                    subscription_items = new Object[]
                    {
                        new
                        {
                            plan = "plan_c25b26adb287fc0cbee126ef728490cd",
                            quantity = 1
                        }
                    }
                };

                string request = JsonSerializer.Serialize(requestObj);

                string result = RapydApiRequestSample.Utilities.MakeRequest("POST", "/v1/payments/subscriptions", request);

                Console.WriteLine(result);
            }
            catch (Exception e)
            {
                Console.WriteLine("Error completing request: " + e.Message);
            }
        }
    }
 }
const makeRequest = require('<path-to-your-utility-file>/utilities').makeRequest;

async function main() {
  try {
    const body = {
      customer: 'cus_7511c8b024a7cf8467ee49850e14d903',
      billing: 'pay_automatically',
      cancel_at_period_end: false,
      payment_method: 'other_df52ab205a95f016e0c9fd48cd7b27e7',
      subscription_items: [
        {
          plan: 'plan_c25b26adb287fc0cbee126ef728490cd',
          quantity: 1
        }
      ]
    };
    const result = await makeRequest('POST', '/v1/payments/subscriptions', body);

    console.log(result);
  } catch (error) {
    console.error('Error completing request', error);
  }
}
<?php
$path = $_SERVER['DOCUMENT_ROOT'];
$path .= "/<path-to-your-utility-file>/utilities.php";
include($path);

$body = [
    "customer" => "cus_7511c8b024a7cf8467ee49850e14d903",
    "billing" => "pay_automatically",
    "cancel_at_period_end" => false,
    "payment_method" => "other_df52ab205a95f016e0c9fd48cd7b27e7",
    "subscription_items" => array(array(
        "plan" => "plan_c25b26adb287fc0cbee126ef728490cd",
        "quantity" => 1
    ))
];

try {
    $object = make_request('post', '/v1/subscriptions', $body);
    var_dump($object);
} catch (Exception $e) {
    echo "Error: $e";
}
?>
from pprint import pprint

from utilities import make_request

subscription = {
    "customer": "cus_7511c8b024a7cf8467ee49850e14d903",
    "billing": "pay_automatically",
    "cancel_at_period_end": False,
    "payment_method": "other_df52ab205a95f016e0c9fd48cd7b27e7",
    "subscription_items": [
        {
            "plan": "plan_c25b26adb287fc0cbee126ef728490cd",
            "quantity": 1
        }
    ]
}
result = make_request(method='post',
                      path='/v1/subscriptions',
                      body=subscription)
pprint(result)

Create a Subscription response

The response below is generated. Subscription Objectdescribes the fields in the response.

{
    "status": {
        "error_code": "",
        "status": "SUCCESS",
        "message": "",
        "response_code": "",
        "operation_id": "e2417a3b-837e-461f-be13-3b1d43860092"
    },
    "data": {
        "id": "sub_8ecd3def4f88fcdef6a3feb767b21925",
        "billing": "pay_automatically",
        "billing_cycle_anchor": 1581250450,
        "created_at": 1581250450,
        "customer_token": "cus_7511c8b024a7cf8467ee49850e14d903",

//    ...          
          
        "current_period_end": 1583756050,
        "current_period_start": 1581250450,
        "discount": null,
        "ended_at": null,
        "subscription_items": {
            "data": [
                {
                    "id": "subi_887020fe3760945f79707507447ca003",
                    "created": 1581250450,
                    "metadata": null,
                    "quantity": 1,
                    "plan": {
                        "id": "plan_c25b26adb287fc0cbee126ef728490cd",
                        "aggregate_usage": "sum",
                        "amount": 3,
                        "billing_scheme": "per_unit",
                        "created_at": 1581250014,
                        "currency": "SGD",
                        "interval": "month",
                        "interval_count": 1,
                        "metadata": {},
                        "product": "product_4a93b26d55c5c68d085effbdf14f5e10",
                        "nickname": "Basic",
                        
//     ...                      
                      
                        "usage_type": "licensed"
                    }
                }
            ],
            "has_more": false,
            "total_count": 0,
            "url": "/v1/subscription_items?subscription=sub_8ecd3def4f88fcdef6a3feb767b21925"
        },
        "status": "active",
        "trial_end": null,
        "trial_start": null,
        "payment_method": "other_df52ab205a95f016e0c9fd48cd7b27e7",
        "payment_fields": null,
        "payout_fields": null,
        "type": "payment"
    }
}

The data section of this response shows:

  • The id of the subscription is sub_8ecd3def4f88fcdef6a3feb767b21925. When you run this example in your own sandbox, you will get a different ID, which you will need for a later step.

View the Invoice

You can view the invoice that Rapyd generates after your customer's subscription is created, by using List Invoices request with the following parameters:

Path Parameter

Description

limit

Enter 1 to view one invoice.

subscription

Enter the subscription 'id' that you received when you created the subscription in your sandbox. In this instance, we are using sub_8ecd3def4f88fcdef6a3feb767b21925, which is the subscription ID we created in our sandbox.

List Invoices request

Request Rapyd to view the invoice for the subscription you created.

// Request URL: GET https://sandboxapi.rapyd.net/v1/invoices?limit=1&subscription=sub_8ecd3def4f88fcdef6a3feb767b21925

// Message body absent
using System;

 namespace RapydApiRequestSample
 {
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                int limit = 1;
                string subscription = "sub_8ecd3def4f88fcdef6a3feb767b21925";

                string result = RapydApiRequestSample.Utilities.MakeRequest("GET", $"/v1/invoices?limit={limit}&subscription={subscription}");

                Console.WriteLine(result);
            }
            catch (Exception e)
            {
                Console.WriteLine("Error completing request: " + e.Message);
            }
        }
    }
 }
const makeRequest = require('<path-to-your-utility-file>/utilities').makeRequest;

async function main() {
  try {
    const result = await makeRequest(
      'GET',
      '/v1/invoices?limit=1&subscription=sub_8ecd3def4f88fcdef6a3feb767b21925'
    );

    console.log(result);
  } catch (error) {
    console.error('Error completing request', error);
  }
}
<?php
$path = $_SERVER['DOCUMENT_ROOT'];
$path .= "/<path-to-your-utility-file>/utilities.php";
include($path);

try {
    $object = make_request('get', '/v1/invoices?limit=1&subscription=sub_8ecd3def4f88fcdef6a3feb767b21925');
    var_dump($object);
} catch (Exception $e) {
    echo "Error: $e";
}
?>
from pprint import pprint

from utilities import make_request

# List Invoices request
result = make_request(method='get',
                      path='/v1/invoices?limit=1&subscription=sub_c86c7357323d074248f6a38b1c4d34b8')
pprint(result)

List Invoices response

The response below is generated. Invoice Object describes the fields in the response.

{
    "status": {
        "error_code": "",
        "status": "SUCCESS",
        "message": "",
        "response_code": "",
        "operation_id": "60f04bb6-af51-4a1a-8d23-3092675549b8"
    },
    "data": [
        {
            "id": "invoice_a6fe6055e85560d464fe53bcadacf553",
            "attempt_count": 0,
            "billing": "pay_automatically",
            "billing_reason": "subscription_create",
            "currency": "SGD",
            "customer": "cus_7511c8b024a7cf8467ee49850e14d903",
            "description": "",
            "discount": null,
            "due_date": 1583842451000,
            "days_until_due": 0,

//          ...          
          
            "period_end": 1583756050000,
            "period_start": 1581250450000,
            "lines": [
                {
                    "id": "il_fde5c399f3624b8a2c2d22f1b2cfe5a0",
                    "amount": 3,
                    "currency": "SGD",
                    "description": "Acme music stream",
                    "discountable": true,
                    "invoice_item": "",
                    "metadata": {},
                    "period": {
                        "start": 1581250450,
                        "end": 1583756050
                    },
                    "proration": false,
                    "quantity": 1,
                    "plan": {
                        "id": "plan_c25b26adb287fc0cbee126ef728490cd",
                        "aggregate_usage": "sum",
                        "amount": 3,
                        "billing_scheme": "per_unit",
                        "created_at": 1581250014,
                        "currency": "SGD",
                        "interval": "month",
                        "interval_count": 1,
                        "metadata": {},
                        "nickname": "Basic",
                       
//        ...                      
                      
                        "trial_period_days": 0,
                        "usage_type": "licensed"
                    },
                    "subscription": "sub_8ecd3def4f88fcdef6a3feb767b21925",
                    "subscription_item": "subi_887020fe3760945f79707507447ca003",
                    "type": "subscription"
                }
            ],
            "statement_descriptor": "",
            "subscription": "sub_8ecd3def4f88fcdef6a3feb767b21925",
            "subtotal": 3,
            "tax": 0,
            "tax_percent": 0,
            "total": 3,
            "status": "draft",
            "payout_fields": null,
            "type": "payment"
        }
    ]
}

The data section of this response shows that the invoice is due now since the value for the days_until_due field is '0'.

Note: When no trial period is provided and the usage_type is licensed, the billing date is at the start of the billing cycle.

📘

Looking for more in-depth technical information?

Want to see the Rapyd API methods and objects that you'll use?
Visit the Rapyd API Reference Documentation for more technical details.

Updated about a month ago


What's Next

Mass Invoices

Subscriptions


With Rapyd Collect you can create subscriptions (also called subscription billing), recurring billing or recurring payments.

Suggested Edits are limited on API Reference Pages

You can only suggest edits to Markdown body content, but not to the API spec.