PHP code example of swedbank-spp / swedbank-payment-portal

1. Go to this page and download the library: Download swedbank-spp/swedbank-payment-portal library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

swedbank-spp / swedbank-payment-portal example snippets


function someControllerAction() {  // this method must be called whenever Notification URL is accessed.
      $xml = file_get_contents("php://input"); // POST raw data
      try {
          $spp->getBankLinkGateway()->handleNotification($xm);
      } catch (\Exception $e) {
          // here log any exceptions if occurs, because if you will not respond
          // with “<Response>OK</Response>” SPP will repeatedly submit notifications.
      }
      echo "<Response>OK</Response>";
}

use SwedbankPaymentPortal\Options\CommunicationOptions;
use SwedbankPaymentPortal\Options\ServiceOptions;
use SwedbankPaymentPortal\SharedEntity\Authentication;
use SwedbankPaymentPortal\SwedbankPaymentPortal;

$options = new ServiceOptions(
    new CommunicationOptions('https://accreditation.datacash.com/Transaction/acq_a'),
    new Authentication( 'login', 'password' )
);

$spp = new SwedbankPaymentPortal($options);

$paypal   = $spp->getPayPalGateway();
$banklink = $spp->getBankLinkGateway();
$hps      = $spp->getPaymentCardHostedPagesGateway();

SwedbankPaymentPortal::init(ServiceOptions $options); // you must call this once to initialize library
$spp = SwedbankPaymentPortal::getInstance();  // method will return an object of SwedbankPaymentPortal.

$spp->getBankLinkGateway()->handlePendingTransaction($orderId);
 $spp->getPayPalGateway()->handlePendingTransaction($orderId);
 $spp->getPaymentCardHostedPagesGateway()->hpsQuery($orderId);

public function handleFinishedTransaction(
   TransactionResult $transactionResult,
   TransactionFrame $transactionFrame,
   PaymentCardTransactionData $paymentCardTransactionData = null
);

