You are viewing the documentation for Digipost API Client 6.0, which is not the most recently released version. The newest version is 14.0 and can be browsed here.

Initial setup

The client library is available as a nuget package. The client library (and associated nuget package) is updated regularly as new functionality is added.

To install the nuget package, follow these steps in Visual Studio:

  1. Select TOOLS -> nuget Package Manager -> Manage nuget Packages Solution…
  2. Search for “digipost-api-client
    • If you would like pre-releases og this package, make sure it says Include Prerelease in the drop-down menu above the search results (where it by default says Stable Only).
  3. Select digipost-api-client and click Install.

Install business certificate in certificate store

SSL Certificates are small data files that digitally bind a cryptographic key to an organization's details. When installed on a web server, it activates the padlock and the https protocol (over port 443) and allows secure connections from a web server to a browser.

To communicate over HTTPS you need to sign your request with a business certificate. The following steps will install the certificate in the your certificate store. This should be done on the server where your application will run.

  1. Double-click on the actual certificate file (CertificateName.p12)
  2. Save the sertificate in Current User and click Next
  3. USe the suggested filename. Click Next
  4. Enter password for private key and select Mark this key as exportable … Click Next
  5. Select Automatically select the certificate store based on the type of certificate
  6. Click Next and Finish
  7. Accept the certificate if prompted.
  8. When prompted that the import was successful, click Ok.

Use business certificate thumbprint

  1. Start mmc.exe (Click windowsbutton and type mmc.exe)
  2. Choose File -> Add/Remove Snap-in…(Ctrl + M)
  3. Mark certificate and click Add >
  4. Choose ‘My user account’ followed by Finish, then ‘OK’.
  5. Double-click on ‘Certificates’
  6. Double-click on the installed certificate
  7. Go to the ‘Details’ tab
  8. Scroll down to ‘Thumbprint’
  9. Copy the thumbprint.

Client configuration

ClientConfig is a container for all the connection specific paramters that you can set. All attributes, except TechnicalSenderID, have default values. The technical sender id is a required parameter to contstruct the class.

// The sender id can be retrieved from your Digipost organisation account (https://www.digipost.no/bedrift)
private const string SenderId = "123456";
var config = new ClientConfig(SenderId);

Use cases

Send one letter to recipient via personal identification number

var config = new ClientConfig(senderId: "xxxxx");
var client = new DigipostClient(config, thumbprint: "84e492a972b7e...");

var message = new Message(
    new Recipient(IdentificationChoice.PersonalidentificationNumber, "311084xxxx"),
    new Document(subject: "Attachment", mimeType: "txt", path: @"c:\...\document.txt")
  );

var result = client.SendMessage(message); 

Send one letter to recipient via name and address

//Init Client
var config = new ClientConfig(senderId: "xxxxx");
var client = new DigipostClient(config, thumbprint: "84e492a972b7e...");

//Compose Recipient by name and address
var recipientByNameAndAddress = new RecipientByNameAndAddress(
    fullName: "Ola Nordmann",
    addressLine: "Prinsensveien 123",
    postalCode: "0460",
    city: "Oslo"
   );

//Compose message
var message = new Message(
    new Recipient(recipientByNameAndAddress),
    new Document(subject: "document subject", mimeType: "pdf", path: @"c:\...\document.pdf")
    );

var result = client.SendMessage(message);

Send one letter with multiple attachments

var config = new ClientConfig(senderId: "xxxxx");
var client = new DigipostClient(config, thumbprint: "84e492a972b7e...");

var primaryDocument = new Document(subject: "Primary document", mimeType: "pdf", path: @"c:\...\document.pdf");
var attachment1 = new Document(subject: "Attachment 1", mimeType: "txt", path: @"c:\...\attachment_01.txt");
var attachment2 = new Document(subject: "Attachment 2", mimeType: "pdf", path: @"c:\...\attachment_02.pdf");

var message = new Message(
    new Recipient(IdentificationChoice.PersonalidentificationNumber, id: "241084xxxxx"), primaryDocument
    ) { Attachments = { attachment1, attachment2 } };

var result = client.SendMessage(message);

Logging.Log(TraceEventType.Information, result.Status.ToString());

Send letter with SMS notification

var config = new ClientConfig(senderId: "xxxxx");
var client = new DigipostClient(config, thumbprint: "84e492a972b7e...");

var primaryDocument = new Document(subject: "Primary document", mimeType: "pdf", path: @"c:\...\document.pdf");

primaryDocument.SmsNotification = new SmsNotification(afterHours: 0); //SMS reminder after 0 hours
primaryDocument.SmsNotification.AddAtTime.Add(new Listedtime(new DateTime(2015, 05, 05, 12, 00, 00))); //new reminder at a specific date

