ApplePay Integration Error

Hello ApplePay Support,

I am integrating apple pay support on the following page but getting error. I have attached code files and video also about debug that code with different response print. Please check it and let me know where is issue.

ApplePay Page:

https://payment.bestgoodstudio.com/uk/pay/

JS Code:

$(document).ready(function() { function setupApplePayButton() { var applePayButton = $('#apple-pay-button');

    if (applePayButton.length) {
        applePayButton.on('click', function() {
            initiateApplePayPayment();
        });
    }
}

async function initiateApplePayPayment() {
    if (!window.ApplePaySession) {
        alert('Apple Pay is not supported in this browser/environment.');
        console.error('Apple Pay is not supported in this browser/environment.');
        return;
    }

    var request = {
        countryCode: 'GB',
        currencyCode: 'EUR',
        supportedNetworks: ['visa', 'masterCard', 'amex'],
        merchantCapabilities: ['supports3DS', 'supportsEMV', 'supportsCredit', 'supportsDebit'],
        total: {
            label: 'Elitelab Pte Ltd',
            amount: '2.50'
        }
    };

    var session = new ApplePaySession(3, request);

    session.onvalidatemerchant = async function(event) {
        const validationURL = event.validationURL;
        alert("Validation URL received: " + validationURL);

        try {
            const response = await fetch('https://payment.bestgoodstudio.com/uk/pay/apple_pay_validation.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ validationURL: validationURL })
            });

            const responseBody = await response.text(); // Get raw text to print whole response
            alert("Validation Response (raw): " + responseBody); // Print raw response in alert

            if (response.ok) {
                const responseData = JSON.parse(responseBody); // Parse it if valid JSON
                alert('Validation Response (parsed): ' + JSON.stringify(responseData));
                console.log('Merchant Validation Data:', responseData);

                if (session) {
                    session.completeMerchantValidation(responseData);
                    alert('Merchant validation completed.');
                }
            } else {
                alert("Merchant Validation failed. HTTP Status: " + response.status);
                session.abort(); // Abort session if validation fails
            }
        } catch (e) {
            alert('Error during Merchant Validation: ' + e.message);
            console.error('Merchant validation error:', e);
            session.abort(); // Abort session on error
        }
    };

    session.onpaymentauthorized = function(event) {
        var payment = event.payment;
        var paymentToken = payment.token.paymentData;
        alert("Payment authorized. Payment Data: " + JSON.stringify(payment));
        console.log('Payment Authorized:', payment);

        processApplePayPayment(payment, function(success) {
            if (success) {
                session.completePayment(ApplePaySession.STATUS_SUCCESS);
                alert('Payment completed successfully.');
            } else {
                session.completePayment(ApplePaySession.STATUS_FAILURE);
                alert('Payment failed.');
            }
        });
    };

    session.oncancel = function(event) {
        alert("Session canceled: " + JSON.stringify(event));
        console.log("Session canceled:", event);
    };

    session.oncomplete = function(event) {
        alert("Session complete: " + JSON.stringify(event));
        console.log("Session complete:", event);
    };

    session.begin();
}

function processApplePayPayment(payment, callback) {
    var postData = {
        paymentData: payment.token.paymentData,
        billingContact: payment.billingContact,
        shippingContact: payment.shippingContact
    };

    $.ajax({
        url: 'process_apple_pay.php',
        method: 'POST',
        data: JSON.stringify(postData),
        contentType: 'application/json',
        success: function(response) {
            alert("Payment Processing Response: " + JSON.stringify(response));
            console.log("Payment Processing Response:", response);
            callback(response.success);
        },
        error: function(error) {
            alert('Error processing payment: ' + JSON.stringify(error));
            console.error('Error processing payment:', error);
            callback(false);
        }
    });
}

setupApplePayButton();

});

PHP Code:

<?php

header('Content-Type: application/json');

// Retrieve the validation URL from the POST data $input = json_decode(file_get_contents('php://input'), true); $validationURL = $input['validationURL'];

$merchantIdentifier = 'merchant.biz.elitelab.kidsgames'; $displayName = 'Kid friendly online gaming and media platform'; $domainName = 'payment.bestgoodstudio.com';

$data = [ 'merchantIdentifier' => $merchantIdentifier, 'displayName' => $displayName, 'initiative' => 'web', 'initiativeContext' => $domainName ];

// Path to your combined Apple Pay Merchant Identity Certificate $certPath = '/home/bitnami/certificates/combined_merchant_id.pem';

$ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $validationURL); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json' ]); curl_setopt($ch, CURLOPT_SSLCERT, $certPath); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);

// Enable verbose output for debugging curl_setopt($ch, CURLOPT_VERBOSE, true); $verboseLog = fopen('php://temp', 'rw+'); curl_setopt($ch, CURLOPT_STDERR, $verboseLog);

$response = curl_exec($ch);

// Log cURL request and response details rewind($verboseLog); $verboseLogContent = stream_get_contents($verboseLog); error_log("Apple Pay Validation cURL Verbose Information:\n" . $verboseLogContent); fclose($verboseLog);

// Log error or successful response if ($response === false) { $error_message = curl_error($ch); error_log('Apple Pay Merchant Validation Error: ' . $error_message); // Log error on server http_response_code(500); echo json_encode(['error' => $error_message]); } else { // Log the response from Apple error_log('Apple Pay Merchant Validation Response: ' . $response); http_response_code(200); echo $response; // Return the raw response from Apple }

curl_close($ch);


Testing Video:

https://drive.google.com/file/d/1wxjnRq_rfasW9***1ciL6ketb6nUXmFl/view?usp=sharing

ApplePay Integration Error
 
 
Q