You are viewing the documentation for Digipost API Client 7.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 of this package, make sure Include Prerelease is enabled. Please refer to documentation for your version of Visual Studio for detailed instructions.
  3. Select digipost-api-client and click Install.

Install and use business certificate

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 business certificate can be loaded directly from file or from the Windows certificate store. The latter is preferred, as this avoids password handling in the code itself.

Install business certificate to certificate store

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 or Local Machine and click Next. If you are running the client library from a system account, but debugging from a different user, please install it on Local Machine, as this enables loading it from any user.
  3. Use the suggested filename. Click Next
  4. Enter password for private key and select Mark this key as exportable … Click Next
  5. Choose 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 in code

  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. If the certificate was installed in Current User choose My User Account and if installed on Local Machine choose Computer Account. Then click Finish and then OK
  5. Expand Certificates node, select Personal and open Certificates
  6. Double-click on the installed certificate
  7. Go to the Details tab
  8. Scroll down to Thumbprint
  9. Copy the thumbprint and load as shown below
var config = new ClientConfig(senderId: "xxxxx", environment: Environment.Production);
var client = new DigipostClient(config, thumbprint: "84e492a972b7e...");

Load business certificate from file

If there is a reason for not loading the certificate from the Windows certificate store, you can use the constructor taking in a X509Certificate2:

var config = new ClientConfig(senderId: "xxxxx", environment: Environment.Production);
var businessCertificate =
new X509Certificate2(
    @"C:\Path\To\Certificate\Cert.p12",
    "secretPasswordProperlyInstalledAndLoaded",
    X509KeyStorageFlags.Exportable
);

var client = new DigipostClient(config, businessCertificate);

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)
const string senderId = "123456";
var config = new ClientConfig(senderId, Environment.Production);

Use cases

Send one letter to recipient via personal identification number

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

var message = new Message( 
    new RecipientById(IdentificationType.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("xxxxx", Environment.Production);
var client = new DigipostClient(config, thumbprint: "84e492a972b7e...");

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

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

//Compose message and send
var message = new Message(recipient, primaryDocument);
var result = client.SendMessage(message);

Send one letter with multiple attachments

var config = new ClientConfig("xxxxx", Environment.Production);
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 RecipientById(IdentificationType.PersonalIdentificationNumber, id: "241084xxxxx"), primaryDocument
    ) { Attachments = { attachment1, attachment2 } };

var result = client.SendMessage(message);

Send letter with SMS notification

var config = new ClientConfig("xxxxx", Environment.Production);
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 RecipientById(identificationType: IdentificationType.PersonalIdentificationNumber, id: "311084xxxx"), primaryDocument);

var result = client.SendMessage(message);

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("xxxxx", Environment.Production);
var client = new DigipostClient(config, thumbprint: "84e492a972b7e...");

var recipient = new RecipientByNameAndAddress(
    fullName: "Ola Nordmann",
    addressLine1: "Prinsensveien 123",
    postalCode: "0460",
    city: "Oslo");

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"))
        );

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

var messageWithFallbackToPrint = new Message(recipient, primaryDocument)
{
    PrintDetails = printDetails
};

var result = client.SendMessage(messageWithFallbackToPrint);

Send letter with higher security level

var config = new ClientConfig("xxxxx", Environment.Production);
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 RecipientById(identificationType: IdentificationType.PersonalIdentificationNumber, id: "311084xxxx"), primaryDocument);

var result = client.SendMessage(message);

Identify recipient

Attempts to identify the person submitted in the request and returns whether he or she has a Digipost account. The person can be identified by personal identification number (PIN), Digipost address, or name and address.

If the user is identified, the ResultType will be DigipostAddress or PersonAlias. In cases where we identify the person, the data parameter will contain the given identification value.

User is identified and have a Digipost account:

ResultType: DigipostAddress
Data: "Ola.Nordmann#3244B"
Error: Null

User is identified but does not have a Digipost account:

ResultType: PersonAlias
Data: "azdixsdfsdffsdfncixtvpwdp#6QE6"
Error: Null

The PersonAlias can be used for feature lookups, instead of the given identify criteria.

Note: If you identify a person by PIN, the Digipost address will not be returned, since it is preferred that you continue to use this as identificator when sending the message.

