27.12.11

Payex payment gateway integration php


       


               INTEGRATE PAYEX PAYMENT GATEWAY
                            -----------------------------------

1. Payex use SOAP for communication
2. Get a test account of Payex
3. We require Payex AccountNumber and Payex Encryptionkey
4. there are two methods of payments are supported by payex
 (a).AUTHORISED
 (b).CAPTURED
5.we can implement Payex Payment Gateway in our Application

++++++++++++++++++++++++++++++++++++++++++++++++++++++++

<?php
/**
 * test urls : https://test-external.payex.com/pxorder/pxorder.asmx?wsdl
 * https://test-confined.payex.com/PxConfined/pxorder.asmx?wsdl
 *
 * Type: VISA
 * Card number: 4925000000000004
 * CVC: 123
 * Expire date: 12/12
 */

class PayEx
{
public $priceArgList = ''; // No CPA, VISA,
public $currency;
public $vat =0; // Vat
public $orderID = "60"; // Local order id
public $description = ''; // Product description
public $clientIPAddress = '';
public $clientIdentifier = '';
public $additionalValues = '';//'DOCUMENTID=
public $externalID = '';
public $view = 'CC'; // Payment method PayEx
public $agreementRef = '';
public $cancelUrl = '';
public $config = '';
private $respons;
private $orderRef;
var $account_no;
var $encrypted_key; // Qwefgdfgdfgre5464564WpH
var $uniqueId;
var $PxOrderWSDL = "https://test-external.payex.com/pxorder/pxorder.asmx?wsdl";
var $PxConfinedWSDL = "https://test-confined.payex.com/PxConfined/pxorder.asmx?wsdl";

    function PayEX() {


        $this->account_no = 45667854781;
        $this->encrypted_key = Qwefgdfgdfgre5464564WpH;
        $this->testmode = 1;
        if($this->testmode == 1){
            $this->PxOrderWSDL = "https://test-external.payex.com/pxorder/pxorder.asmx?wsdl";
            $this->PxConfinedWSDL = "https://test-confined.payex.com/PxConfined/pxorder.asmx?wsdl";
        }
        else{
            $this->PxOrderWSDL = "https://external.payex.com/pxorder/pxorder.asmx?wsdl";
            $this->PxConfinedWSDL = "https://confined.payex.com/PxConfined/pxorder.asmx?wsdl";
        }
       
    }
    /**
     * Set payment configuration
     * @param $apiConfig
     */
    function setPaymentInfo($apiConfig){
        $this->description = $apiConfig['description'];
        $this->currency = $apiConfig['currency'];
        $this->uniqueId = $apiConfig['uniqueId'];
    }
    /**
     * Proccess the payment details
     * @param array $data
     * @param string $paymentStatus : AUTHORIZATION or SALE
     */
    function process($data,$paymentStatus){
        switch($paymentStatus) {

            case S:

                $data['pxmerchant_account_no'] = $this->account_no;
                $data['pxmerchant_encpt_key'] = $this->encrypted_key;
                $data['description'] = $this->description;
                $data['currency_details'] = $this->currency;
                $data['purchaseOperation'] = 'AUTHORIZATION';

                $this->TwoPhaseTransaction($data);
                       
        }
    }
    /**
     * Initialisation of data to be passed to payment gateway
     * @param array $data
     * @return array $paramas
     */
    function initialization($data)
    {
        //$_server won't work if run from console.
        $this->clientIPAddress = $_SERVER['REMOTE_ADDR'];
        $this->clientIdentifier = "USERAGENT=".$_SERVER['HTTP_USER_AGENT'];
        //Not sure why we need to do this - for large amounts we need to preserver the decimals (not as 1.2E6)
        //So converting it to string;
        $amtasStr = $data['totalPaymentValue'] . '';
            $res = $amtasStr * 100;               
        $params = array
        (
        'accountNumber' => $this->account_no,
        'purchaseOperation' => $data['purchaseOperation'],
        'price' => sprintf("%s",$res),
        'priceArgList' => $this->priceArgList,
        'currency' => 'NOK',
        'vat' => '0',
        'orderID' => $this->uniqueId,
        'productNumber' => $AdBase,// A ten digit no that needs to passed to payment gateway
        'description' => substr($data['description'],0,158),
        'clientIPAddress' => $this->clientIPAddress,
        'clientIdentifier' => $this->clientIdentifier,
        'additionalValues' => $this->additionalValues,
        'externalID' => $this->externalID,
        'returnUrl' => 'BASEURL/success/', // for testing
        'view' => $this->view,
        'agreementRef' => $this->agreementRef,
        'cancelUrl' => BASEURL/error/',// for testing
        'clientLanguage' => 'nb-NO'
        );
        return $params;
    }

