Skip to content

Commit

Permalink
Merge pull request #180 from unzerdev/develop
Browse files Browse the repository at this point in the history
Release 3.5.0
  • Loading branch information
Ryouzanpaku authored Feb 8, 2024
2 parents df721ca + a7cfd16 commit 818cb1f
Show file tree
Hide file tree
Showing 21 changed files with 1,138 additions and 5 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/unit-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
php: ['7.4', '8.0', '8.1', '8.2']
php: ['7.4', '8.0', '8.1', '8.2', '8.3']
name: PHP ${{ matrix.php }} unit tests
steps:
- uses: actions/checkout@v3
Expand Down
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,15 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres
to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).

## [3.5.0](https://github.com/unzerdev/php-sdk/compare/3.4.1..3.5.0)

This version adds support for Google Pay.

### Added
* Add `\UnzerSDK\Resources\PaymentTypes\Googlepay` payment type.
* Add Example for Google Pay.
* Add PHP 8.3 version to composer.json

## [3.4.1](https://github.com/unzerdev/php-sdk/compare/3.4.0..3.4.1)

Revert deprecation of Sepa Direct Debit type.
Expand Down
4 changes: 2 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
{
"name": "unzerdev/php-sdk",
"description": "This is the php sdk to connect to the Unzer rest api.",
"description": "This is the php sdk to connect to the Unzer rest API.",
"minimum-stability": "stable",
"license": "Apache-2.0",
"require": {
"php": "~7.4.0|~8.0.0|~8.1.0|~8.2.0",
"php": "~7.4.0|~8.0.0|~8.1.0|~8.2.0|~8.3.0",
"ext-json": "*"
},
"require-dev": {
Expand Down
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
2 changes: 2 additions & 0 deletions src/Constants/IdStrings.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ class IdStrings
public const CARD = 'crd';
public const EPS = 'eps';
public const GIROPAY = 'gro';
public const GOOGLE_PAY = 'gop';
public const HIRE_PURCHASE_DIRECT_DEBIT = 'hdd';
public const IDEAL = 'idl';
public const INSTALLMENT_SECURED = 'ins';
Expand Down Expand Up @@ -63,6 +64,7 @@ class IdStrings
self::CARD,
self::EPS,
self::GIROPAY,
self::GOOGLE_PAY,
self::HIRE_PURCHASE_DIRECT_DEBIT,
self::IDEAL,
self::INSTALLMENT_SECURED,
Expand Down
Loading

0 comments on commit 818cb1f

Please sign in to comment.