Quick start guide php-api

Quick start guide php-payment-api

Quick start guide php-payment-api

This article will introduce you to the basics of our heidelpay payment api for php. The api is designed for an easy integration of the heidelpay payment methods into your php application.

Note: The php-payment-api is based on heidelpay ngw api. For more details, please contact our support and ask for the “Heidelpay-developer_guide-Whitelabel_Interface” documentation.

Please have a look into the installation article before starting.

First of all, make sure that the composer autoloader is available in your application.
The simplest way is

require_once(__DIR__.'/vendor/autoload.php');

If your framework takes care of this you don’t need this.

Now you can create a instance of the payment method. For example:

 $payPal = new \Heidelpay\PhpPaymentApi\PaymentMethods\PayPalPaymentMethod();

Currently supported payment methods:

  • credit card
  • debit card
  • prepayment
  • Sofort
  • PayPal
  • direct debit
  • iDeal
  • Giropay
  • Przelewy24
  • PostFinance Card
  • PostFinance EFinance
  • EPS
  • invoice
  • invoice secured b2c
  • direct debit secured b2c
  • Santander invoice
  • Payolution invoice

Depending on the chosen payment method there are different transaction types that can be used. Please have a look inside the payment method documentation.

Transaction types:

The transaction types can be separated into 2 categories. Frontend and Backend. The implementation of the transaction types will be covered later in this document.

Frontend transaction types

This transaction types normally requires interaction with the shop customer and will be implemented in the store front.

  • authorize : performs risk management validations and saves the payment processing data for the later retrieval. For credit card transactions the payment amount is reserved on the credit card of the customer (in case the underlying acquirer supports this functionality). A following Capture with reference to the authorization will trigger the actual booking
  • debit : debits a customer’s account and credits the virtual account of the merchant
  • registration : initial registration of an account and/or customer. Later Debit (DB) or Credit (CD) transactions can always reference to a valid registration. Through this process no sensible end customer account information has to be stored within the merchant system.
  • authorizeOnRegistration : same as authorize but related to a given registration.
  • debitOnRegistration : same as debit but related to a given registration.