    /**
     * Start payment processing
     * @param array $data
     */
    function TwoPhaseTransaction($data)
    {
           
        $params = $this->initialization($data);
        $result = $this->initialize7($params);

        $status = $this->checkStatus($result);
        // if code & description & errorCode is OK, redirect the user
        if($status['code'] == "OK" && $status['errorCode'] == "OK" && $status['description'] == "OK")
        {
            $_SESSION['payexOrderRef'] = $status['orderRef'];
            header('Location: '.$status['redirectUrl']);
            exit;
        }else {
            foreach($status as $error => $value)
            {
                echo  "$error , $value "."\n";
            }
        }
    }
    /**
     * Inistailising soap client and post data
     * @param $params
     * @return $respons xml response data
     */
    public function initialize7($params)
    {
        $PayEx = new SoapClient($this->PxOrderWSDL,array("trace" => 1, "exceptions" => 0));
        //create the hash
        $hash = $this->createHash(trim(implode("", $params)));
        //append the hash to the parameters
        $params['hash'] = $hash;

        try{  
            //defining which initialize version to run, this one is 7.
            $respons = $PayEx->Initialize7($params);

        }catch (SoapFault $error){
            echo "Error: {$error->faultstring}";
        }
        return $respons->{'Initialize7Result'};
    }
    /**
     * Parse XML data to array
     * @param XML $xml
     * @return array $status
     */
     public function checkStatus($xml) {
        $returnXml = new SimpleXMLElement($xml);
        $code = strtoupper($returnXml->status->code);
        $errorCode = strtoupper($returnXml->status->errorCode);
        $description = strtoupper($returnXml->status->description);
        $orderRef = strtoupper($returnXml->orderRef);
        $authenticationRequired = strtoupper($returnXml->authenticationRequired);

        return $status = array(
                'code'=>$code,
                'errorCode'=>$errorCode,
                'description'=>$description,
                'redirectUrl'=>$returnXml->redirectUrl,
                'orderRef'=>$orderRef,
                'authenticationRequired'=>$authenticationRequired);

    }
    /**
     * Create hash value for passign it to the payex
     * @param $params : data to be posted
     * @return hash value
     */
    public function createHash($params) {
         $params = $params.$this->encrypted_key;
        return md5($params);
    }
    /**
     * On response from Payex
     * @param $orderRef : payment ref id from payex
     * @return array : transaction process result
     */
    function Completeorder($orderRef)
    {
        //$orderRef =  $orderRef; //'24713cacaf4c47709ff352e8a44efb38';
        $params = array
        (
        'accountNumber' => $this->account_no,
        'orderRef' => $orderRef
        );
       
        // complete the transaction by passing the refid to payex
        $completeResponse = $this->Complete($params);
        $result = $this->ckhCompleteResp($completeResponse);
        /*
        Transaction status (defined in payex_defines.php):
        0=Sale, 1=Initialize, 2=Credit, 3=Authorize, 4=Cancel, 5=Failure, 6=Capture
       
        */
        if ($result['transactionStatus'] == '0' || $result['transactionStatus'] == '6'){
        echo 'Order successfully completed.';
        }else if($result['transactionStatus'] == '5'){
        echo 'Order unsuccessfull';
        }else {
            /* status 3 is in this section */
            echo "Transaction not completed.";
        }
        return $result;
    }
    /**
     * complete the transaction by passing the refid to payex
     * @param array $params : account no and refid
     * @return xml response data
     */
    function Complete($params){
        $PayEx = new SoapClient($this->PxOrderWSDL,array("trace" => 1, "exceptions" => 0));

        //create the hash
        $hash = $this->createHash(trim(implode("", $params)));
        //append the hash to the parameters
        $params['hash'] = $hash;

        try{
            //defining which complete
            $respons = $PayEx->Complete($params);
           
        }catch (SoapFault $error){
            echo "Error: {$error->faultstring}";
        }
        return $respons->{'CompleteResult'};
    }
    function Capture($params)
    {
        $PayEx = new SoapClient($this->PxOrderWSDL,array("trace" => 1, "exceptions" => 0));

        //create the hash
        $hash = $this->createHash(trim(implode("", $params)));
        //append the hash to the parameters
        $params['hash'] = $hash;

        try{
            //defining which complete
            $respons = $PayEx->Capture3($params);

        }catch (SoapFault $error){
            echo "Error: {$error->faultstring}";
        }
        return $respons->{'Capture3Result'};

    }
    // Authorise to credit
    function intialise($params)
    {
        //$_server won't work if run from console.

        $params = array
        (
                    'accountNumber' => $this->account_no,
                    'transactionNumber' => $params['transactionNumber'],
                    'amount' => $params['amount']*100,
                    'orderId' =>$params['orderId']);

        return $params;
    }
    /**
     * Parse the xml response on payex complete transaction
     * @param $params : xml data
     * @return array of response data
     */
    function ckhCompleteResp($params) {
        $returnXml = new SimpleXMLElement($params);
        $code = strtoupper($returnXml->status->code);
        $errorCode = strtoupper($returnXml->status->errorCode);
        $description = strtoupper($returnXml->status->description);
        $transactionStatus = strtoupper($returnXml->transactionStatus);
        $transactionNumber = strtoupper($returnXml->transactionNumber);
        $orderId = strtoupper($returnXml->orderId);
        return $status = array(
                'code'=>$code,
                'errorCode'=>$errorCode,
                'description'=>$description,
                'transactionStatus'=>$transactionStatus,
                'transactionNumber'=>$transactionNumber,
                'orderId'=>$orderId);
    }
}