If the user is not identified, the ResultType will be InvalidReason or UnidentifiedReason. See the Error parameter for more detailed error message.

The user is not identified because the PIN is not valid:

ResultType: InvalidReason
Data: Null
Error: InvalidPersonalIdentificationNumber

The user is not identified because we did not have a match from the identify criteria:

ResultType: UnidentifiedReason
Data: Null
Error: NotFound

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

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

var identification = new Identification(new RecipientById(IdentificationType.PersonalIdentificationNumber, "211084xxxxx"));
var identificationResponse = client.Identify(identification);

if (identificationResponse.ResultType == IdentificationResultType.DigipostAddress)
{
    //Exist as user in Digipost. 
    //If you used personal identification number to identify- continue to use that in the next step. 
    //If not- see Data for DigipostAddress 
}
else if (identificationResponse.ResultType == IdentificationResultType.Personalias)
{
    //The person is identified but does not have an active Digipost account. 
    //You can continue to use this alias to check the status of the user in future calls.
}
else if (identificationResponse.ResultType == IdentificationResultType.InvalidReason ||
         identificationResponse.ResultType == IdentificationResultType.UnidentifiedReason)
{
    //The person is NOT identified. Check Error for more details.
}

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 that ClientConfig.Environment must be set to Environment.NorskHelsenett.

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

var message = new Message(
    new RecipientById(IdentificationType.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("xxxxx", Environment.Production);
var client = new DigipostClient(config, thumbprint: "84e492a972b7e...");

var message = new Message(
    new RecipientById(IdentificationType.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("xxxxx", Environment.Production);
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.

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

var digitalRecipient = new RecipientById(IdentificationType.PersonalIdentificationNumber, "311084xxxx");
var primaryDocument = new Document(subject: "Attachment", fileType: "txt", path: @"c:\...\document.txt");

var message = new Message(digitalRecipient, primaryDocument){ SenderId = "5555"};

var result = client.SendMessage(message); 

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("xxxxx", Environment.Production);
var client = new DigipostClient(config, thumbprint: "84e492a972b7e...");

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

var result = client.SendMessage(message);

Logging

Logging request flow

The client is using Common Logging API for .NET as an abstraction for logging. It is up to the user to implement the API with a logging framework.

Common Logging API is a lightweight infrastructure logging platform that allows developers to focus on the logging requirements instead of the logging tools and required configuration. The Common Logging API abstracts the logging requirements of any project making it easy to swap logging providers.

Enabling logging on level DEBUG will output results of requests, WARN only failed requests or worse. These loggers will be under the Digipost.Api.Client namespace.

Example with Log4Net

  1. Let’s assume that log4net [1.2.13] 2.0.3 is installed in project.
  2. Since log4net has version [1.2.13], Common.Logging.Log4Net1213 is the correct logging adapter. Install this package.
  3. In some cases the adapter may install or update Log4Net to a incorrect version. If installing the adapter for log4net 2.0.3, Common.Logging.Log4Net1213 must be the installed version.
  4. Following is a complete App.config with the Log4Net adapter containing a RollingFileAppender. Note the version of the adapter specified in the <factoryAdapter/> node:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <sectionGroup name="common">
      <section name="logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging" />
    </sectionGroup>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>

  <common>
    <logging>
      <factoryAdapter type="Common.Logging.Log4Net.Log4NetLoggerFactoryAdapter, Common.Logging.Log4net1213">
        <arg key="configType" value="INLINE" />
      </factoryAdapter>
    </logging>
  </common>

   <log4net>
    <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
      <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
      <file value="${AppData}\Digipost\Client\" />
      <appendToFile value="true" />
      <rollingStyle value="Date" />
      <staticLogFileName value="false" />
      <rollingStyle value="Composite" />
      <param name="maxSizeRollBackups" value="10" />
      <datePattern value="yyyy.MM.dd' digipost-api-client-dotnet.log'" />
      <maximumFileSize value="100MB" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
      </layout>
    </appender>
   <root>
      <appender-ref ref="RollingFileAppender"/>
    </root>
  </log4net>
</configuration>

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(message);	
}
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 = await api.SendMessageAsync(message);	
}
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.