HelloWorld.java - How to run Java Sample Code using the Hello World API and X-Pay-Token

Visa Employee

HelloWorld.java - How to run Java Sample Code using the Hello World API and X-Pay-Token

In this "How-to" guide we will show you how to run the “Hello World” project using Visa Hello World API and and API Key - Shared Secret Authentication. The Hello World API is a simple API for testing the connectivity with the Visa Network.


Important Links:



How to Create a Visa Developer Project


Before you are able to run the “Hello World” Project, you must create a Visa Developer Portal (VDP) project and get credentials. If you haven't registered yet just click on register here, fill out the account information, agree to the terms and conditions and click on receive emails. Once you have successfully activated your account, you will see your dashboard and you are ready to go.






Once you are there, click on create your first project if this is your first project.  On the next page, you will be asked for details, such as project name, description and a list of APIs to choose from.





For this tutorial, we're going to select CyberSource Payments and click create project.







How to get Credentials


After creating your project, you will be redirected to the project summary page. You can obtain your project credentials by browsing the left side navigation menu of your project and click on “Credentials”.





What is required for the X-Pay-Token Authentication?


To be able to make an API call with X-Pay-Token Authentication, you need to have the following:

  1. Api Key
  2. Secret Key




How to run the Java Sample codes of the “Hello World API” using IntelliJ


Next, we'll show you how to run the Java sample code of the “Hello World API” using IntelliJ. IntelliJ IDEA is a cross-platform IDE that provides consistent experience on Windows, macOS, and Linux, and can be downloaded here. In IntelliJ IDEA, a project helps you organize your source code, tests, libraries that you use, build instructions, and your personal settings in a single unit.



Step 1: Launch IntelliJ IDEA


  • If the Welcome screen opens, click Create New Project. Otherwise, from the main menu, select File | New | Project.




Step 2 - In the New Project wizard, select Java from the list on the left.


To develop Java applications in IntelliJ IDEA, you need the Java SDK (JDK).


  • If the necessary JDK is already defined in IntelliJ IDEA, select it from the Project SDK list.
  • If the JDK is installed on your computer, but not defined in the IDE, select Add JDK and specify the path to the JDK home directory.
  • If you don't have the necessary JDK on your computer, select Download JDK.


We're not going to use any additional libraries or frameworks for this tutorial, so click Next. Don't create a project from the template. In this tutorial, we're going to do everything from scratch, so click Next.



Step 3 - Name the project


  • For example: HelloWorld. If necessary, change the default project location and click Finish.




Step 4 - Create a Java class and named it as HelloWorld in the “src” folder




Copy the below Java code and paste it to the Helloworld Java File and set the below parameters. 


String apiKey = "<YOUR API KEY>";

String sharedSecret = "<YOUR SHARED SECRET>";




 * (c) Copyright 2018 - 2020 Visa. All Rights Reserved.**
 * NOTICE: The software and accompanying information and documentation (together, the “Software”) remain the property of and are proprietary to Visa and its suppliers and affiliates. The Software remains protected by intellectual property rights and may be covered by U.S. and foreign patents or patent applications. The Software is licensed and not sold.*
 *  By accessing the Software you are agreeing to Visa's terms of use (developer.visa.com/terms) and privacy policy (developer.visa.com/privacy).In addition, all permissible uses of the Software must be in support of Visa products, programs and services provided through the Visa Developer Program (VDP) platform only (developer.visa.com). **THE SOFTWARE AND ANY ASSOCIATED INFORMATION OR DOCUMENTATION IS PROVIDED ON AN “AS IS,” “AS AVAILABLE,” “WITH ALL FAULTS” BASIS WITHOUT WARRANTY OR  CONDITION OF ANY KIND. YOUR USE IS AT YOUR OWN RISK.** All brand names are the property of their respective owners, used for identification purposes only, and do not imply product endorsement or affiliation with Visa. Any links to third party sites are for your information only and equally  do not constitute a Visa endorsement. Visa has no insight into and control over third party content and code and disclaims all liability for any such components, including continued availability and functionality. Benefits depend on implementation details and business factors and coding steps shown are exemplary only and do not reflect all necessary elements for the described capabilities. Capabilities and features are subject to Visa’s terms and conditions and may require development,implementation and resources by you based on your business and operational details. Please refer to the specific API documentation for details on the requirements, eligibility and geographic availability.*
 * This Software includes programs, concepts and details under continuing development by Visa. Any Visa features,functionality, implementation, branding, and schedules may be amended, updated or canceled at Visa’s discretion.The timing of widespread availability of programs and functionality is also subject to a number of factors outside Visa’s control,including but not limited to deployment of necessary infrastructure by issuers, acquirers, merchants and mobile device manufacturers.*

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.SignatureException;

