Skip to content

Instantly share code, notes, and snippets.

@ahoshaiyan
Created July 28, 2021 16:42
Show Gist options
  • Save ahoshaiyan/3e4fd14a2f81e51147e97d08a407636f to your computer and use it in GitHub Desktop.
Save ahoshaiyan/3e4fd14a2f81e51147e97d08a407636f to your computer and use it in GitHub Desktop.

Laravel Apple Pay Merchant Validation Sample

Routes

Route::post('/apple-pay/verify-merchant', 'ApplePayController@validateMerchant');

Controller

Here is an example used to validate merchant in a Laravel controller. Please make sure to install GuzzleHttp as it is needed to perform HTTP requests. To install please use:

composer install guzzlehttp/guzzle

Avoid using curl procedural APIs directly and prefer using guzzle in order to handle error using exceptions and to simplify your code.

Here is the controller:

<?php

namespace App\Http\Controllers;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\BadResponseException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class ApplePayController extends Controller
{
    public function validateMerchant(Request $request)
    {
        $this->validate($request, [
            'validation_url' => 'required|url'
        ]);

        $url = $request->input('validation_url');

        Log::info('Validating Merchant: ' . $url);

        $body = [
            'merchantIdentifier' => 'merchant.com.example',
            'displayName' => "Merchant Name",
            'initiative' => 'web',
            'initiativeContext' => 'example.com'
        ];

        $options = [
            'json' => $body,
            'ssl_key' => '/path/to/merchant/validation/pk.pem',
            // In case you have a password on your Private Key
            // 'ssl_key' => [
            //     '/path/to/merchant/validation/pk.pem',
            //     '1234567890-='
            // ],
            'cert' => '/path/to/merchant/validation/cert.pem',
        ];

        try {
            $client = new Client();
            $response = $client->post($url, $options);
        } catch (BadResponseException $e) {
            $r = $e->getResponse();

            // Send Apple response as is to frontend
            return response(json_decode($r->getBody()->getContents()))
                ->setStatusCode($r->getStatusCode());
        }

        return json_decode($response->getBody()->getContents());
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment