Merchant Validation: ASP.NET Core


On this page

Before Using This Sample

This code sample is provided to help you implement the merchant validation process using ASP.NET Core MVC. You should read through Requesting an Apple Pay Payment Session for more information on the process.

We do not provide any warranty or support for code samples on this page.

Requirements

In this sample, we are using Newtonsoft.Json to serialize our DTOs. You can add it from here: Newtonsoft.Json on Nuget

Merchant Identity Certificate

Before we can proceed, we need to generate a Merchant Identity Certificate that will allow us to successfully connect to Appleā€™s servers and request an Apple Pay session.

You can follow this guide to acquire your certificate: How to Setup Apple Pay Requirements.

Storing Certificates

Certificates are credential files, they are used to authenticate you with Apple and must be stored safely. You SHOULD NEVER store them in your wwwroot directory and instead store them in the project directory.

You can instruct Visual Studio to copy the files every build or add this to your csproj file:

<ItemGroup>
    <None Update="merchant_id/**/*">
        <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </None>
</ItemGroup>

.NET Core requires certificate and key files to be combined into a pfx file, to do this we can run the following command on our files:

openssl pkcs12 -export -in ApplePay.crt.pem -inkey ApplePay.key.pem -out ApplePay.pfx

For this demonstration, we will store our pfx file as /path/to/project/merchant_id/ApplePay.pfx.

Data Transfer Objects

We need to DTOs to help us with our validation process. Please define the following classes anywhere within your project.

class ValidateMerchantRequest
{
    public string merchantIdentifier { get; set; }
    public string displayName { get; set; }
    public string initiative { get; set; }
    public string initiativeContext { get; set; }
}
public class FrontEndValidationRequest
{
    public string ValidationUrl { get; set; }
}

The Validation Action

First, import some namespaces:

using Newtonsoft.Json;
using System.Net.Http;
using System.Security.Cryptography.X509Certificates;
using System.Text;

Now, within our controller, we can define the following action:

[HttpPost("/validate-merchant")]
public async Task<IActionResult> ValidateMerchant([FromBody] FrontEndValidationRequest request)
{
    var certFile = await System.IO.File.ReadAllBytesAsync("merchant_id/ApplePay.pfx");
    var cert = new X509Certificate2(certFile, "123");

    var opt = new HttpClientHandler();
    opt.ClientCertificates.Add(cert);
    var client = new HttpClient(opt);
    
    var requestBody = new ValidateMerchantRequest
    {
        merchantIdentifier = "merchant.com.example",
        displayName = "example.com",
        initiative = "web",
        initiativeContext = "example.com"
    };
    
    using (var content = new StringContent(JsonConvert.SerializeObject(requestBody), Encoding.Default, "application/json"))
    {
        HttpResponseMessage response = null;
        try
        {
            response = await client.PostAsync(request.ValidationUrl, content);
            response.EnsureSuccessStatusCode();
            return Content(await response.Content.ReadAsStringAsync(), "application/json");
        }
        catch (HttpRequestException e)
        {
            return BadRequest(new
            {
                Type = "validation_error",
                Error = e.Message,
                Response = response != null ? await response.Content.ReadAsStringAsync() : null
            });
        }
        finally
        {
            if (response != null)
            {
                response.Dispose();
            }
        }
    }
}

More Resources

You can read more about merchant validation at Requesting an Apple Pay Payment Session.


Last Modified : Sep 2021