Developing Web Solutions on Windows

This document describes how to use the MintChip API to incorporate MintChip payments into the Web solutions built on Microsoft Windows platform. It covers both the server and the client side development. The MintChip .NET API permits MintChip to be used in all kinds of applications on Windows; including desktop Windows applications, WCF services etc. This document is focused on Web applications that include an ASP.NET server solution and a Web browser HTML / JavaScript based thin client. The .NET and JavaScript MintChip APIs are well suited to be used in modern AJAX enabled Web applications

Sample Code

A sample ASP.NET application that illustrates usage of the MintChip API in Web development can be downloaded from the MintChip developer Web site.

This application has been developed using the ASP.NET MVC 3. In order to work with it in Visual Studio, the ASP.NET MVC 3 Tools for Visual Studio 2010 must be installed.

MintChip .NET API

The MintChip .NET API provide a full set of functionality for interacting with the MintChip and handling the MintChip messages. The .NET developers do not need to know the internal structures of the MintChip messages, their serialisation mechanism or the cryptographic mechanism built into the MintChip and its messages. The Web developers should just use the MintChip .NET and the JavaScript APIs to enable the MintChip payments in their applications.

On the Windows platform, the MintChip APIs are implemented in a set of the following DLLs:

  • Mint.MintChip.Api.dll
  • Mint.MintChip.Contract.dll
  • Mint.MintChip.Core.dll
  • GTSDUpi.dll

This implementation is intended to be used by the .NET code running on Microsoft .NET Framework 2.0 or higher. The API technical details can be found in the reference documentation for the MintChip .NET API. Even though the reference documentation uses C#, the API can be consumed by any .NET compliant language.

MintChip on the Client

Before we start looking into how the MintChip technology works on the Web server we should have a good understanding of how to interact with the Web user's MintChip on the client. A physical MintChip must be present in the client's machine in order to participate in the MintChip payment transactions on the Web. Currently, MintChip is housed in a microSD card that the user can plug into their computer either by using a USB adapter or a SD adapter.

As it was mentioned before, the MintChip .NET API allows building different types of Windows applications that can participate in the MintChip payment transactions. The purpose of this document is to demonstrate how to build the browser based HTML/JavaScript clients. A cross browser MintChip plug-in has been developed for this purpose. This plug-in provides JavaScript version of the MintChip API that works equally well with all major Web browsers on the Windows platform. The plug-in has been tested with the IE 9, Firefox 9 and Chrome 16. The API technical details can be found in the reference documentation for the MintChip JavaScript API. The MintChip browser plug-in is distributed as an MSI package - MintChipPlugin.msi. The MSI package installs the plug-in and all the required DLLs for the MintChip API. The installation does not require the user to have administrative privileges. The plug-in gets installed in the following location on the user's machine:

