HelloWorld.cs - How to run CSharp Sample Code using the Hello World API and Mutual SSL

shameem
Visa Employee

HelloWorld.cs - How to run CSharp Sample Code using the Hello World API and Mutual SSL

In this "How-to" guide we will show you how to run the “Hello World” project using Visa Hello World API and Two-Way SSL (Mutual 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.

 

java1.png

 

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.

 

Java2.png

 

For this tutorial, we're going to select “Visa Direct” and click create project.

 

 

Java3.png

 

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”.

 

Java4.png

 

What is required for the Two-Way SSL (Mutual Authentication)?

 

To be able to make an API call with 2-way SSL authentication, you need to have the following:

 

  1. User ID
  2. Password
  3. Your client cert
  4. Your private key previously downloaded
  5. Visa Development Platform Certificate

Java5.png

 

 

You will need to download the project certificate as well as the common certificates - Visa Developer Platform certificate and DigiCert Certificate and save them in the correct directory. 

 

 

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:

 

https://visualstudio.microsoft.com/downloads/

 

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.

 

2020-11-12_12-05-37.png

 

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.

 

 

2020-11-12_12-08-53.png

 

 

Step 3 - Name the project

 

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

 

 

2020-11-12_12-11-50.png

 

 

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

 

 

2020-11-12_12-13-08.png

 

Set the below parameters:

 

public static string userId = "<YOUR USER ID>";

public static string password = "<YOUR PASSWORD>";

 

public static string cert = "<YOUR CLIENT CERTIFICATE PATH>";

public static string certPassword = "<YOUR CERTIFICATE PASSWORD>";

 

 

 

 

 

/*
 * (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.*
*
*/
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

namespace HelloWorld
{

    class Program
    {
        public static string visaUrl = "https://sandbox.api.visa.com/";
        public static string userId = "<YOUR USER ID>";
        public static string password = "<YOUR PASSWORD>";

        public static string cert = "<YOUR CLIENT CERTIFICATE PATH>";
        public static string certPassword = "<YOUR CERTIFICATE PASSWORD>";

        static void Main(string[] args)
        {
            Console.WriteLine("START Sample Code for Two-Way (Mutual) SSL!");

            Program program = new Program();
            program.DoMutualAuthCall("vdp/helloworld", "GET", null, null, null);

            Console.WriteLine("END Sample Code for Two-Way (Mutual) SSL!");
        }

        private void LogRequest(string url, string requestBody)
        {
            Debug.WriteLine(url);
            Debug.WriteLine(requestBody);
        }

        private void LogResponse(string info, HttpWebResponse response)
        {
            string responseBody;
            Debug.WriteLine(info);
            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);
        }

        private string GetBasicAuthHeader(string userId, string password)
        {
            string authString = userId + ":" + password;
            var authStringBytes = Encoding.UTF8.GetBytes(authString);
            string authHeaderString = Convert.ToBase64String(authStringBytes);
            return "Basic " + authHeaderString;
        }

        public string DoMutualAuthCall(string path, string method, string testInfo, string requestBodyString, Dictionary<string, string> headers = null)
        {
            string requestURL = visaUrl + path;
            string certificatePath = cert;
            string certificatePassword = certPassword;
            string statusCode = "";
            LogRequest(requestURL, requestBodyString);
            // Create the POST request object
            HttpWebRequest request = WebRequest.Create(requestURL) as HttpWebRequest;
            request.ContentType = "application/json";
            request.Accept = "application/json";

            request.Method = method;
            if (method.Equals("POST") || method.Equals("PUT"))
            {
                // Load the body for the post request
                var requestStringBytes = Encoding.UTF8.GetBytes(requestBodyString);
                request.GetRequestStream().Write(requestStringBytes, 0, requestStringBytes.Length);
            }

            if (headers != null)
            {
                foreach (KeyValuePair<string, string> header in headers)
                {
                    request.Headers[header.Key] = header.Value;
                }
            }

            // Add headers
            request.Headers["Authorization"] = GetBasicAuthHeader(userId, password);

            // Add certificate
            var certificate = new X509Certificate2(certificatePath, certificatePassword);
            request.ClientCertificates.Add(certificate);

            try
            {
                // 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;
        }

    }
}

 

 

 

 

Step 5 - Compile Your Code 

 

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

2020-11-12_12-13-30.png

 

 

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