$spp->getBankLinkGateway()->initPayment(
    $purchaseRequest,
    UrlCallback::create(“http://yourdomain.com/some_secret_complete_handler?order_id={$orderId}”)
);

 $purchaseAmount = 1500; // 15 Eur 00 ct
$merchantReferenceId = "Invoice01234";

$purchaseRequest = (new PurchaseBuilder())
    ->setDescription("SPP demoshop Order $merchantReferenceId")
    ->setAmountValue($purchaseAmount)
    ->setAmountExponent(2)
    ->setAmountCurrencyCode(978)// for EUR
    ->setConsumerEmail("[email protected]")
    ->setServiceType(ServiceType::swdBank())
    ->setPaymentMethod(PaymentMethod::swedbank())
    ->setSuccessUrl("SPP") // see chapter “Success / Failure URL Handling” for more info
    ->setFailureUrl("SPP")
    ->setMerchantReference($merchantReferenceId)
    ->setLanguage("lt")
    ->setPageSetId(1)
    ->getPurchaseRequest();

    $response = $spp->getBankLinkGateway()->initPayment(
        $purchaseRequest,
        new Swedbank_Ordering_Handler_PaymentCompletedCallback(
            $merchantReferenceId
        )
    );
 

use SwedbankPaymentPortal\BankLink\CommunicationEntity\HPSQueryResponse\HPSQueryResponse;
use SwedbankPaymentPortal\BankLink\CommunicationEntity\NotificationQuery\ServerNotification;
use SwedbankPaymentPortal\CallbackInterface;
use SwedbankPaymentPortal\CC\PaymentCardTransactionData;
use SwedbankPaymentPortal\SharedEntity\Type\TransactionResult;
use SwedbankPaymentPortal\Transaction\TransactionFrame;

class Swedbank_Ordering_Handler_PaymentCompletedCallback implements CallbackInterface
{

    private $merchantReferenceId;

    public function __construct($merchantReferenceId)
    {
        $this->merchantReferenceId = $merchantReferenceId;
    }

    /**
     * Method for handling finished transaction which ended because of the specified response status.
     *
     * @param TransactionResult         $status
     * @param TransactionFrame          $transactionFrame
     * @param PaymentCardTransactionData $creditCardTransactionData
     */
    public function handleFinishedTransaction(TransactionResult $status, 
         TransactionFrame $transactionFrame, 
         PaymentCardTransactionData $creditCardTransactionData = null)
    {
        if ($status == TransactionResult::success()) {
            // success no you can put flag payment done
        } else if ($status == TransactionResult::failure()) {
            // failure. Do some action here
        } else {
            // unfinished payment
        }
	// This is only for debug. You can log into file if needed.
        mail('[email protected]', 
	    'DONE', print_r($status, true).print_r($transactionFrame, true).print_r($creditCardTransactionData, true)); 
	    
    }

    public function serialize()
    {
        return json_encode(
            [
                'merchantReferenceId' => $this->merchantReferenceId
            ]
        );
    }
                    
    public function unserialize($serialized)
    {
        $data = json_decode($serialized);

        $this->merchantReferenceId = $data->merchantReferenceId;
    }
}
 

 // in autoloader and library needed for HPS payment
ons;
use SwedbankPaymentPortal\Options\ServiceOptions;
use SwedbankPaymentPortal\SharedEntity\Authentication;
use SwedbankPaymentPortal\SwedbankPaymentPortal;
use SwedbankPaymentPortal\SharedEntity\Amount;
use SwedbankPaymentPortal\CC\HPSCommunicationEntity\SetupRequest\SetupRequest;
use SwedbankPaymentPortal\CC\HPSCommunicationEntity\SetupRequest\Transaction;
use SwedbankPaymentPortal\CC\Type\ScreeningAction;
use SwedbankPaymentPortal\CC\Type\TransactionChannel;
use SwedbankPaymentPortal\CC\HPSCommunicationEntity\SetupRequest\Transaction\TxnDetails;
use SwedbankPaymentPortal\CC\HPSCommunicationEntity\SetupRequest\Transaction\ThreeDSecure;
use SwedbankPaymentPortal\CC\HPSCommunicationEntity\SetupRequest\Transaction\CardTxn;

ngAction::preAuthorization(), new Transaction\MerchantConfiguration(
        TransactionChannel::web(), 'Vilnius' //Merchant location (city)
        ), new Transaction\CustomerDetails(
        new Transaction\BillingDetails(// Customer details
        'Mr', // title
        'Name Surname', // Name and surname
        'Zip0000', // Post code
        'Street address', // address line 1
        '', // address line 2
        'London', // City
        'UK' // Country
        ), new Transaction\PersonalDetails(// Personal details
        'Name', // Required, Card holder name
        'Surname', // Required. Card holder surname
        '+3705555555' // Required. Card holder phone
        ), new Transaction\ShippingDetails(// Shipping details
        'Mr', // title
        'Name', // name
        'Surname', // surname
        'Street address', // address line 1
        '', // address line 2
        'City', // City
        'UK', // Country
        'Zip0000' // Post code
        ), new Transaction\RiskDetails(
        '127.15.21.55', // Required. Card holder IP address
        '[email protected]' // Required. Card holder email
        )
        )
);

$txnDetails = new TxnDetails(
        $riskAction, $merchantReferenceId, new Amount($purchaseAmount), new ThreeDSecure(
        'Order nr: ' . $merchantReferenceId, 'http://sppdemoshop.eu/', new \DateTime()
        )
);

$hpsTxn = new Transaction\HPSTxn(
        'http://sppdemoshop.eu/test/hps_confirm.php?way=expiry&order_id=' . $merchantReferenceId, // expire url
        'http://sppdemoshop.eu/test/hps_confirm.php?way=confirmed&order_id=' . $merchantReferenceId, // return url
        'http://sppdemoshop.eu/test/hps_confirm.php?way=cancelled&order_id=' . $merchantReferenceId, // error url
        164, // Page set ID
        // Firs field to show in card input form Name and Surname field. 
        //Firs parameter goes as string 'show' or null. Second field is url for back button in card input form.
        new Transaction\DynamicData(null, 'http://sppdemoshop.eu/')
);

$transaction = new Transaction($txnDetails, $hpsTxn, new CardTxn());
$setupRequest = new SetupRequest($auth, $transaction);
$response = $spp->getPaymentCardHostedPagesGateway()->initPayment(
        $setupRequest,
        new Swedbank_Ordering_Handler_PaymentCompletedCallback($merchantReferenceId)
);
$url = $response->getCustomerRedirectUrl(); // Getting redirect url
header('Location: ' . $url); // redirecting card holder to card input form.
 

namespace SwedbankPaymentPortal;

