C# Create Swiss QR-Bill API

74

C# Create Swiss QR-Bill API -

using System;
using System.Linq;
using System.Web;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Collections.Generic;
using Newtonsoft.Json;

static void Main(string[] args)
{
	//service and docs
    https://qr.livingtech.ch
	
    // Configuration
    Dictionary myRequestConfiguration = new Dictionary();
    myRequestConfiguration.Add("Account", "CH4431999123000889012");
    myRequestConfiguration.Add("CreditorName", "Muster AG");
    myRequestConfiguration.Add("CreditorAddress1", "Hauptstrasse 1");
    myRequestConfiguration.Add("CreditorAddress2", "8000 Zürich");
    myRequestConfiguration.Add("CreditorCountryCode", "CH");
    myRequestConfiguration.Add("DebtorName", "LivingTech GmbH");
    myRequestConfiguration.Add("DebtorAddress1", "Dörflistrasse 10");
    myRequestConfiguration.Add("DebtorAddress2", "8057 Zürich");
    myRequestConfiguration.Add("DebtorCountryCode", "CH");
    myRequestConfiguration.Add("Amount", "1.50");
    myRequestConfiguration.Add("ReferenceNr", "21000000000313947143000901");
    myRequestConfiguration.Add("UnstructuredMessage", "Mitteilung zur Rechnung");
    myRequestConfiguration.Add("Currency", "CHF");
    myRequestConfiguration.Add("IsQrOnly", "false");
    myRequestConfiguration.Add("Format", "PDF");
    myRequestConfiguration.Add("Language", "DE");

    // Call function to create invoice
    byte[] myByteResult = generateQrInvoice(myRequestConfiguration);

    // Work with binary data
    if(myByteResult != null)
    {
        // ...
    }
}

protected byte[] generateQrInvoice(Dictionary myRequestConfiguration)
{
    // Main configuration
    string myEndpointUrl = "http://qrbillservice.livingtech.ch";
    string myEndpointPath = "/api/qrinvoice/create/";
    string myApiKey = "mySecretApiKey";

    // GET parameters
    string myGetParams = $"?{string.Join("&", myRequestConfiguration.Select(myDict => $"{HttpUtility.UrlEncode(myDict.Key)}={HttpUtility.UrlEncode(myDict.Value)}"))}";

    // HttpClient
    HttpClient myHttpClient = new HttpClient();
    myHttpClient.BaseAddress = new Uri(myEndpointUrl);
    myHttpClient.DefaultRequestHeaders.Add("APIKEY", myApiKey);
    myHttpClient.DefaultRequestHeaders.Accept.Clear();
    myHttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    try
    {
        // Perform request
        HttpResponseMessage myResponse = myHttpClient.GetAsync(myEndpointPath + myGetParams).Result;

        // Check status
        if (myResponse.IsSuccessStatusCode)
        {
            // Read and parse JSON
            string myJsonBody = myResponse.Content.ReadAsStringAsync().Result;
            var myJsonObject = Newtonsoft.Json.Linq.JObject.Parse(myJsonBody);

            // Check if error
            if (myJsonObject["isSuccessed"].ToString().ToLower() == "true")
            {
                if (myJsonObject["base64Image"] != null && !String.IsNullOrEmpty(myJsonObject["base64Image"].ToString()))
                {
                    // Convert base64 string to byte array
                    byte[] myByteArray = Convert.FromBase64String(myJsonObject["base64Image"].ToString());

                    // E.g. save file
                    using (FileStream myFileStream = System.IO.File.Create(HttpContext.Current.Server.MapPath("~/App_Data/" + Guid.NewGuid().ToString() + ".pdf")))
                    {
                        myFileStream.Write(myByteArray, 0, myByteArray.Length);
                    }

                    // Return data
                    return myByteArray;
                }
                else
                {
                    throw new Exception("no data provided");
                }
            }
            else
            {
                throw new Exception(myJsonObject["Message"].ToString());
            }
        }
        else
        {
            throw new Exception("status code " + myResponse.StatusCode);
        }
    }
    catch (Exception ex)
    {
        // Handle exception
        Console.WriteLine("Error: " + ex.Message);
        return null;
    }
}

Comments

Submit
0 Comments