HOWTO: Getting started with the HMRC APIs

Hi all,

here is some code, half complete, which shows a way to connect to the HRMC VAT apis, using OAuth.
See
https://developer.service.hmrc.gov.uk/a … at-api/1.0

The code currently connects to the sandbox test environment.
It may be used as a starting point to connect to other HMRC apis.

/**
 * @private
 * @type {String}
 *
 * @properties={typeid:35,uuid:"BAB6531E-4AD0-42E6-A0F5-9F00BE9FB377"}
 */
var clientID = [YOUR CLIENT ID];

/**
 * @private
 * @type {String}
 *
 * @properties={typeid:35,uuid:"35332694-F164-429E-A1F2-4F141115F2B8"}
 */
var clientSecret = [YOUR CLIENT SECRET];

/**
 * @type {String}
 *
 * @properties={typeid:35,uuid:"14C7A664-6CD6-4C55-AC59-413CB8D20F44"}
 */
var serverToken = [YOUR SERVER TOKEN];

/**
 * @type {String}
 *
 * @properties={typeid:35,uuid:"BF9DF7EC-2D3A-464A-8BFB-129FE4D782FC"}
 */
var END_POINT = "https://test-api.service.hmrc.gov.uk";

/**
 * @private
 * @type {String}
 *
 * @properties={typeid:35,uuid:"EBC4D581-791A-48B8-A746-E6259720A07F"}
 */
var AUTH_URI = END_POINT + "/oauth/authorize";

/**
 * @type {String}
 *
 * @properties={typeid:35,uuid:"F796D33A-AEF4-42A8-BC18-1594C03AD1F1"}
 */
var VAT_NUMBER = [YOUR VAT NUMBER];

/**
 * @private
 * @type {String}
 *
 * @properties={typeid:35,uuid:"9EAD332D-B1A7-4DCC-AD1F-A61AE31190D0"}
 */
var TOKEN_URI = END_POINT + "/oauth/token";

/**
 * @private
 * @type {String}
 *
 * @properties={typeid:35,uuid:"FD9AA512-F219-45F4-A15B-947904EB1368"}
 */
var OBLIGATION_URI = END_POINT + "/organisations/vat/" + VAT_NUMBER + "/obligations"

/**
 * @type {String}
 *
 * @properties={typeid:35,uuid:"07D76C39-BA33-4DBE-8517-880D3B976FA1"}
 */
var SUBMIT_RETURN_URI = END_POINT + "/organisations/vat/" + VAT_NUMBER + "/returns"

/**
 * @type {String}
 *
 * @properties={typeid:35,uuid:"1095EA47-F19E-4DFD-A56D-80DF83629FCF"}
 */
var AUTHORISATION_CODE = '';

/**
 * @type {String}
 *
 * @properties={typeid:35,uuid:"A7DEF904-0171-4EB4-BCB9-5DCF04E9C426"}
 */
var ACCESS_TOKEN = '';

/**
 * @type {String}
 *
 * @properties={typeid:35,uuid:"A102F7E3-7447-4A6E-A23F-9117DC490E29"}
 */
var REFRESH_TOKEN = '';

/**
 * @private
 * @enum
 * @type {String}
 *
 * @properties={typeid:35,uuid:"79E4C8F0-9500-42C3-BC19-AD6BBDBA9DCE"}
 */
var SCOPES = 'read:vat+write:vat'

/**
 *
 * @properties={typeid:24,uuid:"4C5EA0D6-5557-4D92-B3A8-12AE431A018C"}
 * @param {plugins.http.Response} response
 */
function check_response(response) {

	application.output(response.getStatusCode());
	application.output(response.getResponseBody());
}

/**
 * @properties={typeid:24,uuid:"0EEAC238-0987-4693-A3EC-41BCCF0BE495"}
 */
function get_authorisation() {
	var url = AUTH_URI + "?response_type=code";
	url += "&client_id=" + clientID;
	url += "&scope=" + SCOPES;
	url += "&redirect_uri=urn:ietf:wg:oauth:2.0:oob";
	//application.output(url);
	application.showURL(url);
	AUTHORISATION_CODE = plugins.dialogs.showInputDialog("HMRC", "Paste code here:")
}

/**
 * @properties={typeid:24,uuid:"C8DFBA73-134A-477B-95D8-F07A9643B4C3"}
 */
function get_access_token() {
	var client_ = plugins.http.createNewHttpClient();
	var url = TOKEN_URI;
	var body = '';
	body += 'client_secret=' + clientSecret;
	body += '&client_id=' + clientID;
	body += '&grant_type=authorization_code'
	body += '&redirect_uri=urn:ietf:wg:oauth:2.0:oob'
	body += '&code=' + AUTHORISATION_CODE;

	var poster = client_.createPostRequest(url);
	poster.setBodyContent(body)
	poster.addHeader("Accept", "application/vnd.hmrc.1.0+json");
	poster.addHeader("Content-Type", "application/x-www-form-urlencoded");

	poster.executeAsyncRequest(extract_tokens, check_error);
}