s\CommunicationOptions;
use SwedbankPaymentPortal\Options\ServiceOptions;
use SwedbankPaymentPortal\SharedEntity\Authentication;
use SwedbankPaymentPortal\SwedbankPaymentPortal;

https://accreditation.datacash.com/Transaction/acq_a' //this is test environment 
		// for production/live use this URL: https://mars.transaction.datacash.com/Transaction
      ),
   $auth
  );
  SwedbankPaymentPortal::init($options);  // <- library  initiation
  $spp = SwedbankPaymentPortal::getInstance();  // <- library usage

  $rez = $spp->getPaymentCardHostedPagesGateway()->handlePendingTransaction($orderId); 
  // now you can show user "thank you for your payment, but don't put flag 
  //flag need to put inside callback
  
  echo 'Thank you';
} else if ($way == 'expiry'){
	echo 'Session expired';
	// do same logic if seesion expired
} else { // cancelled
	echo 'Payment cancelled';
	// do some action for cancel logic
}

namespace SwedbankPaymentPortal;
// in autoloader and library needed for HPS payment
ptions\ServiceOptions;
use SwedbankPaymentPortal\SharedEntity\Authentication;
use SwedbankPaymentPortal\SwedbankPaymentPortal;

use SwedbankPaymentPortal\SharedEntity\Amount;
use SwedbankPaymentPortal\CC\HPSCommunicationEntity\SetupRequest\SetupRequest;
use SwedbankPaymentPortal\CC\HPSCommunicationEntity\SetupRequest\Transaction;
use SwedbankPaymentPortal\CC\Type\ScreeningAction;
use SwedbankPaymentPortal\CC\Type\TransactionChannel;
use SwedbankPaymentPortal\CC\HPSCommunicationEntity\SetupRequest\Transaction\TxnDetails;
use SwedbankPaymentPortal\CC\HPSCommunicationEntity\SetupRequest\Transaction\ThreeDSecure;
use SwedbankPaymentPortal\CC\HPSCommunicationEntity\SetupRequest\Transaction\CardTxn;


$auth = new Authentication('8*****','********'); // VtID and password
// Generating unique merchant reference. To generate merchant reference 
//please use your one logic. This is only example.
$merchantReferenceId = 'ID235r'.strtotime('now'); 
$purchaseAmount = '4.99'; // Euro and cents needs to be separated by dot.  

$options = new ServiceOptions(
    new CommunicationOptions(
        'https://accreditation.datacash.com/Transaction/acq_a' //this is test environment 
		// for production/live use this URL: https://mars.transaction.datacash.com/Transaction
    ),
   $auth
);

SwedbankPaymentPortal::init($options);  // <- library  initiation
$spp = SwedbankPaymentPortal::getInstance();  // <- library usage

$riskAction = new Transaction\Action(
    ScreeningAction::preAuthorization(),
    new Transaction\MerchantConfiguration(
        TransactionChannel::web(),
        'Vilnius' //Merchant location (city)
    ),
    new Transaction\CustomerDetails( 
        new Transaction\BillingDetails( // Customer details
            'Mr', // title
            'Name Surname', // Name and surname
            'Zip0000', // Post code
            'Street address', // address line 1
            '', // address line 2
            'London', // City
            'UK' // Country
        ),
        new Transaction\PersonalDetails( // Personal details
            'Name', // Required, Card holder name
            'Surname', // Required. Card holder surname
            '+3705555555' // Required. Card holder phone
        ),

        new Transaction\ShippingDetails( // Shipping details
            'Mr', // title
            'Name', // name
            'Surname', // surname
            'Street address', // address line 1
            '', // address line 2
            'City', // City
            'UK', // Country
            'Zip0000' // Post code
        ),

        new Transaction\RiskDetails( 
            '127.15.21.55', // Required. Card holder IP address
            '[email protected]' // Required. Card holder email
        )
    )
);

$txnDetails = new TxnDetails(
    $riskAction,
    $merchantReferenceId,
    new Amount($purchaseAmount),
    new ThreeDSecure(
        'Order nr: ' . $merchantReferenceId,
        'http://sppdemoshop.eu/',
        new \DateTime()
    )
);
	 
