Re: HelloWorld.cs - How to run CSharp Sample Code using the Hello World API and X-Pay-Token

Solved! Go to solution
Visa Employee

HelloWorld.cs - How to run CSharp 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 C# Sample code of the “Hello World API” using Microsoft Visual Studio



Next, we'll show you how to run the C# sample code of the “Hello World API” using Microsoft Visual Studio. Microsoft Visual Studio is an integrated development environment from Microsoft. It is used to develop computer programs, as well as websites, web apps, web services and mobile apps, and can be downloaded using below link:


In Visual Studio, 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 Visual Studio


  • On the Visual Studio Welcome Screen, click Create a new Project.




Step 2 - In the Create a new project wizard, we will select Console App (.Net Code) from the list on the right and click next.






Step 3 - Name the project


  • Provide the project Project Name, check on box Place solution and project in the same directory and click Create.






Step 4 - Copy the below sample code to the “Program.cs” file






Set the below parameters:


public static string apiKey = "<YOUR API KEY>";

public static 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 ( and privacy policy ( 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 ( **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.*
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Security.Cryptography;
using System.Diagnostics;
using System.Linq;

namespace Helloworld
    class Program
        public static string visaUrl = "";
        public static string apiKey = "<YOUR API KEY>";
        public static string sharedSecret = "<YOUR SHARED SECRET>";

        static void Main(string[] args)
            Console.WriteLine("START Sample Code for Api Key-Shared Secret (X-Pay-Token)!");
            Program program = new Program();

            string queryString = "apiKey=" + apiKey;
            String status = program.DoXPayTokenCall("vdp/", "helloworld", queryString, "GET", null, null);
            Debug.WriteLine("Status  :" + status);

            Console.WriteLine("END Sample Code for Api Key-Shared Secret (X-Pay-Token)!");

        private void LogRequest(string url, string requestBody)

        private void LogResponse(string info, HttpWebResponse response)
            string responseBody;
            Debug.WriteLine("Response Status: \n" + response.StatusCode);
            Debug.WriteLine("Response Headers: \n" + response.Headers.ToString());

            using (var reader = new StreamReader(response.GetResponseStream(), ASCIIEncoding.ASCII))
                responseBody = reader.ReadToEnd();

            Debug.WriteLine("Response Body: \n" + responseBody);

        //Correlation Id ( ex-correlation-id ) is an optional header while making an API call. You can skip passing the header while calling the API's.
        private string GetCorrelationId()
            const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            var random = new Random();
            return new string(Enumerable.Repeat(chars, 12).Select(s => s[random.Next(s.Length)]).ToArray()) + "_SC";


        public string DoXPayTokenCall(string baseUri, string resourcePath, string queryString, string method, string testInfo, string requestBodyString)
            string requestURL = visaUrl + baseUri + resourcePath + "?" + "apikey=" + apiKey;
            string apikey = apiKey;
            LogRequest(requestURL, requestBodyString);
            // Create the POST request object
            string statusCode = "";
            HttpWebRequest request = WebRequest.Create(requestURL) as HttpWebRequest;
            request.Method = method;
            if (method.Equals("POST") || method.Equals("PUT"))
                request.ContentType = "application/json";
                request.Accept = "application/json";
                // Load the body for the post request
                var requestStringBytes = Encoding.UTF8.GetBytes(requestBodyString);
                request.GetRequestStream().Write(requestStringBytes, 0, requestStringBytes.Length);

            string xPayToken = GetXPayToken(resourcePath, "apikey=" + apikey, requestBodyString);
            request.Headers["x-pay-token"] = xPayToken;
            request.Headers["ex-correlation-id"] = GetCorrelationId();

                // Make the call
                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                    LogResponse(testInfo, response);
                    statusCode = response.StatusCode.ToString();
            catch (WebException e)
                if (e.Response is HttpWebResponse)
                    HttpWebResponse response = (HttpWebResponse)e.Response;
                    LogResponse(testInfo, response);
                    statusCode = response.StatusCode.ToString();
            return statusCode;

        private static string GetXPayToken(string apiNameURI, string queryString, string requestBody)
            string timestamp = GetTimestamp();
            string sourceString = timestamp + apiNameURI + queryString + requestBody;
            string hash = GetHash(sourceString);
            string token = "xv2:" + timestamp + ":" + hash;
            return token;

        private static string GetTimestamp()
            long timeStamp = ((long)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds) / 1000;
            return timeStamp.ToString();

        private static string GetHash(string data)
            var hashString = new HMACSHA256(Encoding.ASCII.GetBytes(sharedSecret));
            var hashbytes = hashString.ComputeHash(Encoding.ASCII.GetBytes(data));
            string digest = String.Empty;

            foreach (byte b in hashbytes)
                digest += b.ToString("x2");

            return digest;





Step 5 - Compile Your Code 


  • Simply click on the “Start” to run HelloWorld Program




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 


Re: HelloWorld.cs - How to run CSharp Sample Code using the Hello World API and X-Pay-Token

good working ... but is this code working with .net 4.7 and postman ... I tried it but not working 

Visa Developer Support Specialist
Visa Developer Support Specialist

Re: HelloWorld.cs - How to run CSharp Sample Code using the Hello World API and X-Pay-Token

Hi @shameem,


Can you please let us know if the code works with .net 4.7 and postman? Thanks.


Was your question answered? Don't forget to click on "Accept as Solution" to help other devs find the answer to the same question.
Visa Employee

Re: HelloWorld.cs - How to run CSharp Sample Code using the Hello World API and X-Pay-Token

Hi @adamlee,


Thank you for trying out the C# Sample Code.  Could you please let us know what issues are you facing with .Net 4.7?


You can find the "How To" guide for Postman here:


Feel free to reach out if you have further queries.


Thank you.