/**
 * @param {plugins.http.Response} response
 *
 * @properties={typeid:24,uuid:"18044A61-EDCB-4512-B98B-5E26778C5F42"}
 */
function extract_tokens(response) {
	application.output(response.getResponseBody());
	var response_body = JSON.parse(response.getResponseBody());
	application.setUserProperty("ACCESS_TOKEN",response_body['access_token'])
	application.setUserProperty("REFRESH_TOKEN",response_body['refresh_token'])
	//ACCESS_TOKEN = response_body['access_token']
	//REFRESH_TOKEN = response_body['refresh_token']
}

/**
 * @param {plugins.http.Response} response
 * @properties={typeid:24,uuid:"2DD0674E-0DAF-43DD-B4ED-25545645103B"}
 */
function check_error(response) {
	application.output(response.getStatusCode());
	application.output(response.getResponseBody());
}

/**
 * @properties={typeid:24,uuid:"E861A2BC-5744-45A4-8EFB-FE8865F75541"}
 */
function get_obligations() {
	var client_ = plugins.http.createNewHttpClient();
	var url = OBLIGATION_URI + '?status=O';
	var getter = client_.createGetRequest(url);

	getter.addHeader("Accept", "application/vnd.hmrc.1.0+json");
	getter.addHeader("Authorization", "Bearer " + application.getUserProperty("ACCESS_TOKEN"));
	getter.executeAsyncRequest(obligations_response, check_error);
}

/**
 * @param {plugins.http.Response} response
 *
 * @properties={typeid:24,uuid:"EB940807-120E-4B64-853F-9B9213069AA6"}
 */
function obligations_response(response) {
	if (response.getStatusCode() == 200) {
		var body = JSON.parse(response.getResponseBody());
		var obligations = body["obligations"];
		if(obligations[0]) {
			//a VAT return is due
			var obligation = obligations[0];
			application.output(obligation);
			var start_date = utils.parseDate(obligation['start'],"yyyy-MM-dd");
			var end_date   = utils.parseDate(obligation['end'],"yyyy-MM-dd");
			var status     = obligation['status'];
			var period_key = obligation['periodKey'];
			forms.acc_vat_returns.locate_return(start_date, end_date, status, period_key);
		}
	} else {
		return null;
	}
}

//The VAT Return table has a number of fields starting in hmrc_

/**
 * @properties={typeid:24,uuid:"6695A3EF-8A20-4BF1-A8FE-FAC013C912CF"}
 * @param {JSRecord<db:/[MY DATABASE NAME]/[MY VAT RETURN TABLE]>} vat_return
 */
function submit_return(vat_return) {
	if (!vat_return.hmrc_processing_date) {
		var client_ = plugins.http.createNewHttpClient();
		var url = SUBMIT_RETURN_URI;
		var poster = client_.createPostRequest(url);
		var body = JSON.stringify({
			periodKey: vat_return.hmrc_period_key,
			vatDueSales: vat_return.hmrc_vat_due_sales,
			vatDueAcquisitions: vat_return.hmrc_vat_due_acquisitions,
			totalVatDue: vat_return.hmrc_total_vat_due,
			vatReclaimedCurrPeriod: vat_return.hmrc_vat_reclaimed_curr_period,
			netVatDue: Math.abs(Math.round(100 * vat_return.hmrc_net_vat_due) /100),
			totalValueSalesExVAT: vat_return.hmrc_total_value_sales_ex_vat,
			totalValuePurchasesExVAT: vat_return.hmrc_total_value_purchases_ex_vat,
			totalValueGoodsSuppliedExVAT: (vat_return.hmrc_total_value_goods_supplied_ex_vat || 0),
			totalAcquisitionsExVAT: (vat_return.hmrc_total_acquisitions_ex_vat || 0),
			finalised: true
		});
		
		application.output(body);
		if(plugins.dialogs.showQuestionDialog("VAT Return","Submit VAT Return now?","No","Yes") == "Yes") {
			poster.addHeader("Accept", "application/vnd.hmrc.1.0+json");
			poster.addHeader("Content-Type", "application/json");
			poster.addHeader("Authorization", "Bearer " + application.getUserProperty("ACCESS_TOKEN"));
			poster.setBodyContent(body)
			poster.executeAsyncRequest(returns_response, check_error);
		}
	}
}

/**
 * @param {plugins.http.Response} response
 *
 * @properties={typeid:24,uuid:"7652EE8C-31D0-4C49-AE33-A90D7C2AEF68"}
 */
function returns_response(response) {
	application.output(response.getStatusCode());
	application.output(response.getResponseBody());
	if (response.getStatusCode() == 201) {
		var body = JSON.parse(response.getResponseBody());
		application.output(body);
		return body;
	} else {
		return '';
	}
}