$hpsTxn = new Transaction\HPSTxn(
    'http://sppdemoshop.eu/confirm.php?way=expiry&order_id='.$merchantReferenceId, // expire url
       'http://sppdemoshop.eu/confirm.php?way=confirmed&order_id='.$merchantReferenceId, // return url
       'http://sppdemoshop.eu/confirm.php?way=cancelled&order_id='.$merchantReferenceId, // error url
    164, // Page set ID
    // Firs field to show in card input form Name and Surname field. 
    //Firs parameter goes as string 'show' or null. Second field is url for back button in card input form.
    new Transaction\DynamicData(null, 'http://sppdemoshop.eu/') 
);

$transaction  = new Transaction($txnDetails, $hpsTxn, new CardTxn());
$setupRequest = new SetupRequest($auth, $transaction);
$response = $spp->getPaymentCardHostedPagesGateway()->initPayment(
   $setupRequest,
   // This url card holder won't be redirected. This url will be called by cronjob to finalize transaction.
  UrlCallback::create("http://sppdemoshop.eu/secretprocesor.php?order_id={$merchantReferenceId}") 
);
$url=$response->getCustomerRedirectUrl(); // Getting redirect url
header('Location: '.$url); // redirecting card holder to card input form.
die();
 



use SwedbankPaymentPortal\Options\CommunicationOptions;
use SwedbankPaymentPortal\Options\ServiceOptions;
use SwedbankPaymentPortal\SharedEntity\Authentication;
use SwedbankPaymentPortal\SwedbankPaymentPortal;

$orderId = $_GET['order_id'];
$way  = $_GET['way'];

if ($way == 'confirmed'){
  $auth = new Authentication('8******','******');
  $options = new ServiceOptions(
      new CommunicationOptions(
        'https://accreditation.datacash.com/Transaction/acq_a' //this is test environment 
		// for production/live use this URL: https://mars.transaction.datacash.com/Transaction
      ),
   $auth
  );
  SwedbankPaymentPortal::init($options);  // <- library  initiation
  $spp = SwedbankPaymentPortal::getInstance();  // <- library usage

  $rez = $spp->getPaymentCardHostedPagesGateway()->handlePendingTransaction($orderId); 
  // now you can show user "thank you for your payment, but don't put flag 
  //what this payment is done. This is done in secretprocesor.php file
  
  echo 'Thank you';
} else if ($way == 'expiry'){
	// do same logic if seesion expired
} else { // cancelled
	// do some action for cancel logic
}
 

 $orderId = $_GET['order_id'];
 
 if($_POST['status'] === 'SUCCESS') {
		//Do action for success. This is final confirmations of success
		// now you can set flag what payment is success
	} else if($_POST['status'] === 'FAIL') {
		// Do action if failed
	} else if($_POST['status'] === 'UNFINISHED'){
		// Do action if unfinished
	} else {
	    // log this attempt 
	}
    
 

// in autoloader and library needed for banklink payment

use SwedbankPaymentPortal\Options\ServiceOptions;
use SwedbankPaymentPortal\SharedEntity\Authentication;
use SwedbankPaymentPortal\SwedbankPaymentPortal;

use SwedbankPaymentPortal\BankLink\PurchaseBuilder;
use SwedbankPaymentPortal\BankLink\CommunicationEntity\Type\PaymentMethod;
use SwedbankPaymentPortal\BankLink\CommunicationEntity\Type\ServiceType;

 // for production/live use this URL: https://mars.transaction.datacash.com/Transaction
        ), $auth
);

SwedbankPaymentPortal::init($options);  // <- library  initiation
$spp = SwedbankPaymentPortal::getInstance();  // <- library usage


$purchaseAmount = 1500; // 15 Eur 00 ct


$purchaseRequest = (new PurchaseBuilder())
    ->setDescription("SPP demoshop Order $merchantReferenceId")
    ->setAmountValue($purchaseAmount)
    ->setAmountExponent(2)
    ->setAmountCurrencyCode(978)// for EUR
    ->setConsumerEmail("[email protected]")
    /*
ServiceType::swdBank() - SWEDBANK AB (SWEDEN)
ServiceType::nrdSwd() - NORDEA BANK AB (SWEDEN)
ServiceType::sebSwd() - SKANDINAVISKA ENSKILDA BANKEN AB (SWEDEN)
ServiceType::estBank() - SWEDBANK AS (ESTONIA)
ServiceType::sebEst() - SEB AS Pank (ESTONIA)
ServiceType::nrdEst() - Nordea Bank AB Estonia Branch (ESTONIA)
ServiceType::ltvBank() - SWEDBANK AS (LATVIA)
ServiceType::sebLtv() - SEB AS banka (LATVIA)
ServiceType::litBank() - SWEDBANK AB (LITHUANIA)
ServiceType::sebLit() - SEB AB bankas (LITHUANIA)
ServiceType::nrdLit() - NORDEA BANK AB LITHUANIA BRANCH (LITHUANIA)
*/        
    ->setServiceType(ServiceType::litBank())
