C# .NET communication with API

Post Affiliate Pro API is PHP based but you can access it from other programming languages too.

The only requirement is to implement HTTP POST request correctly as well as encode JSON request to our server correctly.

Here is an example of such a request using C# in .Net (simple console application):

//
//    EXAMPLE OF LOGIN REQUEST 
//

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a request using a URL that can receive a post. 
            WebRequest request = WebRequest.Create("https://getting-started.postaffiliatepro.com/scripts/server.php");
            // Set the Method property of the request to POST.
            request.Method = "POST";
            // Create POST data and convert it to a byte array.
            //WRITE JSON DATA TO VARIABLE D
            string postData = "D={\"requests\":[{\"C\":\"Pap_Api_AuthService\", \"M\":\"authenticate\", \"fields\":[[\"name\",\"value\"],[\"Id\",\"\"],[\"username\",\"user@example.com\"],[\"password\",\"ab9ce908\"],[\"rememberMe\",\"Y\"],[\"language\",\"en-US\"],[\"roleType\",\"M\"],[\"apiVersion\",\"\"]]}],\"C\":\"Gpf_Rpc_Server\", \"M\":\"run\"}";
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            // Set the ContentType property of the WebRequest.
            request.ContentType = "application/x-www-form-urlencoded";
            // Set the ContentLength property of the WebRequest.
            request.ContentLength = byteArray.Length;
            // Get the request stream.
            Stream dataStream = request.GetRequestStream();
            // Write the data to the request stream.
            dataStream.Write(byteArray, 0, byteArray.Length);
            // Close the Stream object.
            dataStream.Close();
            // Get the response.
            WebResponse response = request.GetResponse();
            // Display the status.
//            Console.WriteLine(((HttpWebResponse)response).StatusDescription);
            // Get the stream containing content returned by the server.
            dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd();
            // Display the content.
            Console.WriteLine(responseFromServer);
            // Clean up the streams.
            reader.Close();
            dataStream.Close();
            response.Close();


        }
    }
}
Description of fields in postData variable:
C = the main class we are accessing ("Pap_Api_AuthService" in this case)
M = the method of the class that we want to use ("authenticate" in this case)
fields = an array of name-value arrays that we are sending to the chosen method


Now you only have to correctly encode/decode JSON data from request.
JSON encoding/decoding in .NET can be done by multiple libraries which can serialize and unserialize data into/from JSON format.
An example of such a library is: Json.NET
To use this library in your project try the following:
1. download Json.Net library
2. Extract Newtonsoft.Json.dll and Newtonsoft.Json.xml from the archive's /bin directory into your own applications.
3. Add a reference to Newtonsoft.Json.dll within Visual Studio.NET to your project.

Now you can decode e.g. response from request we executed in last example:

JsonSerializer serializer = new JsonSerializer();
object result = JsonConvert.DeserializeObject(responseFromServer);

The best will be to create interfaces for each type of request and use unserialization directly to .Net objects - this is not a part of this short example.

 
How to get a proper request content?
 
Simply use our PHP API file. For example here is how you can get data from Pap_Api_PayoutsHistoryGrid table:
 
include '../api/PapApi.class.php';
 
$session = new Pap_Api_Session("path_to_your_server.php_file");
$session->setDebug(true); //this will produce output with request/response
if(!$session->login("merchant_name", "merchant_pass")) {
  die('Failed authentication');
}
 
$payoutHistoryrequest = new Pap_Api_PayoutsHistoryGrid($session);
 
$payoutHistoryrequest->sendNow();
 
$historyGrid = $payoutHistoryrequest->getGrid();
$recordset = $historyGrid->getRecordset();
 
//print list of payouts
foreach($recordset as $rec) {
    echo $rec->get('id') . ';' . $rec->get('amount') . ';' . $rec->get('accountid') . ';' . $rec->get('users') .';' . '</br>';
}
And you'll get an answer similar to this:
 
REQUEST: {"C":"Gpf_Rpc_Server","M":"run","requests":[{"C":"Pap_Merchants_Payout_PayoutsHistoryGrid","M":"getRows"}],"S":"ep6udpp8i2mgnh70vdp52on5h3"}
RESPONSE: [{"rows":[["id","payouthistoryid","dateinserted","merchantnote","affiliatenote","accountid","amount","users"],["0bc99b08","0bc99b08","2011-03-25 05:39:49","","","default1",99,"1 payee"]],"count":1}]

0bc99b08;99;default1;1 payee;
Notice rows start with REQUEST and RESPONSE.
REQUEST is what the request string should looks like.

JSON data model description:
×