cancel
Showing results for 
Search instead for 
Did you mean: 

Authentication failed because the remote party sent a TLS alert: 'HandshakeFailure'

Hi,

I am doing the apple pay implementation for website using authorize.net and asp.net core. I have configured my apple developer account and I also enabled/configured the apple pay settings on the authorize.net. I downloaded the payment processing certificate and merchant Id certificate on mac and generated the .pem file form that.

I am using the apple pay js API.  I am facing the issue in onvalidatemerchant method. below is client side code

session.onvalidatemerchant = function (event) {
                            // Send the validation URL to the server to get the merchant session
                            fetch('/applepay/validatemerchant', {
                                method: 'POST',
                                body: JSON.stringify({
                                    validationUrl: event.validationURL,
                                }),
                                headers: {
                                    'Content-Type': 'application/json',
                                    //RequestVerificationToken: document.getElementsByName("__RequestVerificationToken")[0].value,
                                    Accept: 'application/json',
                                },
                            })
                                .then(function (response) {
                                    console.log('response', response);
                                    return response.json();
                                })
                                .then(function (result) {
                                    console.log('success', result);
                                    if (result.success) {
                                        // Complete the validation and pass the merchant session to the payment request
                                        paymentRequest.completeMerchantValidation(result.merchantSession);
                                    }
                                });
                        };

my server side code is like below

[HttpPost]
        [Route("applepay/validatemerchant")]
        public async Task<IActionResult> ValidateMerchant([FromBody] RequestData requestData)
        {
            try
            {
                var certificatePath = "applepay.cert.full.pem";
                var url = "https://apple-pay-gateway.apple.com/paymentservices/paymentSession";

                // Load the certificate file
                var certificateBytes = await System.IO.File.ReadAllBytesAsync(certificatePath);
                var certificate = new X509Certificate2(certificateBytes);
                // Prepare the request data
                var requestData1 = new
                {
                    merchantIdentifier = "merchant.com.mymerchantid",
                    initiativeContext = "website url",
                    initiative = "web",
                    displayName = "sote name"
                };
                var jsonRequestData = JsonConvert.SerializeObject(requestData1);
                var content = new StringContent(jsonRequestData, Encoding.UTF8, "application/json");

                // Create the HTTP client
                var handler = new HttpClientHandler()
                {
                    ClientCertificateOptions = ClientCertificateOption.Manual,
                    SslProtocols = SslProtocols.Tls12 | SslProtocols.Tls13,
                    AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip,
                };
                handler.ClientCertificates.Add(certificate);
                var client = new HttpClient(handler,disposeHandler:true);
                // Send the request
                var response = await client.PostAsync(requestData.validationUrl, content);
                // Read the response
                var responseContent = await response.Content.ReadAsStringAsync();
                if (responseContent.IsSuccessStatusCode)
                {
                    return Ok(responseContent);
                }
                else
                {
                    return BadRequest(responseContent);
                }
            }
            catch (Exception e)
            {
                return Json(new { success = false, source = "catch", error = e.Message + ", " + e.InnerException != null ? e.InnerException.Message : "" });
            }
        }

I have tried many server side settings but I always get the same error message. I tested the curl command on the mac with same detail and certificate it worked fine. This code is not working on my server.  Below is the error.

{
   "StatusCode":null,
   "StackTrace":" at System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Boolean async, Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken)\r\n at System.Net.Http.HttpConnectionPool.ConnectAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)\r\n at System.Net.Http.HttpConnectionPool.CreateHttp11ConnectionAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)\r\n at System.Net.Http.HttpConnectionPool.GetHttpConnectionAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)\r\n at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean async, Boolean doRequestAuth, CancellationToken cancellationToken)\r\n at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)\r\n at System.Net.Http.DecompressionHandler.SendAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)\r\n at System.Net.Http.DiagnosticsHandler.SendAsyncCore(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)\r\n at System.Net.Http.HttpClient.SendAsyncCore(HttpRequestMessage request, HttpCompletionOption completionOption, Boolean async, Boolean emitTelemetryStartStop, CancellationToken cancellationToken)\r\n at Web.Controllers.CartController.ValidateMerchant(RequestData requestData) in C:\\Project\\AllfilterCoreRepoRecent Authorize\\Web\\Controllers\\CartController.cs:line 1640",
   "Message":"The SSL connection could not be established, see inner exception.",
   "Data":{
      
   },
   "InnerException":{
      "ClassName":"System.Security.Authentication.AuthenticationException",
      "Message":"Authentication failed because the remote party sent a TLS alert: 'HandshakeFailure'.",
      "Data":null,
      "InnerException":{
         "ClassName":"System.ComponentModel.Win32Exception",
         "Message":"The message received was unexpected or badly formatted.",
         "Data":null,
         "InnerException":null,
         "HelpURL":null,
         "StackTraceString":null,
         "RemoteStackTraceString":null,
         "RemoteStackIndex":0,
         "ExceptionMethod":null,
         "HResult":-2147467259,
         "Source":null,
         "WatsonBuckets":null,
         "NativeErrorCode":-2146893018
      },
      "HelpURL":null,
      "StackTraceString":" at System.Net.Security.SslStream.ForceAuthenticationAsync[TIOAdapter](TIOAdapter adapter, Boolean receiveFirst, Byte[] reAuthenticationData, Boolean isApm)\r\n at System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Boolean async, Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken)",
      "RemoteStackTraceString":null,
      "RemoteStackIndex":0,
      "ExceptionMethod":null,
      "HResult":-2146233087,
      "Source":"System.Net.Security",
      "WatsonBuckets":null
   },
   "HelpLink":null,
   "Source":"System.Net.Http",
   "HResult":-2146233087
}

 Can you please help me to resolve this error.

 

2 REPLIES 2

Apple Pay is working for me now. I have made some changes.

1. I converted the PEM file to PFX file

2. I made one change in the application pool. converted the identity from ApplicationPoolIdentity to NetworkService.

After that my Apple Pay worked fine.

Hope this will help to someone.

Many thanks. Your solution worked.

haleyhoman
Member