In this blog post, we’ll walk through how to integrate the Tabscanner API into a C# application to process receipts
and retrieve structured data in JSON format. We’ll expand the program incrementally with explanations and code
snippets.
Step 1: Set Up the Project
First, create a new .NET console application:
- Open a terminal or IDE.
- Create a new project:
dotnet new console -n TabscannerIntegration cd TabscannerIntegration
- Add the
Newtonsoft.Json
package for handling JSON:dotnet add package Newtonsoft.Json
Step 2: Define API Configuration
Tabscanner’s API requires an API key and endpoints for uploading receipts and polling results. Add these as constants
in the program:
private static readonly string API_KEY = Environment.GetEnvironmentVariable("TABSCANNER_API_KEY");
private static readonly string PROCESS_ENDPOINT = "https://api.tabscanner.com/api/2/process";
private static readonly string RESULT_ENDPOINT_BASE = "https://api.tabscanner.com/api/result/";
Replace TABSCANNER_API_KEY
with your actual API key (or set it in the environment).
Step 3: Upload a Receipt
The first step is to upload a receipt image to the Tabscanner API. This function takes the image path, sends it as
multipart/form-data
, and retrieves a token to poll for results.
private static async Task<string> UploadReceiptAsync(string filePath)
{
using (var client = new HttpClient())
using (var fileContent = new MultipartFormDataContent())
{
var request = new HttpRequestMessage(HttpMethod.Post, PROCESS_ENDPOINT);
request.Headers.Add("apikey", API_KEY);
var fileStreamContent = new StreamContent(File.OpenRead(filePath));
fileStreamContent.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
fileContent.Add(fileStreamContent, "file", "receipt.jpg");
request.Content = fileContent;
var response = await client.SendAsync(request);
if (response.IsSuccessStatusCode)
{
var json = await response.Content.ReadAsStringAsync();
var token = JObject.Parse(json)["token"]?.ToString();
Console.WriteLine($"Token received: {token}");
return token;
}
else
{
Console.WriteLine($"Error uploading receipt: {response.StatusCode}, {response.ReasonPhrase}");
return null;
}
}
}
Step 4: Poll for Results
Once the receipt is uploaded, use the token to poll the Tabscanner API until the receipt processing is complete. Add
the following function to the program:
private static async Task<JObject> PollForResultAsync(string token)
{
var pollingUrl = $"{RESULT_ENDPOINT_BASE}{token}";
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("apikey", API_KEY);
while (true)
{
var response = await client.GetAsync(pollingUrl);
if (response.IsSuccessStatusCode)
{
var json = await response.Content.ReadAsStringAsync();
var resultData = JObject.Parse(json);
var status = resultData["status"]?.ToString();
if (status == "done")
{
Console.WriteLine("Processing complete!");
return resultData["result"] as JObject;
}
else if (status == "pending")
{
Console.WriteLine("Processing... retrying in 1 second.");
await Task.Delay(1000);
}
else
{
Console.WriteLine($"Unexpected status: {status}");
return null;
}
}
else
{
Console.WriteLine($"Error polling for result: {response.StatusCode}, {response.ReasonPhrase}");
return null;
}
}
}
}
Step 5: Integrate and Test
Combine the two functions into the Main
method. Provide the path to a sample receipt image and run the
program:
static async Task Main(string[] args)
{
string filePath = "sample_receipt.jpg";
Console.WriteLine("Uploading receipt...");
var token = await UploadReceiptAsync(filePath);
if (string.IsNullOrEmpty(token))
{
Console.WriteLine("Failed to start receipt processing.");
return;
}
Console.WriteLine("Polling for results...");
var result = await PollForResultAsync(token);
if (result != null)
{
Console.WriteLine("Receipt Data Retrieved:");
Console.WriteLine(result.ToString(Newtonsoft.Json.Formatting.Indented));
}
else
{
Console.WriteLine("Failed to retrieve receipt data.");
}
}
Step 6: Run the Program
- Place a receipt image (e.g.,
sample_receipt.jpg
) in the project directory. - Build and run the program:
dotnet run
- View the token, polling updates, and final receipt data.
Example Output
When the processing completes, the program will display structured receipt data in JSON format:
{
"establishment": "SuperMart",
"date": "2025-01-01 14:32:00",
"total": 45.67,
"subTotal": 41.23,
"tax": 4.44,
"lineItems": [
{"desc": "Apple", "qty": 3, "price": 1.5, "lineTotal": 4.5},
{"desc": "Milk", "qty": 1, "price": 2.5, "lineTotal": 2.5}
]
}
Conclusion
Tabscanner simplifies receipt data extraction with its powerful OCR API. This step-by-step guide shows how to:
- Upload a receipt.
- Poll for results.
- Retrieve structured JSON data.
With this integration, you can automate receipt processing and streamline workflows in your applications. 🚀
Happy coding!