Backend transaction types

  • capture : captures a prior authorized amount from the customer`s account .
  • finalize : report shipment of an order. Necessary for secured invoice and direct debit.
  • reversal : reverses a authorized transaction before any money is transferred . The customer won`t see any transaction or cash flow on his account . A Reversal is solely possible within a connector specific cut-off time. Some connectors don`t support reversals at all.
  • refund : credits the account of the customer with a reference to a prior debit, receipt or capture  transaction. This can be done in order to refund an already processed debit transaction. The customer will always see two transactions on his statement.
  • rebill : debits the account of the end customer with a reference to a prior debit or capture transaction. Please note, that a rebill should not be used in case of a chargeback or for recurring payments. Depending on payment method and chargeback reason a rebill will probably fail. A rebill is usually used to add additional products to an already processed order.

Set up request data

The next step will be to set the necessary request  data. You can do so by call

$payPal->getRequest()->getName()->set('given', 'Paul');

The function getName() will return the current instance of the NameParameterGroup and  set('given', 'Paul'); will set the given name to Paul.

The heidelpay api supports a great amount of name spaces and parameters. Please have a look into the ParameterGroup documentation.

Helper functions

The heidelpay php-payment-api comes with a set of helper function. This will make it much easier for you to set up the request.

  • async : this helper can be used to set up frontend transaction requests like authorize and debit.
  • authentication : collects all necessary api authentication parameters.
  • basketData : collects all necessary basket details like amount and currency.
  • b2cSecured : collects the necessary customer data for secured invoice and direct debit.
  • customerAddress : collects all necessary customer data for a payment request.

For the given parameters, please have a look into the request object documentation.

Integration in your store backend

We will cover backend integration first, because it is easier to explain. As mentioned in the beginning you have to create a new instance of the payment method. All so called backend transaction are related to a frontend transaction. So you have to reference the first transaction by using the payment reference or identification.uniqueId. You can do so by calling getPaymentReferenceId on the response object. For example this could be the response of a PayPal authorize in frontend.

$heidelpayResponse = new Heidelpay\PhpPaymentApi\Response($_POST);
$paymentReference = $heidelpayResponse->getPaymentReferenceId();

Now starting with for example a capture of the PayPal authorization.

To simplify the code we will use …$data for the helper, this is also known as argument unpacking. See https://wiki.php.net/rfc/argument_unpacking

$payPal = new \Heidelpay\PhpPaymentApi\PaymentMethods\PayPalPaymentMethod();

//set authentication parameter<
$payPal->getRequest()->authentification(...$auth);

// set basket data<
$payPal->getRequest()->basketData(...$basket);

// Prepare and send PayPal capure request
$payPal->capture($paymentReference);

This is the request itself, which will be send directly when calling the capture function. Now you can check the result and save the payment reference.

if($payPal->getResponse()->isSuccess()) {
// please make sure that you check isPending as well before saving
// save($payPal->getResponse()->getPaymentReferenceId());
}
if ($payPal->getResponse()->isError()) {
print_r($payPal->getResponse()->getError());
}

Integration in your Store Front

Depending on the used payment method the “frontend transaction types” integration have to be separate in 3 kinds: Redirect, Form and Iframe.

Starting with the request itself, because it is pretty much the same. The difference here is this is a so called initial request to get the payment url. To simplify the code we will use …$data for the helper as before, this is also known as argument unpacking. See https://wiki.php.net/rfc/argument_unpacking

$payPal = new \Heidelpay\PhpPaymentApi\PaymentMethods\PayPalPaymentMethod();

//set authentication parameter
$payPal->getRequest()->authentification(...$authData);

// set basket data
$payPal->getRequest()->basketData(...$basketData);

// set customer data
$payPal->getRequest()->customerAddress(...$customer);

// set basket data
$payPal->getRequest()->async(...$async);

// Prepare and send PayPal debit request
$payPal->debit();

You will recognize that it looks pretty much the same as for a backend transaction. The difference is that the response object contains a redirect url.

 if ($payPal->getResponse()->isSuccess()) {
$url = $payPal->getResponse()->getPaymentFormUrl();
} else {
print_r($payPal->getResponse()->getError());
}

Now we will cover the different integrations.

Redirect

The simplest integration is the redirect. Most of the payment methods are able to use this.

 header('Location: '.$payPal->getResponse()->getPaymentFormUrl());

The customers browser will be redirected to the payment url.
It can be used for:

  • prepayment
  • Sofort
  • PayPal
  • Giropay
  • Przelewy24
  • PostFinance Card/EFinance
  • invoice.

In case on debitOnRegistration and authorizeOnRegistration, you can also use the redirect integration for

  • credit card
  • debit card
  • direct debit.

We will cover the payment response and the redirect of the customer to your application in the next chapter.

Form

Payment methods like direct debit (secured and unsecured), iDeal, EPS, invoice secured and Santander invoice needs additional payment information from the shop customer. Like iban, birth date and so on. For example you can integrate direct debit like this.

<html>
<head>
<title>Direct Debit registration example</title>
</head>
<body>
<form method="post" class="formular" 
action="<?php if ($directDebit->getResponse()->isSuccess()) 
{ 
echo $directDebit->getResponse()->getPaymentFormUrl(); 
} ?>" id="paymentFrameForm">
Holder:<input type="text" name="ACCOUNT.HOLDER" value="" /><br/>
IBan:<input type="text" name="ACCOUNT.IBAN" value="" /><br/>
<button type="submit">Submit data</button></td>
</form>
</body>
</html>

Please have a look into the example folder, there is an example for each payment method.

We will cover the payment response and the redirect of the customer to your application in the next chapter.

IFrame

Because of payment card industry standards, the payment methods credit card and debit card needs to be integrated by using the “heidelpay payment frame”. We will cover the integration here shortly if you need to dive deeper please ask our support for the “Heidelpay-developer_guide-Whitelabel_Interface” documentation.

The request itself is a little bit different.

$creditCard->registration(
"https://dev.heidelpay.de", //uri of your application
"FALSE", //PreventAsyncRedirect
"https://dev.heidelpay.de/style.css" //CSSPath
);

This first 2 parameters are required for the heidelpay payment frame. The integration in your store front could be like this.

<html>
<head>
<title>Credit card registration example</title>
</head>
<body>
<form method="post" class="formular" id="paymentFrameForm">
<?php if ($creditCard->getResponse()->isSuccess()) {

  echo '<iframe id="paymentIframe"   
   src="'.$creditCard->getResponse()->getPaymentFormUrl() . '"  
   style="height:250px;">
   </iframe><br />';
} else {
    print_r($creditCard->getResponse()->getError());
}?>
<button type="submit">Submit data</button>
</form>
<script type="text/javascript" src="./js/creditCardFrame.js"></script>
</body>
</html>

You can find the javascipt in our example folder. The  javascript in your shop will interacted with the iframe using html5 postMessage. So it is possible for you to listen on any click in your shop to submit the from inside the payment frame. This give you the freedom to have only one button inside you shop to save or submit every payment method.

The receiveMessage function will be called if your customer put incorrect data in the iframe or if you set prevent PreventAsyncRedirect to true.

We will cover the payment response and the redirect of the customer to your application in the next chapter.

Response and customer redirect

First of all – what is a response?

The payment server will send you application the result of the transaction. This is the case for each “frontend transaction type”.

Important: The response will be send directly (server to server) from heidelpay payment system to your application. So please make sure that your application is reachable from the Internet (no .htacces,  no ip filter and correct dns).

The Target of the response is the url you have defined as the second parameter of the async helper.

$sofort->getRequest()->async(
        'EN', // Language code for the Frame
        'https://dev.heidelpay.de/HeidelpayResponse.php'
);

The response will be send using post.

Now you can start creating this response controller and  a instance of the response object to hand over the post parameters.

$heidelpayResponse = new Heidelpay\PhpPaymentApi\Response($_POST);

Note: If your application uses dependency injection you can inject the response object without parameter and call

$heidelpayResponse->splitArray($_POST);

instead.

Validate the response

For security reasons please validate the response to make sure that the request and the answer are from the same source. This will protect your application against so called brute force response attacks. You can do so by calling

try {
    $heidelpayResponse->verifySecurityHash($secretPass, $orderId);
} catch (\Exception $e) {
/* If the verification does not match this can mean some 
* kind of manipulation or miss configuration. 
* So you can log $e->getMessage() for debugging.
*/
return;
}

The request will be signed with a sha512 hash base on the reference Id of your application and a secret from your application. Please make sure that the secret will never be send in the request.

Saving response and generating the order

First thing to mention here is the response object has 3 methods isSuccess(), isPending() and isError(). Depending on your order process and the used payment method you should use for example another status than “paid” for transaction which are pending.

Saving the response and generating the order is up to your application. We will not cover this here but we want to give you some tips which you should be aware of.

First thing is, you will not receve the response from your customer’s browser. As we mention it is a server to server response. So using the browser session of your customer for the response is a bad idea. This can lead to session hijacking and depending from your php settings, php will destroy the session.

If your shop system or application can only handle the order process with the customer session. We strongly recommend to just save the payment response on your response controller. Then redirect the costumers browser to your shop, load the response from
your database and process the order.

This page will normally not be rendered  in your browser, if this happens the payment does not have a redirect url from your application. To debug this please log the steps of your response controller. Print some content will not help you.

Redirect the customer back to your application

After saving the response to your database the last thing would be to redirect the customers browser to your system. The payment server expects a blank page with only the url for the customer redirect.

You can use different urls in case of error and success, this is up to your application design.

It is important to only show the encoded url. Please remove any html content from this page. If your are not sure that your url is encoded use php rawurlencode. http://php.net/manual/de/function.rawurlencode.php

print rawurlencode(
       Mage::getUrl('checkout/cart', array('_secure' => true))
);

If everything works as expected the customer should be redirect to this url after the transaction.

Error handling

As mentioned above there is an isError() function for the response object. You can also get the error message and code by using getError()

if ($sofort->getResponse()->isError()) {
    $error = $sofort->getResponse()->getError();
}

The error message is designed for the merchant and we recommend you to not use it for your customer.

You can create customer message based on the error code. We have a composer extension for this as well, please have a look here.

Questions and support

If you need help with your integration or have problems with it. Please contact us using twitter, github or mail (development@).

For Transaction related issues or questions please contact our support. (support@)

If you have feature ideas please open a github issue with “idea:”.

Thanks