Users\[user profile name]\AppData\Roaming\RoyalCanadianMint\MintChipPlugin\[plugin's version]

Besides the required DLLs, this folder contains the MintChipControl.htm file, which can be used to test the plug-in's installation. This file is also a good example of the MintChip JavaScript API usage.

Accessing the MintChip Browser Plug-in

In order to use the MintChip JavaScript API the MintChip browser plug-in should be referenced in the HTML code like the following:





    

The event handler which is called when the plug-in is ready to be used is specified in the "onload" parameter as shown in the code above. The function implementing the onload event handler (pluginLoaded in the example) should be placed in the <> section of the HTML document. Once the plug-in is loaded it can be accessed like the following:

document.getElementById("mintChipApiPlugin");

The onload event handler is a good place to get hold of the main objects required to start calling the MintChip API. For example,

var mintChip;
var messageFactory;

function mintChipApi() {
    return document.getElementById("mintChipApiPlugin");
}
   
function pluginLoaded() {
    try {
        var mintChipFactory = mintChipApi().mintChipFactory;
        mintChip = mintChipFactory.createMintChip();
        messageFactory = mintChipApi().messageFactory;
    }
    catch (err) {
        // Handle the error ...
    }
}

If the onload event handler gets invoked, it indicates that the MintChip browser plug-in is present on the user's machine and it is functional. If the onload event handler is never called, it either means that the plug-in is missing or the plug-in does not work with the user's Web browser. In this case, the user should be notified that they cannot participate in the MintChip payment transactions.

Accessing the MintChip API Factories

The two main JavaScript objects provided by the MintChip browser plug-in are the MessageFactory and the MintChipFactory:

    var mintChipFactory = mintChipApi().mintChipFactory;
    var messageFactory = mintChipApi().messageFactory;

The MintChipFactory's sole responsibility is to create an instance of the MintChip:

var mintChip = mintChipFactory.createMintChip();

If the call to MintChipFactory.createMintChip() is successful, the returned MintChip object can be used to interact with the physical MintChip installed on the user's machine. If the call fails, the JavaScript exception is thrown, which indicates that either the MintChip is not present on the user's machine or it is not functional. In this case the user should be notified that they cannot participate in the MintChip payment transactions. Since accessing the physical MintChip is an expensive operation, it is recommended to create the MintChip object once on the plug-in load and then use it everywhere in the JavaScript code on the page as needed.

The MessageFactory object is used to instantiate the MintChip message objects from their base64 representations. Also, the MessageFactory is used to create the ValueRequestMessage object used to initiate the MintChip payment.

Handling Value Request Messages

In a Web purchase scenario, the value request message is most likely issued by the Web server to the client. For example, when the Web user clicks on a button or a link to pay for a product the JavaScript code can make an AJAX call to the server to obtain the value request message, which would include all the details of the requested payment. This prompts the Web server to return a base64 encoded value request message with the MIME type set to application/vnd.scg.ecn-request. On receiving a response to such AJAX call the JavaScript code would check the MIME type of the response and if it is correct use the MessageFactory to instantiate the value request message from the received base64 string. The following example uses jQuery to make an AJAX call:

var xhr = $.get(url, function (data) {
    try {
        var mimeType = xhr.getResponseHeader('content-type');
        if (mimeType.toLowerCase().indexOf(
                    "application/vnd.scg.ecn-request") == 0) {
            var request = messageFactory.toMessage(data);
            // Use the request object ...
        }
        else {
            // Handle a wrong MIME type ...
        }
    }
    catch (err) {
        // Handle the error ...
    }
});

Once the ValueRequestMessage object is instantiated by the MessageFactory on the client, its properties can be examined. For example, the following code demonstrates how to display a value request message to the client for confirmation:

confirm("Value Request Message: \n" +
        "\n Amount: " + request.amount +
        "\n Annotation: " + request.annotation +
        "\n Challenge: " + request.challenge +
        "\n Currency Code: " + request.currencyCode +
        "\n Payee Id: " + request.payeeId);

Eventually, the value request message is submitted to the physical MintChip to create a payment in form of the value message. For example,

    try {
        var valueMessage = mintChip.createValueMessage(request);
    }
    catch (err) {
        // Handle the error ...
    }

Once the value message is created by the MintChip it can be submitted to the server as a payment. The submission can be performed by any required method - an AJAX post, a form post etc. In order to send the value message over the HTTP it should be serialised to its base64 representation:

var valueMessage = request.toBase64String();

If a payment request needs to be created on the client, the following is an example of the MessageFactory.createValueRequestMessage() call that does that:

    var payeeId = "5310000000000053";
    var amount = 10;/*cents*/
    
    var request = messageFactory.createValueRequestMessage(
            payeeId, amount, mintChipApi().currencyCode.CAD);
            
    request.challenge = Math.round(Math.random() * (Math.pow(2, 31)-1));
    request.annotation = "Request for payment";
    request.responseAddress = "www.mint.ca";    

Please note that setting the challenge, annotation and responseAddress properties is optional.

In order to send the value request message over the HTTP it should be serialised to its base64 representation:

var str = request.toBase64String();

Handling Value Messages

When the client's MintChip is acting as a payment recipient (a payee), it will most likely receive the value message in its base64 representation. When the value message is sent over the HTTP it is associated with the application/vnd.scg.ecn-message MIME type. The following code uses jQuery to make an AJAX call to receive a payment (the value message) from the server:

var xhr = $.get(url, function (data) {
    try {
        var mimeType = xhr.getResponseHeader('content-type');
        if (mimeType.toLowerCase().indexOf(
                    " application/vnd.scg.ecn-message ") == 0) {
        var valueMessage = messageFactory.toMessage(data);
        // Use the value message ...
        }
        else {
            // Handle a wrong MIME type ...
        }
    }
    catch (err) {
        // Handle the error ...
    }
});

Once the ValueMessage object is instantiated by the MessageFactory its properties can be examined. For example, the following code demonstrates how to display a value message to the user for confirmation:

confirm("Value Message:\n" +
        "\n Amount: " + valueMessage.amount +
        "\n Annotation: " + valueMessage.annotation +
        "\n Challenge: " + valueMessage.challenge +
        "\n Currency Code: " + valueMessage.currencyCode +
        "\n Payee Id: " + valueMessage.payeeId +
        "\n Payer Id: " + valueMessage.payerId +
        "\n Version: " + valueMessage.mintChipVersion +
        "\n Created: " +
               (new Date(valueMessage.createdTime)).toString("yyyy-MM-dd"));

Eventually, the value message is submitted to the physical MintChip to be loaded on the chip. For example,

    try {
        mintChip.loadValueMessage(valueMessage);
    }
    catch (err) {
        // Handle the error ...
    }

Using MintChip jQuery Plug-ins

Using the jQuery JavaScript library can simplify usage of the MintChip JavaScript API. The sample ASP.NET application includes two jQuery plug-ins - the MintChip Pay Button and the MintChip Control.

The MintChip Pay Button is a UI control that makes it very simple for the Web developers to integrate with the MintChip JavaScript API in order to enable payments by the local MintChip.

A developer would need to follow a few simple steps.

1. Reference the jQuery and jQuery UI libraries:

 


2. Reference the MintChip Pay Button jQuery plug-in and the MintChip API JavaScript utility:



3. Embed the MintChip Plug-in object in the HTML page:


    

4. Provide links (HTML anchor tags <a>) that include references to the URLs that can return the Value Request messages from the server. For example:

Rose at $0.08

5. Attach the MintChip Pay Button behaviour to the Value Request links:


This is pretty much it. When the user clicks on the link, the MintChip Pay Button pops up a confirmation dialog. After the user confirms the payment, the MintChip Pay Button posts a Value Message to the URL supplied by the Value Request message. Behaviour of the MintChip Pay Button can be tweaked to use AJAX instead of the form post when submitting the Value Message. For example:

$(".mintChip-pay-button").mintChipPayButton({
    submitPayment: "ajax",
    paymentSuccess: function (data, status, xhr) {
        if (confirm("Payment has been processed. You may now download the image.")) {
            document.location = data;
        }
    }
});

The MintChip Control jQuery plugin allows showing the local MintChip information and the transaction log records in a Web page. Its usage is similar to the MintChip Pay Button. Developers would follow the same first 3 steps as described above, and then use code similar to the following to include the MintChip Control in their Web pages:

MintChip on the Server

It is important to realize that Web applications developed and run on the ASP.NET can participate in the MintChip payment transactions regardless of the client platform. The client accessing the MintChip enabled Web site can run on any of the platforms that have the MintChip support. At the moment, these are the Microsoft desktop Windows with .NET Framework 2.0 or higher, the Android smart phones and the BlackBerry smart phones. The number of the supported client platforms will grow in the future, though it should not have a profound effect on the server code. The reason for that lies in the simplicity of the MintChip message exchange. The MintChip messages when they go on the wire are just base64 encoded strings of a relatively small size (no more than 2K), which makes them very well suited for all kinds of Internet based communications. When they are sent over the HTTP protocol, the following MIME types are used to help recognize the MintChip messages:

  • application/vnd.scg.ecn-messagefor the value messages
  • application/vnd.scg.ecn-requestfor the value request messages

For an ASP.NET application, be it a Web Forms or a MVC one, it should be very straightforward to accept base64 encoded strings from the client and send them back. The ability to translate between these base64 encoded strings and the data used to communicated with a MintChip is provided by the MintChip .NET API.

When incorporating the MintChip payments into the server side of a Web solution the .NET developers need the following set of DLLs:

  • Mint.MintChip.Api.dll
  • Mint.MintChip.Contract.dll
  • Mint.MintChip.Core.dll
  • GTSDUpi.dll

The first three DLLs are .NET assemblies that should be referenced by a .NET project. The last one, GTSDUpi.dll, is a native Windows DLL that the Mint.MintChip.Api.dll assembly depends on. This means that the GTSDUpi.dll should be deployed to the Web project's bin folder to be available at runtime.

It should be noted that a Web solution participating in the MintChip payment transactions may or may not have access to a MintChip on the server. If the server has no access to a MintChip, the functionality will be limited to only receiving the value messages (payments) and issuing the value request messages. The server will not be able to act as a payer, an issuer of the value messages. We will cover these two use cases in the following sections.

Issuing Value Request Messages

Regardless whether the Web server has access to a MintChip or not the .NET server code can use the MintChip .NET API to issue the value request messages. In a typical Web purchase scenario, the client may ask the server to issue the value request message to initiate a payment for the purchase. The following is an example of how the MintChip .NET API can be used in an ASP.NET MVC controller to perform this operation:

    string merchantId = "5310000000000046";
    int amount = 100; //cents
    IValueRequestMessage request = MessageFactory.Instance.
        CreateValueRequestMessage(merchantId, amount, CurrencyCode.CAD);
        
    request.Annotation = "Payment for a Web purchase";
    request.Challenge = DateTime.Now.GetHashCode();
    request.ResponseAddress = string.Format(
        "http://www.mysite.com/Store/SubmitPayment?receiptId={0}",
        Guid.NewGuid().ToString());
        
    return new ContentResult()
        {
            Content = request.ToBase64String(),
            ContentType = "application/vnd.scg.ecn-request"
        };

Please note that the value request message created in the example above has the ResponseAddress set to a URL that the client can use to submit a payment (the value message) created in response to this request. The URL can be of any form that the server accepting the payment can handle.

Accepting Value Messages

Accepting the value messages posted to the server involves the following steps:

  1. Reading the posted data as a string.
  2. Using MessageFactory to translate the base64 encoded string into the IValueMessage object.
  3. Verifying that the value message contains correct amount.
  4. Verifying that the payer's certificate was issued by a MintChip Root Certificate Authority.
  5. Verifying that the value message is issued to the correct recipient's MintChip.
  6. Verifying that the value message is not a duplicate and has not been processed before.

Depending on the availability of a MintChip on the Web server these steps may be performed in different ways. However, the first three steps are the same regardless regardless whether a MintChip can be accessed from the Web server or not.

Typically the client submits the value message to the server using the URL provided in the value request message as a HTTP POST operation. Depending on the client this POST may happen as an AJAX call or as a HTML Form post. It is a good practice to ensure that the server can handle either scenario. In the end, the server just should be able to read the posted value message as a string. The server may check the MIME type of the posted data to be sure this is the value message (application/vnd.scg.ecn-message MIME type), but that is not required. The following example demonstrates how to read the value message posted to an ASP.NET Web site:

HttpRequest httpRequest = HttpContext.Current.Request;
if (httpRequest.InputStream != null)
{
    string valueString;
    if (!this.Request.IsAjaxRequest() && this.Request.Form.Count > 0)
    {
        valueString = httpRequest.Form[0];
    }
    else
    {
        using (var reader = new StreamReader(httpRequest.InputStream))
        {
            valueString = reader.ReadToEnd();
        }
    }

    IMessage message = null;
    try
    {
        message = MessageFactory.Instance.ToMessage(valueString);
    }
    catch (IOException)
    {
        // Handle invalid posted data
    }

    IValueMessage valueMessage = null;
    if (message is IValueMessage)
    {
        valueMessage = message as IValueMessage;
    }
    else
    {
    // Handle a wrong message type
    }
}

The code above just reads the value message from the HttpRequest object and uses the MessageFactory to instantiate the value message object assuming the posted data is a base64 encoded string representing the value message. Proper error checking must be done to ensure that this assumption is correct. Once the value message object (IValueMessage) has been instantiated it can either be loaded onto a MintChip immediately or verified and stored to a database for future processing.

It is important to understand that the MessageFactory.ToMessage() method does all the heavy lifting to translate a base64 encoded string into a valid value message object. When this method call successfully returns, we can be sure that the value message is authentic. The method performs message integrity verification using the digital signature and the payer's public key certificate embedded into the message. If either the base64 string decoding, or string parsing or signature verification fail the IOException is thrown. The MessageFactory.ToMessage() does not verify validity of the payer's certificate. This is demonstrated in the sections below.

To ensure that the value message received contains the expected monetary value, the IValueMessage.Amount property should be compared against the amount of the purchase the value message has been submitted for. This correlation can be achieved by including a purchase order number or a receipt Id into the URL provided to the IValueRequestMessage.ResponseAddress (see code example in the section on Issuing Value Request Messages), which the client would include with the posted value message. The query string parameters in the HTTP post can be used for this purpose when posting the value message to the server.

Accepting Value Messages with a Physical MintChip

When the server has a physical MintChip installed, the MintChip .NET API can be used to communicate with the MintChip and to load the value message:

    IMintChip mintChip = null;
    try
    {
        mintChip = MintChipFactory.Instance.CreateMintChip();
    }
    catch (MintChipException)
    {
        // MintChip is not installed.
        // Handle the value message without the MintChip.
    }

    try
    {
        mintChip.LoadValueMessage(valueMessage);
    }
    catch (MintChipException)
    {
        // The value message cannot be processed.
        // The MintChipException contains the error details.
    }

When the IMintChip.LoadValueMessage() method call successfully returns, the value message has been accepted by the MintChip and its balance has been incremented by the amount of the value message. While processing the value message the MintChip performs full verification of the value message to ensure that:

  • The digital signature of the message is valid.
  • The payer's certificate is valid.
  • The value message is issued to the correct recipient's MintChip.
  • The value message is not a duplicate and has not been processed before.

Accepting Value Messages without a Physical MintChip

When an ASP.NET Web application is running on a server that has no physical MintChip installed, it still can accept payments submitted in form of the value messages.

The process of reading the posted base64 string and translating it into the IValueMessage object is identical to the one described previously. The difference is in how the IValueMessage object is handled after it is created by the MessageFactory.ToMessage() method.

The goal is to ensure that the submitted value message is a valid one and then store it for later processing. One of the possible scenarios would be to store the value messages in a database and then later sent them to another server that can load the value messages onto a physical MintChip. Alternatively the value messages might be submitted to a MintChip Broker or other Remote MintChip server for their realization.

Regardless, if we can establish that the submitted value message is a valid and an authentic one we can practically ensure validity of the received payment.

As it was mentioned before, the MessageFactory.ToMessage() method performs signature verification on the value message using the payer's certificate embedded into the value message. Without a physical MintChip present we need to make sure that the payer's certificate is an authentic one and has been issued by the Royal Canadian Mint. In order to do that, the server must have the Royal Canadian Mint Certificate Authority (CA) certificate imported into the Microsoft Certificate Store -> Local Machine -> Trusted Root Certification Authorities. Once this certificate is installed in the server's Certificate Store, the payer's certificate embedded into the value message can be verified as the following:

    if (!MessageFactory.Instance.VerifyCertificate(valueMessage.PayerCertificate))
    {
        throw new MintChipException(
                  "The payer's certificate of this Value Message is not valid.");
    }

Once this verification is successful, we should verify that the IValueMessage.PayeeId of the submitted value message matches the Id of the targeted (payee) MintChip. This Id can be provided through the Web application's configuration file.

To ensure that the submitted value message is not a duplicate and has not been processed before, we suggest keeping a track of the processed value messages in a database. A sufficiently random IValueMessage.Challenge property in combination with the IValueMessage.PayerId should provide good uniqueness. In our previous example we used DateTime.Now.GetHashCode() to generate a unique challenge value.

Issuing Value Messages

When a physical MintChip is present on the server machine, the full MintChip API functionality is available to the Web application including the issuing of payments in form of the value messages. One of the possible scenarios may include issuing refunds for the Web purchases in a consumer oriented solution or paying for a purchase order in a B2B scenario.

The following is an example of how the MintChip .NET API can be used in an ASP.NET MVC controller to perform this operation:

    private ActionResult Pay(int amount, string payeeId)
    {
        IMintChip mintChip = MintChipFactory.Instance.CreateMintChip();

        IValueRequestMessage request = MessageFactory.Instance.
            CreateValueRequestMessage(payeeId, amount, mintChip.CurrencyCode);

        IValueMessage valueMessage = mintChip.CreateValueMessage(request);

        return new ContentResult()
                    {
                        Content = valueMessage.ToBase64String(),
                        ContentType = "application/vnd.scg.ecn-message"
                    };
    }

The example above is a simplified version of what may be needed in a more realistic scenario. For example, the value message may be created in response to receiving a full value request message rather than creating it on the server.

Conclusion

This Guide has demonstrated that the MintChip .NET API makes it rather easy and straightforward to incorporate MintChip payment transactions into Web solutions developed on the Microsoft ASP.NET platform. We showed that the Web server can handle the MintChip payments regardless of the client platform they originate from and regardless whether a physical MintChip is available on the server. The document also demonstrated that the MintChip cross-browser plugin allows the inclusion of MintChip functionality into the client side HTML pages that can be displayed by all major browsers on the Windows platform.