?>
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++



6. On submitting the purchase details

        $payconfig = array('pxmerchant_account_no' => $payexaccountnumber,
                'pxmerchant_encpt_key' => $payexencryptionkey,
                'productNumber' => $dealdetails["DealId"],
                'orderID' => $dealdetails["DealId"],
                'uniqueId' => $unique_id,
                'Price' => $dealdetails["Price"],
                'currency' => $payexcurrency,
                'description' => utf8_encode($dealdetails["details"]));

    //$paymentdata contains all the details of all purchase
    //$transactionStatus = S;

        $paymentObject = new PayEx();
        $paymentObject->setPaymentInfo($payconfig);
        $paymentStatus =  $paymentObject->process($paymentdata,$transactionStatus);


+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

7. Capturing of authorised payments

        $paymentObject = new PayEx();
        $params = array();
        $params['amount'] = $transaction->TransactionAmount;
        $params['accountNumber'] = $this->view->config->payment->payexaccountnumber;
        $params['transactionNumber'] = $transaction->PaypalReferenceId;
        $params['orderId'] = $transaction->UniqueId;
        $hash = $paymentObject->intialise($params);
        $response = $paymentObject->Capture($hash);

    //the response will be an xml we need to parse the xml to get the response
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++











4 comments:

  1. Hey, nice post....love the way you have offered the whole story. If you interested payment gateways you can contact us.

    ReplyDelete
  2. Anonymous12/9/13

    Hi,
    How to run this code..Here have some error..

    Please explain me , how to run this on my website.

    My site is Make in custom php

    Thanks in Advance,

    ReplyDelete
  3. Anonymous12/9/13

    It's to urgent..

    Please give me reply..

    Thanks in advance again..

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete