Skip to content

[CC-724] Add googlepay example #176

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Feb 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions examples/Googlepay/Constants.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php
/**
* This file defines the constants needed for the Google Pay example.
*/

require_once __DIR__ . '/../Constants.php';

define('EXAMPLE_URL', EXAMPLE_BASE_FOLDER . 'Googlepay');
define('CONTROLLER_URL', EXAMPLE_URL . '/Controller.php');
95 changes: 95 additions & 0 deletions examples/Googlepay/Controller.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
<?php
/**
* This is the controller for the Google Pay example.
* It is called when the pay button on the index page is clicked.
*
* @link https://docs.unzer.com/
*
*/

/** Require the constants of this example */
const TRANSACTION_STATUS_KEY = 'transactionStatus';
const REDIRECT_URL_KEY = 'redirectUrl';
require_once __DIR__ . '/Constants.php';

/** @noinspection PhpIncludeInspection */
/** Require the composer autoloader file */
require_once __DIR__ . '/../../../../autoload.php';

use UnzerSDK\examples\ExampleDebugHandler;
use UnzerSDK\Exceptions\UnzerApiException;
use UnzerSDK\Unzer;

session_start();
session_unset();

$clientMessage = 'Something went wrong. Please try again later.';
$merchantMessage = 'Something went wrong. Please try again later.';

function redirect($url, $merchantMessage = '', $clientMessage = '')
{
$_SESSION['merchantMessage'] = $merchantMessage;
$_SESSION['clientMessage'] = $clientMessage;
header('Location: ' . $url);
die();
}

// These lines are just for this example
$jsonData = json_decode(file_get_contents('php://input'), false);
$paymentTypeId = $jsonData->typeId;
$transactionType = $jsonData->transaction_type ?? 'authorize';

// You will need the id of the payment type created in the frontend (index.php)
if (empty($paymentTypeId)) {
echo json_encode(['result' => false]);
return;
}

$transactionResult = [
TRANSACTION_STATUS_KEY => 'error',
REDIRECT_URL_KEY => ''
];

// Catch API errors, write the message to your log and show the ClientMessage to the client.
try {
// Create an Unzer object using your private key and register a debug handler if you want to.
$unzer = new Unzer(UNZER_PAPI_PRIVATE_KEY);
$unzer->setDebugMode(true)->setDebugHandler(new ExampleDebugHandler());

if ($transactionType === 'charge') {
$charge = new \UnzerSDK\Resources\TransactionTypes\Charge(12.32, 'EUR', RETURN_CONTROLLER_URL);
$transaction = $unzer->performCharge($charge, $paymentTypeId);
} else {
$authorize = new \UnzerSDK\Resources\TransactionTypes\Authorization(12.32, 'EUR', RETURN_CONTROLLER_URL);
$transaction = $unzer->performAuthorization($authorize, $paymentTypeId);
}

// You'll need to remember the paymentId for later in the ReturnController
$_SESSION['PaymentId'] = $transaction->getPaymentId();
$_SESSION['ShortId'] = $transaction->getShortId();

$redirectUrl = $transaction->getRedirectUrl();

if (!empty($redirectUrl)) {
$transactionResult[REDIRECT_URL_KEY] = $redirectUrl;
}

if ($transaction->isSuccess()) {
$transactionResult[TRANSACTION_STATUS_KEY] = 'success';
echo json_encode($transactionResult);
return;
}
if ($transaction->isPending()) {
$transactionResult[TRANSACTION_STATUS_KEY] = 'pending';

echo json_encode($transactionResult);
return;
}
} catch (UnzerApiException $e) {
$_SESSION['merchantMessage'] = $e->getMerchantMessage();
$_SESSION['clientMessage'] = $e->getClientMessage();
} catch (RuntimeException $e) {
$_SESSION['merchantMessage'] = $e->getMessage();
}

echo json_encode($transactionResult);
197 changes: 197 additions & 0 deletions examples/Googlepay/index.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,197 @@
<?php

/**
* This file provides an example implementation of the Googlepay payment type.
*/

/** Require the constants of this example */
require_once __DIR__ . '/Constants.php';

/** @noinspection PhpIncludeInspection */
/** Require the composer autoloader file */
require_once __DIR__ . '/../../../../autoload.php';
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<title>Unzer UI Examples</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin="anonymous"></script>

<link rel="stylesheet" href="https://static.unzer.com/v1/unzer.css"/>
<script type="text/javascript" src="https://static.unzer.com/v1/unzer.js"></script>
<script src="https://pay.google.com/gp/p/js/pay.js"></script>

</head>

<body style="margin: 70px 70px 0;">

<p><a href="https://docs.unzer.com/reference/test-data" target="_blank">Click here to open our test data in new tab.</a><br/>
</p>

<form id="payment-form" class="unzerUI form" novalidate>
<!-- This is just for the example - Start -->
<div class="fields inline">
<label for="transaction_type">Chose the transaction type you want to test:</label>
<div class="field">
<div class="unzerUI radio checkbox">
<input type="radio" name="transaction_type" value="authorize" checked="">
<label>Authorize</label>
</div>
</div>
<div class="field">
<div class="unzerUI radio checkbox">
<input type="radio" name="transaction_type" value="charge">
<label>Charge</label>
</div>
</div>
</div>
<!-- This is just for the example - End -->

<div>
<div class="field" id="error-holder" style="color: #9f3a38"> </div>
<div class="button-well">
<div class="applePayButtonContainer">
<div class="apple-pay-button apple-pay-button-black" lang="us"
onclick="setupApplePaySession()"
title="Start Apple Pay" role="link" tabindex="0">
</div>
</div>
</div>
</div>
</form>