var message = new Message(
    new Recipient(identificationChoice: IdentificationChoice.PersonalidentificationNumber, id: "311084xxxx"), primaryDocument);

var result = client.SendMessage(message);

Logging.Log(TraceEventType.Information, result.Status.ToString());

Send letter with fallback to print

In cases where the recipient is not a Digipost user, it is also possible to use the recipient’s name and address for physical mail delivery.

var config = new ClientConfig(senderId: "xxxxx");
var client = new DigipostClient(config, thumbprint: "84e492a972b7e...");

//recipientIdentifier for digital mail
var recipientByNameAndAddress = new RecipientByNameAndAddress(
    fullName: "Ola Nordmann",
    postalCode: "0460",
    city: "Oslo",
    addressLine: "Prinsensveien 123");

//printdetails for fallback to print (physical mail)
var printDetails =
    new PrintDetails(
        recipient: new PrintRecipient(
            "Ola Nordmann",
            new NorwegianAddress("0460", "Oslo", "Prinsensveien 123")),
        printReturnAddress: new PrintReturnAddress(
            "Kari Nordmann",
            new NorwegianAddress("0400", "Oslo", "Akers Àle 2"))
        );

//recipient
var digitalRecipientWithFallbackPrint = new Recipient(recipientByNameAndAddress, printDetails);

var message = new Message(
    new Recipient(recipientByNameAndAddress, printDetails),
    new Document(subject: "document subject", mimeType: "pdf", path: @"c:\...\document.pdf")
   );

var result = client.SendMessage(message);

Send letter with higher security level

var config = new ClientConfig(senderId: "xxxxx");
var client = new DigipostClient(config, thumbprint: "84e492a972b7e...");

var primaryDocument = new Document(subject: "Primary document", mimeType: "pdf", path: @"c:\...\document.pdf");

primaryDocument.AuthenticationLevel = AuthenticationLevel.TwoFactor; // Require BankID or BuyPass to open letter
primaryDocument.SensitivityLevel = SensitivityLevel.Sensitive; // Sender information and subject will be hidden until Digipost user is logged in at the appropriate authentication level

var message = new Message(
    new Recipient(identificationChoice: IdentificationChoice.PersonalidentificationNumber, id: "311084xxxx"), primaryDocument);

var result = client.SendMessage(message);

Identify user by personal identification number

var config = new ClientConfig(senderId: "xxxxx");
var client = new DigipostClient(config, thumbprint: "84e492a972b7e...");

var identification = new Identification(IdentificationChoice.PersonalidentificationNumber, "211084xxxx");
var identificationResponse = client.Identify(identification); 

Send letter through Norsk Helsenett

The Digipost API is accessible from both internet and Norsk Helsenett (NHN). Both entry points use the same API, the only difference is the base URL.

var config = new ClientConfig(senderId: "xxxxx");
var client = new DigipostClient(config, thumbprint: "84e492a972b7e...");

// API URL is different when request is sent from NHN
config.ApiUrl = new Uri("https://api.nhn.digipost.no");

var message = new Message(
    new Recipient(IdentificationChoice.PersonalidentificationNumber, "311084xxxx"),
    new Document(subject: "Attachment", mimeType: "txt", path: @"c:\...\document.txt")
  );

var result = client.SendMessage(message); 

Handling responses

The client library will return the most important status codes and the raw xml response.

  • StatusMessage is the status of the messages.
  • DeliveryTime is the time the digital mail was delivered. This will be set with 01/01/0001 00:00:00) if the message had errors.
  • DelimeryMethod is the channel through which the message was delivered. This is either DIGIPOST for digital mail or PRINT for physical mail.
  • ErrorCode is populated if relevant.
  • ErrorType is the type of error.
  • ResponseMessage is the the raw XML of the respnse.

Example of a response where the recipient is not a Digipost user:

StatusMessage[The recipient does not have a Digipost account.]
Deliverytime[01/01/0001 00:00:00]
DeliveryMethod[]
ErrorCode[UNKNOWN_RECIPIENT]
ErrorType[CLIENT_DATA]
ResponseMessage[<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<error xmlns="http://api.digipost.no/schema/v6">
	<error-code>UNKNOWN_RECIPIENT</error-code>
	<error-message>The recipient does not have a Digipost account.</error-message>
	<error-type>CLIENT_DATA</error-type>
</error>]]

Response objects

The client library returns appropiate response objects for relevant methods.

Identify response

IdentificationResult.cs is populated by three properties:

  • IdentificationResultCode , wich describes if the recipient is either identified, unidentified, invalid or an digipost-customer.
  • IdentificationType is in wich type Digipost will return the identification.
  • IdentificationValue is the value of the IdentificationType.

An example of response could be:

IdentificationResultCode = Digipost
IdentificationType = Digipostaddress
IdentificationValue = johnny.test#1234

Example of a response where the letter has been delivered as digital mail:

StatusMessage[Delivered]
DeliveryTime[30/04/2015 14:54:07]
DeliveryMethod[DIGIPOST]
ErrorCode[]
ErrorType[]
ResponseMessage[<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<message-delivery xmlns="http://api.digipost.no/schema/v6">
	<delivery-method>DIGIPOST</delivery-method>
	<status>DELIVERED</status>
	<delivery-time>2015-04-30T14:54:07.788+02:00</delivery-time>
	<primary-document>
		<uuid>424882ee-4db8-4585-b701-69e6da10c956</uuid>
		<subject>Primary document</subject>
		<file-type>txt</file-type>
		<authentication-level>PASSWORD</authentication-level>
		<sensitivity-level>NORMAL</sensitivity-level>
		<content-hash hash-algorithm="SHA256">XXX=</content-hash>
	</primary-document>
	<attachment>
		<uuid>a3069d0c-fc1d-4966-b17d-9395d410c126</uuid>
		<subject>Attachment</subject>
		<file-type>txt</file-type>
		<authentication-level>PASSWORD</authentication-level>
		<sensitivity-level>NORMAL</sensitivity-level>
		<content-hash hash-algorithm="SHA256">XXXX</content-hash>
	</attachment>
</message-delivery>]]

Send message response

MessageDeliveryResult.cs is populated by six properties:

  • Deliverymethod is either digital or physical, where Print is physical and Digipost is digital.
  • Status is the status of the message in the delivery prosess. See MessageStatus.cs for more information.
  • Deliverytime is the time the message was delivered to the recipient.
  • Primarydocument is a copy of the document that was sent in, except for the actual byte content.
  • Attachment is an list of the attachments that was sent inn, except for the actual byte content.
  • Link is possible links/actions from here. In idempotent methods, this will return blank.

An example of response could be:

 	
Deliverymethod = Digipost
Status = Delivered
Deliverytime = 18/05/2015 16:50:06
Primarydocument = 
	Guid = b3928de2-0555-46be-9a75-837b3290c152
	Subject = Primary document
	FileMimeType = txt
	SmsNotification =  
	AuthenticationLevel = Password
	SensitivityLevel = Normal
	TechnicalType = 
Attachment = 
	Guid = 670c162c-e1d0-4ee6-98db-917e53fc0a2a
	Subject = Attachment
	FileMimeType = txt
	SmsNotification =  
	AuthenticationLevel = Password
	SensitivityLevel = Normal
	TechnicalType = 

Logging

The need for application logging varies from project to project. The client library exposes the ability to set a separate log function on the ClientConfig object. ClientConfig.Logger can be set to a Action<TraceEventType, Guid?, String, String>, where TraceEventType is the type of log message is and Guid is Id of the message. The penultimate parameter is the method in which was logged, and the final parameter is the actual message.

Following is an example:

var clientConfig = new ClientConfig()
{
    Logger = (severity, traceID, metode, message) =>
    {
        System.Diagnostics.Debug.WriteLine("{0} - {1} [{2}]", 
        	DateTime.Now, 
        	message, 
        	traceID.GetValueOrDefault()
        );
    }
};

The following will log all messages sent an received.

clientConfig.DebugToFile = true;
clientConfig.StandardLogPath = @"\LoggPath";

Error Handling

Synchronous error handling

If you are communicating synchronously, the errors will be wrapped in an AggregateException. This is because a set of errors may have occured before the result is received. You can handle each exception within the aggregate by sending in an anonymous function to AggregateException.Handle():

try
{
	var messageDeliveryResult = api.SendMessage();	
}
catch (AggregateException ae)
{
	ae.Handle((x) =>
	 {
         if (x is ClientResponseException)
         {
             Console.WriteLine("A client response exception occured!");
             return true;
         }
         return false;
     });
}

Asynchronous error handling

If you are using methods in the client library that has async in the name, it means that you are communicating asynchronously. To correctly identify errors that might happen, for example during sending a message, you can catch errors like you normally would in an application:

try
{
	var messageDeliveryResult = api.SendMessage();	
}
catch(ClientResponseException e)
{
	Console.WriteLine("A client response exception occured!");
}

Asynchronous communication with Digipost using the client library involves using methods with async in method name, like IdentifyAsync.