public class Helloworld {

    public static void main(String[] args) throws Exception {

        // THIS IS EXAMPLE ONLY how will apiKey and password look like
        // apiKey = "1WM2TT4IHPXC8DQ5I3CH21n1rEBGK-Eyv_oLdzE2VZpDqRn_U";
        // sharedSecret = "19JRVdej9";
        String apiKey = "<YOUR API KEY>";
        String sharedSecret = "<YOUR SHARED SECRET>";

        String resourcePath = "helloworld";
        String queryString = "apiKey=" + apiKey;
        String requestBody = "";

        System.out.println("START Sample Code for Api Key-Shared Secret (X-Pay-Token)");
        URL url = new URL("https://sandbox.api.visa.com/vdp/helloworld?" + queryString);

        HttpURLConnection con = (HttpURLConnection) url.openConnection();

        con.setRequestProperty("Content-Type", "application/json");
        con.setRequestProperty("Accept", "application/json");

        String xPayToken = generateXpaytoken(resourcePath, queryString, requestBody, sharedSecret);
        con.setRequestProperty("x-pay-token", xPayToken);

        int status = con.getResponseCode();
        System.out.println("Http Status: " + status);

        BufferedReader in;
        if (status == 200) {
            in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        } else {
            in = new BufferedReader(new InputStreamReader(con.getErrorStream()));
            System.out.println("Api Key-Shared Secret (X-Pay-Token) test failed");
        String response;
        StringBuffer content = new StringBuffer();
        while ((response = in.readLine()) != null) {

        System.out.println("END Sample Code for Api Key-Shared Secret (X-Pay-Token)");

    public static String generateXpaytoken(String resourcePath, String queryString, String requestBody, String sharedSecret) throws SignatureException {
        String timestamp = timeStamp();
        String beforeHash = timestamp + resourcePath + queryString + requestBody;
        String hash = hmacSha256Digest(beforeHash, sharedSecret);
        String token = "xv2:" + timestamp + ":" + hash;
        return token;

    private static String timeStamp() {
        return String.valueOf(System.currentTimeMillis() / 1000L);

    private static String hmacSha256Digest(String data, String sharedSecret)
            throws SignatureException {
        return getDigest("HmacSHA256", sharedSecret, data, true);

    private static String getDigest(String algorithm, String sharedSecret, String data, boolean toLower) throws SignatureException {
        try {
            Mac sha256HMAC = Mac.getInstance(algorithm);
            SecretKeySpec secretKey = new SecretKeySpec(sharedSecret.getBytes(StandardCharsets.UTF_8), algorithm);

            byte[] hashByte = sha256HMAC.doFinal(data.getBytes(StandardCharsets.UTF_8));
            String hashString = toHex(hashByte);

            return toLower ? hashString.toLowerCase() : hashString;
        } catch (Exception e) {
            throw new SignatureException(e);

    private static String toHex(byte[] bytes) {
        BigInteger bi = new BigInteger(1, bytes);
        return String.format("%0" + (bytes.length << 1) + "X", bi);




Step 5 - Compile Your Code 

  • Click the Run the Remove button in the gutter and select Run 'Helloworld.main()' in the popup. The IDE starts compiling your code.  When the compilation is complete, the Run tool window opens at the bottom of the screen.



Want more? Join the Visa Developer Community to get alerts on the latest tutorials, guides and new developer resources. Stay tuned for more in the series. 


Written by: @shameem@jmedlen, & @mprsic