/*
PaymentMethod::swedbank() - SWEDBANK AB (SWEDEN)
PaymentMethod::nordea() - NORDEA BANK AB (SWEDEN)
PaymentMethod::svenska() - SVENSKA HANDELSBANKEN AB (SWEDEN)
PaymentMethod::seb() - SKANDINAVISKA ENSKILDA BANKEN AB (SWEDEN)
PaymentMethod::swedbank() - SWEDBANK AS (ESTONIA)
PaymentMethod::seb() - SEB AS Pank (ESTONIA)
PaymentMethod::nordea() - Nordea Bank AB Estonia Branch (ESTONIA)
PaymentMethod::swedbank() - SWEDBANK AS (LATVIA)
PaymentMethod::seb() - SEB AS banka (LATVIA)
PaymentMethod::citadele() - AS CITADELE BANKA (LATVIA)
PaymentMethod::swedbank() - SWEDBANK AB (LITHUANIA)
PaymentMethod::seb() - SEB AB bankas (LITHUANIA)
PaymentMethod::dnb() - AB DNB BANKAS (LITHUANIA)
PaymentMethod::nordea() - NORDEA BANK AB LITHUANIA BRANCH (LITHUANIA)
PaymentMethod::danske() - DANSKE BANK AS LITHUANIA BRANCH (LITHUANIA)
*/
    ->setPaymentMethod(PaymentMethod::swedbank())
    ->setSuccessUrl('http://sppdemoshop.eu/test/banklink_confirm.php?way=confirmed&order_id=' . $merchantReferenceId) // see chapter “Success / Failure URL Handling” for more info
    ->setFailureUrl('http://sppdemoshop.eu/test/banklink_confirm.php?way=cancelled&order_id=' . $merchantReferenceId)
    ->setMerchantReference($merchantReferenceId)
    ->setLanguage("lt")
    ->setPageSetId(1) // Always 1
    ->getPurchaseRequest();

    $response = $spp->getBankLinkGateway()->initPayment(
        $purchaseRequest,
        new Swedbank_Ordering_Handler_PaymentCompletedCallback(
            $merchantReferenceId
        )
    );

$url = $response->getCustomerRedirectUrl(); // Getting redirect url
header('Location: ' . $url); // redirecting card holder to card input form.

use SwedbankPaymentPortal\BankLink\CommunicationEntity\HPSQueryResponse\HPSQueryResponse;
use SwedbankPaymentPortal\BankLink\CommunicationEntity\NotificationQuery\ServerNotification;
use SwedbankPaymentPortal\CallbackInterface;
use SwedbankPaymentPortal\CC\PaymentCardTransactionData;
use SwedbankPaymentPortal\SharedEntity\Type\TransactionResult;
use SwedbankPaymentPortal\Transaction\TransactionFrame;

class Swedbank_Ordering_Handler_PaymentCompletedCallback implements CallbackInterface
{

    private $merchantReferenceId;

    public function __construct($merchantReferenceId)
    {
        $this->merchantReferenceId = $merchantReferenceId;
    }

    /**
     * Method for handling finished transaction which ended because of the specified response status.
     *
     * @param TransactionResult         $status
     * @param TransactionFrame          $transactionFrame
     * @param PaymentCardTransactionData $creditCardTransactionData
     */
    public function handleFinishedTransaction(TransactionResult $status, 
         TransactionFrame $transactionFrame, 
         PaymentCardTransactionData $creditCardTransactionData = null)
    {
        if ($status == TransactionResult::success()) {
            // success no you can put flag payment done
        } else if ($status == TransactionResult::failure()) {
            // failure. Do some action here
        } else {
            // unfinished payment
        }
	// This is only for debug. You can log into file if needed.
        mail('[email protected]', 
	    'DONE', print_r($status, true).print_r($transactionFrame, true).print_r($creditCardTransactionData, true)); 
	    
    }

    public function serialize()
    {
        return json_encode(
            [
                'merchantReferenceId' => $this->merchantReferenceId
            ]
        );
    }
                    
