You are viewing the documentation for Digipost API Client 6.1, 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(IdentificationChoiceType.PersonalidentificationNumber, "311084xxxx"),
    new Document(subject: "Attachment", fileType: "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", fileType: "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", fileType: "pdf", path: @"c:\...\document.pdf");
var attachment1 = new Document(subject: "Attachment 1", fileType: "txt", path: @"c:\...\attachment_01.txt");
var attachment2 = new Document(subject: "Attachment 2", fileType: "pdf", path: @"c:\...\attachment_02.pdf");

var message = new Message(
    new Recipient(IdentificationChoiceType.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", fileType: "pdf", path: @"c:\...\document.pdf");

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

var message = new Message(
    new Recipient(identificationChoiceType: IdentificationChoiceType.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(printRecipient: new PrintRecipient(
             "Ola Nordmann",
             new NorwegianAddress("0460", "Oslo", "Prinsensveien 123")), 
             printReturnRecipient: new PrintReturnRecipient(
             "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", fileType: "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", fileType: "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(identificationChoiceType: IdentificationChoiceType.PersonalidentificationNumber, id: "311084xxxx"), primaryDocument);

var result = client.SendMessage(message);

Identify recipient

Identify recipient attempts to identify the person submitted in the request and return information regarding whether or not the person is a Digipost user. The person can be identified by personal identification number (fødelsnummer), Digipost address, or name and address. If personal identification number is used then true/false will be returned regarding whether or not the person is a Digipost user. If other identification choices are used the actual Digipost adresse will be returned.

Following is a example that uses personal identification number as identification choice.

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

var identification = new Identification(IdentificationChoiceType.PersonalidentificationNumber, "211084xxxxx");
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(IdentificationChoiceType.PersonalidentificationNumber, "311084xxxx"),
    new Document(subject: "Attachment", fileType: "txt", path: @"c:\...\document.txt")
  );

var result = client.SendMessage(message); 

Send invoice

It is possible to send invoice-metadata with a document. Documents with invoice-metadata enables the Send to Online Bank feature, which allows people to pay the invoice directly in Digipost.

var config = new ClientConfig(senderId: "xxxxx");
var client = new DigipostClient(config, thumbprint: "84e492a972b7e...");
            
var message = new Message(
    new Recipient(IdentificationChoiceType.PersonalidentificationNumber, "211084xxxx"),
    new Invoice(
        subject: "Invoice 1", 
        fileType: "pdf", 
        path: @"c:\...\invoice.pdf", 
        amount: new decimal(100.21),    
        account: "2593143xxxx", 
        duedate: DateTime.Parse("01.01.2016"), 
        kid: "123123123")
    );
            
var result = client.SendMessage(message); 

Search for receivers

A central part of a user interface in the application that is integrating with Digipost is the possiblity to search for receivers. This is available via the search endpoint. A person can be found by simply searching by first name and last name, e.g. Ola Nordmann, or specified further by street address, postal code, city and organization name.

It is important to note that the search results returned do not necessarily include the receiver to which you actually wish to send. The search results returned are strictly based on the search query you have sent in. This equally applies when only one search result is returned. This means that the actual person to which you wish to send must be confirmed by a human being before the actual document i sent (typically in the senders application). If the goal is to create a 100% automated workflow then the identify recipient endpoint should be used (see Identify recipient use case).

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

 var response = client.Search("Ola Nordmann Bellsund Longyearbyen");

 foreach (var person in response.PersonDetails)
 {
     var digipostAddress = person.DigipostAddress;
     var phoneNumber = person.MobileNumber;
 }

Send on behalf of organization

In the following use case, sender is defined as the party who is responsible for the actual content of the letter. Broker is defined as the party who is responsible for the technical transaction, which in this context means creating the request and being the party that is authenticated.

example

Sending on behalf of an organization is accomplished by setting Message.SenderId to the id of the sender when constructing a message. The actual letter will appear in the receivers Digipost mailbox with the senders details (logo, name, etc.).

Remember to use the business certificate of the broker to sign the message, not the one belonging to the sender. Also, the proper permissions need to be set by Digipost to send on behalf of an organization.

Let us illustrate this with an example. Let BrokerCompany be an organization with id 112233, and thumbprint of their certificate 84e492a972b7e…. They want to send on behalf of SenderCompany with organization id 5555.

var config = new ClientConfig(senderId: "xxxxx");
var client = new DigipostClient(config, thumbprint: "84e492a972b7e...");
var digitalRecipient = new Recipient(IdentificationChoiceType.PersonalidentificationNumber, "311084xxxx");
var primaryDocument = new Document(subject: "Attachment", fileType: "txt", path: @"c:\...\document.txt");

var message = new Message(recipient: digitalRecipient, primaryDocument: primaryDocument, senderId: "5555");

Send message with delivery time

A message can be sent with a delivery time. This means that a message can be sent at 11 AM, and be delivered to the recipient’s Digipost inbox at 3 PM the next day. Message.DeliveryTime is used for this purpose and is of type DateTime. This gives you a lot of flexibility on how to set the delivery time.

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

var message = new Message(
    new Recipient(IdentificationChoiceType.PersonalidentificationNumber, "311084xxxx"),
    new Document(subject: "Attachment", fileType: "txt", path: @"c:\...\document.txt")
    ) {DeliveryTime = DateTime.Now.AddDays(1).AddHours(4)};

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 you receive 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.