<div id="dimmer-holder-googlepay" class="ui active dimmer" style="display: none;">
<div class="ui loader"></div>
</div>

<div id="example-googlepay-stack"></div>
<div id="error-holder-googlepay" class="field" style="text-align: center; color: #9f3a38"></div>

<script>
const unzerInstance = new unzer('<?php echo UNZER_PAPI_PUBLIC_KEY; ?>');
const colors = ['black','white'];
const googlepayChannelId = "<?php echo UNZER_EXAMPLE_GOOGLEPAY_CHANNEL; ?>"
const stackHolder = document.querySelector('#example-googlepay-stack');

const tmpPaymentDataRequestObject = {
gatewayMerchantId: googlepayChannelId,
allowedCardNetworks: [
'MASTERCARD',
'VISA',
'DISCOVER',
'JCB',
],
merchantInfo: {
merchantId: googlepayChannelId,
merchantName: 'Example Merchant'
},
transactionInfo: {
displayItems: [],
countryCode: 'DE',
currencyCode: 'EUR',
totalPrice: '12.00',
},
}

function handleGooglepayError(error) {
let errorMessage = error.customerMessage || error.message || 'Error';
if (error.data && Array.isArray(error.data.errors) && error.data.errors[0]) {
errorMessage = error.data.errors[0].customerMessage || 'Error'
}

document.getElementById('error-holder-googlepay').innerHTML = errorMessage;

return {
status: 'error',
message: errorMessage || 'Unexpected error'
}
}

colors.map(function (color) {
const htmlString = '<div id="example-googlepay-' + color + '" class="field" style="text-align: center; margin: 5px 0"></div>'
return ({
instance: null,
color: color,
htmlString: htmlString
})
}).forEach(function (item) {
stackHolder.insertAdjacentHTML('beforeend', item.htmlString)
item.instance = unzerInstance.Googlepay()
const extendedPaymentDataRequestObject = {
...tmpPaymentDataRequestObject,
buttonColor: item.color,
onPaymentAuthorizedCallback: (paymentData) => {
document.getElementById('error-holder-googlepay').innerHTML = ''
const $form = $('form[id="payment-form"]');
const formObject = QueryStringToObject($form.serialize());

return item.instance.createResource(paymentData)
.then(typeCreationResult => {
document.getElementById('dimmer-holder-googlepay').style.display = 'block';
formObject.typeId = typeCreationResult.id;

return fetch(
'./Controller.php',
{
body: JSON.stringify(formObject),
method: 'POST'
}
)
.then(response => response.json())
.then( transactionResult => {
const status = transactionResult.transactionStatus;

if (status === 'success' || status === 'pending') {
if (transactionResult.redirectUrl.trim().length !== 0) {
window.location.href = transactionResult.redirectUrl;
} else {
window.location.href = '<?php echo RETURN_CONTROLLER_URL; ?>';
}
return { status: 'success' };
}
window.location.href = '<?php echo FAILURE_URL; ?>';
return {
status: 'error',
message: transactionResult.customerMessage || transactionResult.message || 'Unexpected error'
}
})
.catch(function (error) {
return handleGooglepayError(error);
}
)
})
.catch(function (error) {
return handleGooglepayError(error);
})
}
}

const paymentDataRequestObject = item.instance.initPaymentDataRequestObject(extendedPaymentDataRequestObject)
item.instance.create(
{
containerId: 'example-googlepay-' + item.color
},
paymentDataRequestObject
)
})

// Translates query string to object
function QueryStringToObject(queryString) {
const pairs = queryString.slice().split('&');
let result = {};

pairs.forEach(function(pair) {
pair = pair.split('=');
result[pair[0]] = decodeURIComponent(pair[1] || '');
});
return JSON.parse(JSON.stringify(result));
}

</script>

</body>
</html>
9 changes: 8 additions & 1 deletion examples/_enableExamples.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
define('UNZER_PAPI_EXAMPLES', false);

/* Please set this to your url. It must be reachable over the net
Webhooks will work with https only. However protocol can be changed to http if necessary. */
Webhooks will work with https only. However, protocol can be changed to http if necessary. */
define('UNZER_PAPI_URL', 'https://'.$_SERVER['HTTP_HOST']);

/* Please enter the path from root directory to the example folder */
Expand All @@ -26,6 +26,13 @@
define('UNZER_PP_LOGO_URL', 'https://sbx-insights.unzer.com/static/unzerLogo.svg');
define('UNZER_PP_FULL_PAGE_IMAGE_URL', 'https://raw.githubusercontent.com/unzerdev/php-sdk/da9c3fce11264f412e03009606621cc6d9ec0ab1/unzer_logo.svg');

/* ============ PaymentType Specific settings ============ */

/* ------------ Google Pay ------------ */
// Channel of 'googlepay' type. You can find the channel in your keypair config.
define('UNZER_EXAMPLE_GOOGLEPAY_CHANNEL', '');

/* ------------ Apple Pay ------------ */
/* For Apple Pay only, set the path to your Apple Pay Merchant-ID certificate. */
define('UNZER_EXAMPLE_APPLEPAY_MERCHANT_CERT', UNZER_PAPI_FOLDER . '');

Expand Down
12 changes: 12 additions & 0 deletions examples/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,18 @@ function printMessage($type, $title, $text)
Try
</div>
</div>
<div class="card olive">
<div class="content">
<div class="header">
Google Pay
</div>
<div class="description">
</div>
</div>
<div id="tryGooglepayExample" class="ui bottom attached green button" onclick="location.href='Googlepay/';">
Try
</div>
</div>
<div class="card olive">
<div class="content">
<div class="header">
Expand Down