6. Usage examples
These examples are part of the repository (example/) and run in the test suite with test keys.
They read keys and the merchant number from environment variables:
<?php
/**
* Configuration shared by the examples.
*
* Never put private keys, passphrases or merchant credentials into version control,
* and keep key files outside the web root. These examples read them from environment variables:
*
* GPWEBPAY_PRIVATE_KEY path to your private key (PEM) generated in the GP webpay portal
* GPWEBPAY_PRIVATE_KEY_PASSPHRASE passphrase of that key
* GPWEBPAY_PUBLIC_KEY path to the GP webpay public key (PEM) from the portal
* GPWEBPAY_MERCHANT_NUMBER your merchant number
*/
declare(strict_types=1);
use Pixidos\GPWebPay\Config\Factory\ConfigFactory;
$environment = static function (string $name): string {
$value = getenv($name);
if (false === $value || '' === $value) {
throw new RuntimeException(sprintf('Set the %s environment variable.', $name));
}
return $value;
};
return [
ConfigFactory::PRIVATE_KEY => $environment('GPWEBPAY_PRIVATE_KEY'),
ConfigFactory::PRIVATE_KEY_PASSPHRASE => $environment('GPWEBPAY_PRIVATE_KEY_PASSPHRASE'),
ConfigFactory::PUBLIC_KEY => $environment('GPWEBPAY_PUBLIC_KEY'),
// Test environment of GP webpay HTTP API 1.19. Production: https://3dsecure.gpwebpay.com/pgw/order.do
// Use the address your provider gives you if it differs.
ConfigFactory::URL => 'https://test.3dsecure.gpwebpay.com/pgw/order.do',
ConfigFactory::MERCHANT_NUMBER => $environment('GPWEBPAY_MERCHANT_NUMBER'),
ConfigFactory::DEPOSIT_FLAG => 1,
// Without query parameters: GP webpay may refuse return addresses with parameters.
ConfigFactory::RESPONSE_URL => 'https://shop.example/payment/gpwebpay-response',
];
Create and render a request
<?php
declare(strict_types=1);
use Pixidos\GPWebPay\Config\Factory\ConfigFactory;
use Pixidos\GPWebPay\Config\Factory\PaymentConfigFactory;
use Pixidos\GPWebPay\Data\Operation;
use Pixidos\GPWebPay\Enum\Currency as CurrencyEnum;
use Pixidos\GPWebPay\Enum\PayMethod;
use Pixidos\GPWebPay\Factory\RequestFactory;
use Pixidos\GPWebPay\Param\AddInfo;
use Pixidos\GPWebPay\Param\AmountInPennies;
use Pixidos\GPWebPay\Param\Currency;
use Pixidos\GPWebPay\Param\MerOrderNum;
use Pixidos\GPWebPay\Param\OrderNumber;
use Pixidos\GPWebPay\Param\PayMethods;
use Pixidos\GPWebPay\Signer\SignerFactory;
use Pixidos\GPWebPay\Signer\SignerProvider;
require_once __DIR__ . '/../vendor/autoload.php';
// setup services
$config = (new ConfigFactory(new PaymentConfigFactory()))->create(require __DIR__ . '/config.php');
$signerProvider = new SignerProvider(new SignerFactory(), $config->getSignerConfigProvider());
$requestFactory = new RequestFactory($config->getPaymentConfigProvider(), $signerProvider);
// The order being paid, loaded from your database.
$order = ['number' => 2026000123, 'totalInHellers' => 129900, 'customerName' => 'Jan Novak', 'email' => 'jan@example.com'];
// Save a new payment attempt for the order (status "pending", amount, currency, gateway) before
// redirecting the customer. Its unique numeric ID, e.g. an AUTO_INCREMENT key, is the ORDERNUMBER:
// at most 15 digits and never reused for another request. Do not derive it from time(),
// two customers can start a payment in the same second.
$paymentAttemptId = 7001;
$operation = new Operation(
orderNumber: new OrderNumber($paymentAttemptId),
amount: new AmountInPennies($order['totalInHellers']), // integer amount in hellers: 1 299.00 CZK
currency: new Currency(CurrencyEnum::CZK()),
);
$operation->addParam(new MerOrderNum($order['number'])); // your order number, shown on statements
$operation->addParam(new PayMethods(PayMethod::CARD(), PayMethod::GOOGLE_PAY(), PayMethod::APPLE_PAY()));
// Cardholder data required by the card schemes (PSD2): the name and an e-mail or a phone number.
// Send only real data you have and omit elements you do not have; never invent values.
// The name allows ASCII characters only. Validate the structure against the ADDINFO XSD from the GP webpay portal.
$xml = static fn (string $value): string => htmlspecialchars($value, ENT_XML1 | ENT_QUOTES, 'UTF-8');
$operation->addParam(new AddInfo(
'<additionalInfoRequest xmlns="http://gpe.cz/gpwebpay/additionalInfo/request" version="5.0">'
. '<cardholderInfo><cardholderDetails>'
. '<name>' . $xml($order['customerName']) . '</name>'
. '<email>' . $xml($order['email']) . '</email>'
. '</cardholderDetails></cardholderInfo>'
. '</additionalInfoRequest>' // no line breaks or spaces between elements
));
$request = $requestFactory->create($operation);
// Recommended: an automatically or manually submitted POST form. It has no URL length limit
// and keeps UTF-8 in ADDINFO intact. Every value must be HTML-escaped.
$escape = static fn (string $value): string => htmlspecialchars($value, ENT_QUOTES | ENT_HTML5, 'UTF-8');
echo '<form method="post" action="' . $escape($request->getRequestUrl(true)) . '">' . "\n";
foreach ($request->getParams() as $name => $value) {
echo '<input type="hidden" name="' . $escape($name) . '" value="' . $escape($value) . '">' . "\n";
}
echo '<button type="submit">Pay</button>' . "\n";
echo "</form>\n";
// Alternatively a link (GET). Keep the request short: browsers and servers limit URL length.
// echo '<a href="' . $escape($request->getRequestUrl()) . '">Pay</a>';
Handle a response from GP webpay
<?php
declare(strict_types=1);
use Pixidos\GPWebPay\Config\Factory\ConfigFactory;
use Pixidos\GPWebPay\Config\Factory\PaymentConfigFactory;
use Pixidos\GPWebPay\Data\ResponseInterface;
use Pixidos\GPWebPay\Exceptions\GPWebPayException;
use Pixidos\GPWebPay\Exceptions\GPWebPayResultException;
use Pixidos\GPWebPay\Exceptions\InvalidResponseException;
use Pixidos\GPWebPay\Factory\ResponseFactory;
use Pixidos\GPWebPay\ResponseProvider;
use Pixidos\GPWebPay\Signer\SignerFactory;
use Pixidos\GPWebPay\Signer\SignerProvider;
require_once __DIR__ . '/../vendor/autoload.php';
// setup services
$config = (new ConfigFactory(new PaymentConfigFactory()))->create(require __DIR__ . '/config.php');
$signerProvider = new SignerProvider(new SignerFactory(), $config->getSignerConfigProvider());
$responseFactory = new ResponseFactory($config->getPaymentConfigProvider());
$responseProvider = new ResponseProvider($config->getPaymentConfigProvider(), $signerProvider);
// GP webpay returns the result by a redirect (GET) or by an automatically submitted form (POST),
// depending on the services used. Read the data of the actual request method, never both merged.
$params = 'POST' === ($_SERVER['REQUEST_METHOD'] ?? 'GET') ? $_POST : $_GET;
try {
$response = $responseFactory->create($params);
} catch (InvalidResponseException $exception) {
// Not a GP webpay response for this shop: missing or malformed fields, or an unknown gateway in MD.
http_response_code(400);
echo 'Invalid payment response.';
return;
}
// Called only when both signatures are valid and PRCODE and SRCODE are 0.
$responseProvider->addOnSuccess(static function (ResponseInterface $response): void {
// 1. Find your payment attempt by $response->getOrderNumber() (the ORDERNUMBER you sent) and check
// that it belongs to $response->getGatewayKey(). Unknown attempt: reject, change nothing.
// 2. The response does not repeat the amount. It is bound to ORDERNUMBER by the signed request,
// so take the amount from your payment attempt, not from any received parameter.
// 3. Record the successful attempt atomically, for example
// UPDATE payment_attempt SET status = 'paid' WHERE id = ? AND status = 'pending'.
// 4. In the same transaction, guard fulfillment separately by an atomic unpaid-to-paid order transition
// or a unique fulfillment record keyed by order ID. Two attempts for the same order can both succeed;
// record additional successful attempts without fulfilling again. Replayed responses must also be harmless.
echo 'Payment accepted.';
});
// Called for every failure. The callback must accept GPWebPayException, the common parent type.
$responseProvider->addOnError(static function (GPWebPayException $exception, ResponseInterface $response): void {
if ($exception instanceof GPWebPayResultException) {
// Authentic response, but the payment was declined, cancelled or failed.
// Mark the payment attempt as failed (only if it is still pending) and let the customer try again.
echo 'Payment failed: ' . htmlspecialchars($exception->translate('en'), ENT_QUOTES, 'UTF-8');
return;
}
// SignerException: the signatures do not match, the data did not come from GP webpay
// or were changed. Change nothing, log the attempt and reject the request.
http_response_code(400);
echo 'Invalid payment response.';
});
// Verifies DIGEST and DIGEST1 first, then calls exactly one kind of callback.
$responseProvider->provide($response);
Note
For more examples, see tests/WorkflowTest.php and tests/ExamplesTest.php.