Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Overview

This page provides sample code for creating REST clients for various popular programming languages.

 

Table of Contents

 

1. REST client code sample in JVM using JAVA

 

-In this tutorial, we show how to create a RESTful Java client with Java built-in HTTP client library. It’s simple to use and good enough to perform basic operations for REST service.

 Java

client

to

send

a

“POST”

request

to

PAGA

getTransactionDetails

method

on

the

merchant

restful

API,

with

json

string

will

be

as

simple

as

below.

Code Block
languagejava
titleREST Client
package restfulclient.main;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
 
import java.security.MessageDigest;
public class RestClient {
 
	public static void main(String[] args) {
		 
		try {
			 
			URL url = new URL("http://www.mypaga.com/paga-webservices/merchant-rest/getTransactionDetails");
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
				conn.setRequestMethod("POST");
				conn.setDoOutput(true);
				
				conn.setRequestProperty("Content-Type", "application/json");
				conn.setRequestProperty("principal", "AA6EEB78-BD92-4D0B-A87D-E3DB46C53B70"); //business organization publicId
				conn.setRequestProperty("credentials", "password"); //business organization password
				StringBuilder sBuilder = new StringBuilder();
				sBuilder.append("09012939283"); //referenceNumber param value
				sBuilder.append("0123"); //business organization api-key
				
				conn.setRequestProperty("hash", RestClientTest.hashSHA512(sBuilder.toString(), 1000, true).toString());
				//input should be the data formatted as a JSON.
				String input = "{\"referenceNumber\":\"09012939283\"}"; 
		 
				OutputStream os = conn.getOutputStream();
				os.write(input.getBytes());
				os.close();
	 
			if (conn.getResponseCode() != 201 && conn.getResponseCode() != 200) {
				throw new RuntimeException("Failed : HTTP error code : "
					+ conn.getResponseCode());
			}
	 
			BufferedReader br = new BufferedReader(new InputStreamReader(
					(conn.getInputStream())));
	 
			String output;
			System.out.println("Output from Server .... \n");
			while ((output = br.readLine()) != null) {
				System.out.println(output);
			}
	 
			conn.disconnect();
	 
		  } catch (MalformedURLException e) {
	 
			e.printStackTrace();
	 
		  } catch (IOException e) {
	 
			e.printStackTrace();
	 
		 }
	}
	//hash sha-512 with some iterations
	public static Object hashSHA512(String message, int iterations, boolean returnHex) {
	
		try {
		
			MessageDigest mda = MessageDigest.getInstance("SHA-512");
		
			byte [] digest = mda.digest(message.getBytes());
		
			for(int i = 0; i < iterations - 1; i++) {
			
				digest = mda.digest(digest);
			}
	
			if(returnHex) {
				return new String(Hex.encodeHex(digest));
			} else {
				return digest;
			}
		
		} catch(Exception e) {
			return null;
		}
	}
}

Panel

On this page:

Table of Contents

2. REST client code sample using PHP

PHP client to send a “POST” request to PAGA buy Airtime API, with json string will be as below.

Code Block
languagephp
titlePHP REST Client
<?php
    $url = "http://www.mypaga.com/paga-webservices/merchant-rest/secured/getTransactionDetails";
	$postdata = "{\"referenceNumber\":\"0012939283\"}"; 
	//hash with sha-512 1000 times 
	//appended param values referenceNumber and merchant api key
       $hash = hash('sha512', "0012939283"."0123");
    	for ($i=1; $i<1000; $i++) {
       	$hash = hash('sha512', pack("H*", $hash));
    	}
       $opts = array(
        	"http" => array(
        	"method" => "POST",
        	"header" => "Content-Type: application/json\r\nprincipal: 757E1F82-C5C1-4883-B891-C888293F2F00\r\ncredentials: pa55w@rd \r\nhash:".$hash,
        	"content" => $postdata
    	)
    );
    $context = stream_context_create($opts);
    $response =  json_decode(file_get_contents($url, false, $context));
    echo $result;
?>


 

3. REST client code sample in .NET using C#

.NET client to send a “POST” request to PAGA buy Airtime API, with json string will be as simple as below.

Code Block
languagec#
titleC# REST Client
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.IO;
using System.Net; 
namespace RESTfulClient
{
    public class Program
    {
		public static void Main(string[] args)
        {
            // We use the HttpUtility class from the System.Web namespace   
            Uri address = new Uri("http://www.mypaga.com/paga-webservices/merchant-rest/registerCustomer");
            // Create the web request  
            HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
            // Set type to POST  
            request.Method = "POST";
            request.ContentType = "application/json";
            request.Headers.Add("principal", "757E1F82-C5C1-4883-B891-C888293F2F00");
            request.Headers.Add("credentials", "pa55w@rd");
            //Get sha512 hash of the appended param values referenceNumber and api key with 1000 iterations
            String hash = GetSha512("0012939283" + "0123", 1000);
            //add hash header params
            request.Headers.Add("hash", hash);
            // Create the data we want to send  
            String data = "{\"referenceNumber\":\"0012939283\"}"; 
            // Create a byte array of the data we want to send  
            byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());
            // Set the content length in the request headers  
            request.ContentLength = byteData.Length;
            // Write data  
            using (Stream postStream = request.GetRequestStream())
            {
                postStream.Write(byteData, 0, byteData.Length);
            }
            // Get response  
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                // Get the response stream  
                StreamReader reader = new StreamReader(response.GetResponseStream());
                // Console application output  
                Console.WriteLine(reader.ReadToEnd());
            }
        }
		//Get sha512 hash with certain iterations
        public static String GetSha512(string text, long iterations)
        {
            string hash = "";
            SHA512 alg = SHA512.Create();
            byte[] result = alg.ComputeHash(Encoding.UTF8.GetBytes(text));
            for (long i = 1; i < iterations - 1; i++)
            {
                result = alg.ComputeHash(result);
            }
            hash = BitConverter.ToString(result).Replace("-","");
            return hash;
        }
        
	}   
}  


 


Filter by label (Content by label)
showLabelsfalse
max5
spacesPagaMerchantServices
sortmodified
showSpacefalse
reversetrue
typepage
labelsmerchant-services featured

Page Properties
hiddentrue
Related issues