    public function unserialize($serialized)
    {
        $data = json_decode($serialized);

        $this->merchantReferenceId = $data->merchantReferenceId;
    }
}

namespace SwedbankPaymentPortal;

s\CommunicationOptions;
use SwedbankPaymentPortal\Options\ServiceOptions;
use SwedbankPaymentPortal\SharedEntity\Authentication;
use SwedbankPaymentPortal\SwedbankPaymentPortal;

accreditation.datacash.com/Transaction/acq_a' //this is test environment 
		// for production/live use this URL: https://mars.transaction.datacash.com/Transaction
      ),
   $auth
  );
  SwedbankPaymentPortal::init($options);  // <- library  initiation
  $spp = SwedbankPaymentPortal::getInstance();  // <- library usage

  $rez = $spp->getBankLinkGateway()->handlePendingTransaction($orderId); 
  // now you can show user "thank you for your payment, but don't put flag 
  //flag need to put inside callback
  
  echo 'Thank you';
} else { // cancelled
	echo 'Payment cancelled';
	// do some action for cancel logic
}

// clude dirname(__FILE__) . '/../SwedbankPaymentPortal/vendor/autoload.php';

use SwedbankPaymentPortal\Options\CommunicationOptions;
use SwedbankPaymentPortal\Options\ServiceOptions;
use SwedbankPaymentPortal\SharedEntity\Authentication;
use SwedbankPaymentPortal\SwedbankPaymentPortal;
use SwedbankPaymentPortal\SharedEntity\Amount;

use SwedbankPaymentPortal\PayPal\CommunicationEntity\ShippingAddress;
use SwedbankPaymentPortal\PayPal\CommunicationEntity\SetExpressCheckoutRequest\Transaction;
use SwedbankPaymentPortal\PayPal\CommunicationEntity\SetExpressCheckoutRequest\Transaction\TxnDetails;
use SwedbankPaymentPortal\PayPal\CommunicationEntity\SetExpressCheckoutRequest\SetExpressCheckoutRequest;
use SwedbankPaymentPortal\PayPal\Type\PayPalBool;


tPortal::getInstance();  // <- library usage

$payPalTxn = new Transaction\PayPalTxn(
        null,
    'ABCQWH', // Custom
    'PayPal test payment', //Description
    '[email protected]', //Email
    $merchantReference, // Invoice number
    'LT', // Locale code
    $purchaseAmount, // Max amount
    PayPalBool::false(),// No Shipping
    PayPalBool::false(), // Overide address
    PayPalBool::false(), // Requere confirmed shipping
    'http://sppdemoshop.eu/test/paypal_confirm.php?way=confirmed&order_id=' . $merchantReferenceId, //Return URL. See chapter “Success / Failure URL Handling” for more info
    'http://sppdemoshop.eu/test/paypal_confirm.php?way=cancelled&order_id=' . $merchantReferenceId // error url
);

$txnDetails  = new TxnDetails(new Amount($purchaseAmount), $merchantReferenceId);
$transaction = new Transaction($txnDetails, $payPalTxn);
$request = new SetExpressCheckoutRequest($transaction, null);

$response = $spp->getPayPalGateway()->initPayment(
    $request,
    new Swedbank_Ordering_Handler_PaymentCompletedCallback(
        $merchantReferenceId
    )
);

$url = $response->getCustomerRedirectUrl(false); // Getting redirect url. False - if test enviroment, true - if live enviroment

header('Location: ' . $url); // redirecting card holder to card input form.




use SwedbankPaymentPortal\Options\CommunicationOptions;
use SwedbankPaymentPortal\Options\ServiceOptions;
use SwedbankPaymentPortal\SharedEntity\Authentication;
use SwedbankPaymentPortal\SwedbankPaymentPortal;
use SwedbankPaymentPortal\SharedEntity\Amount;
use SwedbankPaymentPortal\PayPal\CommunicationEntity\ShippingAddress;
use SwedbankPaymentPortal\PayPal\CommunicationEntity\SetExpressCheckoutRequest\Transaction;
use SwedbankPaymentPortal\PayPal\CommunicationEntity\SetExpressCheckoutRequest\Transaction\TxnDetails;
use SwedbankPaymentPortal\PayPal\CommunicationEntity\SetExpressCheckoutRequest\SetExpressCheckoutRequest;
use SwedbankPaymentPortal\PayPal\Type\PayPalBool;

  // now you can show user "thank you for your payment, but don't put flag 
  //flag need to put inside callback
  
  echo 'Thank you';
} else { // cancelled
	echo 'Payment cancelled';
	// do some action for cancel logic
}




