In Chargebee you can have additional 'custom' fields associated with the customer. They are very useful for tracking additional information about a customer or a subscription. Once the custom fields are created, they can be accessed through the admin console and using the API.
Click here to learn more about custom fields in Chargebee.
In this tutorial we will be explaining about accessing and updating custom fields using the API.
Honey Comics - Demo Application
'Honey Comics', our demo application, is a fictitious online comic book store providing a subscription service for comics. We send comic books every week to subscribers. In order to let customers try the service, we provide them with a free trial period for two weeks.
In addition to the basic account information such as email, phone number we need the genre (fiction, action, adventure, etc.) that the user is interested in. We also need to get their date of birth as we want to send a surprise package of comics as a birthday gift.
Prerequisites
To try out the tutorial yourself, you'll need the following:
- A Chargebee account. Signup for a free trial if you don't have one.
- A plan with a trial period in Chargebee.
- Your Chargebee API key for your test site.
- Also the custom fields (genre and date of birth) should have been setup for your account.
The Honey Comics signup form is a simple form requiring only basic account information. We also get the two additional information (genre and date of birth).
Here's the code for the genre field in signup form :
<label for="city">Comics Genre</label>
<select class="form-control" name="customer[cf_comics_type]">
<option> Adventures </option>
<option> Action </option>
<option> Fantasy </option>
<option> Horror </option>
<option> Romance </option>
</select>
Now lets switch to the server side implementation
Setup the Chargebee client library
You have to download and import the client library of our choice. Then, configure the client library with your test site and its api key.
For the tutorial, we have configured the site and the credentials in a separate properties file. When the webapp is initialized, the client library gets configured.
/**
* The credentials are stored in a properties file under WEB-INF
* The live site api keys should be stored securely. It should preferably
* be stored only in the production machine(s) and not hard coded
* in code or checked into a version control system by mistake.
*/
Properties credentials = read("WEB-INF/ChargeBeeCredentials.properties");
Environment.configure(credentials.getProperty("site"),
credentials.getProperty("api_key"));
For the tutorial, we have configured the site credentials in config/environments/development.rb
ENV["CHARGEBEE_SITE"]="honeycomics-test"
ENV["CHARGEBEE_API_KEY"]="test_3gfwsdd6doB2EKRP7cufTd5TvT32a5BrT"
We setup the client library in config/initializers/chargebee.rb
# Configuring the server for ChargeBee API call.
ChargeBee.configure(:site => ENV["CHARGEBEE_SITE"],
:api_key => ENV["CHARGEBEE_API_KEY"])
For the tutorial, we have configured the site credentials in Config.php
require_once(dirname(__FILE__) . "/lib/ChargeBee.php");
/*
* Sets the environment for calling the Chargebee API.
* You need to sign up at ChargeBee app to get this credential.
* It is better if you fetch configuration from the environment
* properties instead of hard coding it in code.
*/
ChargeBee_Environment::configure("honeycomics-test",
"test_3gfwsdd6doB2EKRP7cufTd5TvT32a5BrT");
Handle Signup Request
On the server side we get the signup details, do the necessary validations (which is skipped in demo) and then call the Create Subscription API to create the subscription.
Note: The custom fields are passed under customer resource.
Result responseResult = Subscription.create().planId("basic")
.customerFirstName(request.getParameter("customer[first_name]"))
.customerLastName(request.getParameter("customer[last_name]"))
.customerEmail(request.getParameter("customer[email]"))
.customerPhone(request.getParameter("customer[phone]"))
// custom field attribute
.param("customer[cf_comics_type]",
request.getParameter("customer[cf_comics_type]"))
// custom field attribute
.param("customer[cf_date_of_birth]", dateString )
.request();
$customer = $_POST["customer"];
$customer["cf_date_of_birth"] = $dob;
$result = ChargeBee_Subscription::create(
array("plan_id" => "basic",
"customer" => $customer) );
customer = params["customer"]
customer[:cf_date_of_birth] = dob
result = ChargeBee::Subscription.create({
:plan_id => "basic",
:customer => customer } )
Redirect the user to the result page
Now that the subscription has been successfully created we redirect the user to a 'thank you' page. In our demo, since we've used Ajax to submit the form data, the forwarding is done on the client side using JavaScript.
String queryParameters = "subscription_id=" +
URLEncoder.encode(responseResult.subscription().id(), "UTF-8");
out.write("{\"forward\": \"thankyou.jsp?"+ queryParameters + "\"}");
$subscription = $result->subscription();
$queryParameters = "subscription_id=" . urlencode($subscription->id);
$jsonResp["forward"] = "thankyou?" . $queryParameters;
echo json_encode($jsonResp, true);
render json: {
:forward => "thankyou?subscription_id=#{URI.escape(result.subscription.id)}"
}
'Thank you' Page
We have fetched the subscription details using the Retrieve a Subscription API. The response contains the customer resource containing the values for the custom fields which is displayed.
<%
String subscriptionId = request.getParameter("subscription_id");
Result result = Subscription.retrieve(subscriptionId).request();
// Retrieving the custom field from response
String dob = result.customer().optString("cf_date_of_birth");
// Retrieving the custom field from response
String comicsType = result.customer().optString("cf_comics_type");
SimpleDateFormat srcFormat = new SimpleDateFormat("yyyy-MM-dd");
Date d = srcFormat.parse(dob);
SimpleDateFormat destFormat = new SimpleDateFormat("MMM dd");
%>
$subscriptionId = $_GET["subscription_id"];
$result = ChargeBee_Subscription::retrieve($subscriptionId);
$dob = $result->customer()->cfDateOfBirth;
$comicsType = $result->customer()->cfComicsType;
subscriptionId = params["subscription_id"]
result = ChargeBee::Subscription.retrieve(subscriptionId)
dob = result.customer.cf_date_of_birth
@dob = Date.strptime(dob,"%Y-%m-%d").strftime("%b %d")
@comicsType = result.customer.cf_comics_type
Validation and Error Handling
Here's how we validate user inputs and handle API call errors in this demo:
Client Side Validation: Chargebee uses jQuery form validation plugin to check whether the user's field inputs(email, zip code and phone number) are valid or not.
Server Side Validation: As this is a demo application we have skipped the server side validation of all input parameters. But we recommend you to perform the validation at your end.
General API Errors: Chargebee might return error responses due to various reasons such as invalid configuration, bad request etc. To identify specific reasons for all error responses you can check the API documentation . Also take a look at the error handler file to check how these errors can be handled.