$options = new ServiceOptions(
      new CommunicationOptions(
        'https://accreditation.datacash.com/Transaction/acq_a' //this is test environment 
		// for production/live use this URL: https://mars.transaction.datacash.com/Transaction
      ),
   $auth, new Swedbank_Client_Logger()
  );

use SwedbankPaymentPortal\Logger\LoggerInterface;

class Swedbank_Client_Logger implements LoggerInterface
{
    public function __construct()
    {
    }

    /**
     * @param string                                                                                                                                                                                                                                                                                                                                                 $requestXml
     * @param string                                                                                                                                                                                                                                                                                                                                                 $responseXml
     * @param object|\SwedbankPaymentPortal\BankLink\CommunicationEntity\HPSQueryRequest\HPSQueryRequest|\SwedbankPaymentPortal\BankLink\CommunicationEntity\PaymentAttemptRequest\PaymentAttemptRequest|\SwedbankPaymentPortal\BankLink\CommunicationEntity\PurchaseRequest\PurchaseRequest|\SwedbankPaymentPortal\BankLink\CommunicationEntity\TransactionQueryRequest\TransactionQueryRequest $requestObject
     * @param object|\SwedbankPaymentPortal\BankLink\CommunicationEntity\PaymentAttemptResponse\PaymentAttemptResponse|\SwedbankPaymentPortal\BankLink\CommunicationEntity\PurchaseResponse\PurchaseResponse|\SwedbankPaymentPortal\BankLink\CommunicationEntity\TransactionQueryResponse\TransactionQueryResponse|\SwedbankPaymentPortal\SharedEntity\HPSQueryResponse\HPSQueryResponse         $responseObject
     * @param \SwedbankPaymentPortal\SharedEntity\Type\TransportType                                                                                                                                                                                                                                                                                                        $type
     */
    public function logData(
        $requestXml,
        $responseXml,
        $requestObject,
        $responseObject,
        \SwedbankPaymentPortal\SharedEntity\Type\TransportType $type
    ) {

        $requestType = $type->id();
        $request = $this->prettyXml($requestXml);
        $response = $responseXml;

		file_put_contents(dirname(__FILE__) . '/../../../storage/logs/swedbank.log', "\n-----\n$requestType\n$request\n\n$response\n", FILE_APPEND | LOCK_EX);
    }

    /**
     * Method formats given XML into pretty readable format
     *
     * @param $xml
     *
     * @return string
     */
    private function prettyXml($xml)
    {
        $doc = new DomDocument('1.0');
        $doc->loadXML($xml);
        $doc->preserveWhiteSpace = false;
        $doc->formatOutput       = true;

        $prettyXml = $doc->saveXML();

        return $prettyXml;
    }
}


namespace SwedbankPaymentPortal;
// in autoloader and library needed for HPS payment
tions\ServiceOptions;
use SwedbankPaymentPortal\SharedEntity\Authentication;
use SwedbankPaymentPortal\SwedbankPaymentPortal;


$auth = new Authentication('xxxxxxxxxx','xxxxxxxxxx'); // VtID and password

//Merchant referance was used for payment
$merchantReferenceId = 'XXXXXXXXXXX'; 

$options = new ServiceOptions(
   new CommunicationOptions(
       'https://accreditation.datacash.com/Transaction/acq_a' //this is test environment 
   	// for production/live use this URL: https://mars.transaction.datacash.com/Transaction
   ),
  $auth
);

SwedbankPaymentPortal::init($options);  // <- library  initiation
$spp = SwedbankPaymentPortal::getInstance();  // <- library usage

$response = $spp->getPaymentCardHostedPagesGateway()->query($merchantReferenceId);





namespace SwedbankPaymentPortal;
// in autoloader and library needed for HPS payment
tions\ServiceOptions;
use SwedbankPaymentPortal\SharedEntity\Authentication;
use SwedbankPaymentPortal\SwedbankPaymentPortal;


$auth = new Authentication('xxxxxxxxxx','xxxxxxxxxx'); // VtID and password

//Merchant referance was used for payment
$merchantReferenceId = 'XXXXXXXXXXX'; 

$options = new ServiceOptions(
   new CommunicationOptions(
       'https://accreditation.datacash.com/Transaction/acq_a' //this is test environment 
   	// for production/live use this URL: https://mars.transaction.datacash.com/Transaction
   ),
  $auth
);

SwedbankPaymentPortal::init($options);  // <- library  initiation
$spp = SwedbankPaymentPortal::getInstance();  // <- library usage

$response = $spp->getPaymentCardHostedPagesGateway()->query($merchantReferenceId);

//var_dump($response);
$response = $spp->getPaymentCardHostedPagesGateway()->hpsCancel($response['QueryTxnResult']['datacash_reference']);
//check if cancell was successful if not do refund

//$response = $spp->getPaymentCardHostedPagesGateway()->hpsRefund($response['QueryTxnResult']['datacash_reference'], '3.23');




// in autoloader and library needed for HPS payment
ons;
use SwedbankPaymentPortal\Options\ServiceOptions;
use SwedbankPaymentPortal\SharedEntity\Authentication;
use SwedbankPaymentPortal\SwedbankPaymentPortal;


$auth = new Authentication('***********','***********'); // VtID and password

//Merchant referance was used for payment
$merchantReferenceId = 'XXXXXXXXXXXXXXX';

$options = new ServiceOptions(
    new CommunicationOptions(
        'https://accreditation.datacash.com/Transaction/acq_a' //this is test environment
    // for production/live use this URL: https://mars.transaction.datacash.com/Transaction
    ),
    $auth
);

SwedbankPaymentPortal::init($options);  // <- library  initiation
$spp = SwedbankPaymentPortal::getInstance();  // <- library usage

$response = $spp->getPaymentCardHostedPagesGateway()->query($merchantReferenceId);

$ref = $response['QueryTxnResult']['datacash_reference'];
var_dump($ref); //string(16) "3400900025177762"

$amount = $response['QueryTxnResult']['amount'];
var_dump($amount); //string(5) "10.00"

//
$response = $spp->getPaymentCardHostedPagesGateway()->hpsRefund($ref, '0.50');
//Read parameter "status" if status == ACCEPTED then OK else failed
var_dump($response);
/*
 array(10) {
  ["@attributes"]=>
  array(1) {
    ["version"]=>
    string(1) "2"
  }
  ["MAC"]=>
  array(1) {
    ["outcome"]=>
    string(6) "ACCEPT"
  }
  ["acquirer"]=>
  string(22) "Swedbank Baltic Latvia"
  ["datacash_reference"]=>
  string(16) "3300900025177767"
  ["merchantreference"]=>
  string(16) "3400900025177762"
  ["mid"]=>
  string(10) "1000000000"
  ["mode"]=>
  string(4) "LIVE"
  ["reason"]=>
  string(8) "ACCEPTED"
  ["status"]=>
  string(1) "1"
  ["time"]=>
  string(10) "1549357106"
}
 */

$response = $spp->getPaymentCardHostedPagesGateway()->hpsRefund($ref, '15.00');

var_dump($response);
//Read parameter "status" if status == ACCEPTED then OK else failed
/*
 array(7) {
  ["@attributes"]=>
  array(1) {
    ["version"]=>
    string(1) "2"
  }
  ["datacash_reference"]=>
  string(16) "3900900025177769"
  ["merchantreference"]=>
  string(16) "3400900025177762"
  ["mode"]=>
  string(4) "LIVE"
  ["reason"]=>
  string(26) "Refund amount > orig 10.00"
  ["status"]=>
  string(2) "34"
  ["time"]=>
  string(10) "1549357108"
}
 */

$response = $spp->getPaymentCardHostedPagesGateway()->hpsRefund($ref, '2.00');
//Read parameter "status" if status == ACCEPTED then OK else failed
var_dump($response);
/*
 array(10) {
  ["@attributes"]=>
  array(1) {
    ["version"]=>
    string(1) "2"
  }
  ["MAC"]=>
  array(1) {
    ["outcome"]=>
    string(6) "ACCEPT"
  }
  ["acquirer"]=>
  string(22) "Swedbank Baltic Latvia"
  ["datacash_reference"]=>
  string(16) "3700900025177770"
  ["merchantreference"]=>
  string(16) "3400900025177762"
  ["mid"]=>
  string(10) "1000000000"
  ["mode"]=>
  string(4) "LIVE"
  ["reason"]=>
  string(8) "ACCEPTED"
  ["status"]=>
  string(1) "1"
  ["time"]=>
  string(10) "1549357108"
}
 */