0

We are integrating a Realex/Global Payments solution and have run into issues when trying to send data to Realex such as Customer Name, Customer Number, Customer Reference and Variable Reference etc.

We get the following error;

<response timestamp="20211208142721">
<merchantid>OUR MERCHANT ID IS INSERTED HERE</merchantid>
<account>website</account>
<orderid>scsi45880</orderid>
<result>505</result>
<message>sha1hash incorrect - check your code and the Developers Documentation</message>
</response>

Below is the code we are using, I have remitted sensitive data with #

<?php

require_once( '../../../wp-load.php' );
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Content-type: application/json');
//header("Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT,PATCH,DELETE,HEAD");

$dir = __DIR__ . '/soapclient/SforcePartnerClient.php';
require_once($dir);
//ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL);
$donate_give = base64_decode($_POST['donate_give']);
$insert_arr = array();
$secretKey = '########';
//$secretKey = '#########';
$response = $_POST['g-recaptcha-response'];
$remoteIp = $_SERVER['REMOTE_ADDR'];
$reCaptchaValidationUrl = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=$secretKey&response=$response&remoteip=$remoteIp");
$result = json_decode($reCaptchaValidationUrl, TRUE);
if ($result['success'] == 1) {
    $url = 'https://api.realexpayments.com/epage-remote.cgi';
    $merchantid = 'scs';
    $secret = '#########';
    $account = 'website';

    $timestamp = strftime("%Y%m%d%H%M%S");
    $cardNumber = $_POST['cardnnumber'];
    if ($_POST['cardtype'] == 'Visa') {
        $paymentmethod = 'visa01';
        $strCardType = 'VISA';
    }
    if ($_POST['cardtype'] == 'MasterCard') {
        $paymentmethod = "master01";
        $strCardType = "MC";
    }
    $expiryDate = $_POST['cmonth'] . substr($_POST['cyear'], -2);
    $cardHolder = $_POST['cardname'];
    $cvv = $_POST['cvvnumber'];
    global $wpdb;
    $insert_arr['first_name'] = $_POST['cname'];
    $insert_arr['last_name'] = $_POST['cflname'];
    $insert_arr['email'] = $_POST['cemail'];
    $insert_arr['extrainfo'] = $_POST['extrainfo'];
    if ($_POST['chonour']) {
        $insert_arr['newslatter'] = $_POST['chonour'];
    } else {
        $insert_arr['newslatter'] = 0;
    }

    $insert_arr['cardtype'] = $_POST['cardtype'];
    $insert_arr['cardname'] = $_POST['cardname'];
    $insert_arr['payment_status'] = 2;
    $insert_arr['created_date'] = date("Y-m-d H:i:s");
    $insert_arr['browser'] = $_SERVER['HTTP_USER_AGENT'];
    $insert_arr['added_ip'] = $_SERVER['REMOTE_ADDR'];

    $lastid = rand(10000, 99999);
    $amount = $_POST['amount'];
    $pay_amount = $amount * 100;
    $currency = "EUR";
    $rlx_orderid = "scsi" . $lastid;
    $varTmp = "$timestamp.$merchantid.$rlx_orderid.$pay_amount.$currency.$cardNumber";
    $sha1hash = sha1($varTmp);
    $tmp = "$sha1hash.$secret";
    $sha1hash = sha1($tmp);
    $updated_arra = array();
    $updated_arra['cardlastdigit'] = substr($cardNumber, -4);
    $updated_arra['cardholdername'] = $cardHolder;

    $payer_ref = sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
            mt_rand(0, 0xffff), mt_rand(0, 0xffff),
            mt_rand(0, 0xffff),
            mt_rand(0, 0x0C2f) | 0x4000,
            mt_rand(0, 0x3fff) | 0x8000,
            mt_rand(0, 0x2Aff), mt_rand(0, 0xffD3), mt_rand(0, 0xff4B)
    );
    
    //Payer sha1hash
    $payer_secret = '6Lex0fQZAAAAAKLe0bMt7xp1JduVftNRUXp3xbrO';
    $payer_temp_var = "$timestamp.$merchantid.$rlx_orderid.$pay_amount.$currency.$payer_ref";
    $payersha1hash = sha1($payer_temp_var);
    $payertmp = "$payersha1hash.$payer_secret";
    $payersha1hash = sha1($payertmp);
    
    
    $varref = sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
            mt_rand(0, 0xffff), mt_rand(0, 0xffff),
            mt_rand(0, 0xffff),
            mt_rand(0, 0x0C2f) | 0x4000,
            mt_rand(0, 0x3fff) | 0x8000,
            mt_rand(0, 0x2Aff), mt_rand(0, 0xffD3), mt_rand(0, 0xff4B)
    );
    
    $custnum = sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
            mt_rand(0, 0xffff), mt_rand(0, 0xffff),
            mt_rand(0, 0xffff),
            mt_rand(0, 0x0C2f) | 0x4000,
            mt_rand(0, 0x3fff) | 0x8000,
            mt_rand(0, 0x2Aff), mt_rand(0, 0xffD3), mt_rand(0, 0xff4B)
    );

    $payer_stirng = "<?xml version='1.0' encoding='UTF-8'?>
        <request type='payer-new' timestamp='$timestamp'>
          <merchantid>$merchantid</merchantid>
          <account>$account</account>
          <orderid>$rlx_orderid</orderid>
          <payer ref='$payer_ref' type='Retail'>
            <title>Mr.</title>
            <firstname>James</firstname>
            <surname>Mason</surname>
            <company>Global Payments</company>
            <address>
              <line1>Flat 123</line1>
              <line2>House 456</line2>
              <line3>The Cul-De-Sac</line3>
              <city>Halifax</city>
              <county>West Yorkshire</county>
              <postcode>W6 9HR</postcode>
              <country code='GB'>United Kingdom</country>
            </address>
            <phonenumbers>
              <home>+35312345678</home>
              <work>+3531987654321</work>
              <fax>+124546871258</fax>
              <mobile>+25544778544</mobile>
            </phonenumbers>
            <email>arun@appifyou.com</email>
            <dateofbirth>19880227</dateofbirth>
            <state>Yorkshire and the Humber</state>
            <passphrase>montgomery</passphrase>
            <varref>$varref</varref>
            <custnum>$custnum</custnum>
          </payer>
          <sha1hash>$payersha1hash</sha1hash>
        </request>";
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $payer_stirng);
    $payer_response = curl_exec($ch);

    error_log(print_r("Payer String", true));
    error_log(print_r($payer_stirng, true));
    error_log(print_r("Payer Response", true));
    error_log(print_r($payer_response, true));
    curl_close($ch);

    $payer_xml = new SimpleXMLElement($payer_response);
    
    
    
    $field_string = "<request   timestamp='$timestamp' type='auth'>
        <merchantid>$merchantid</merchantid>
        <account>$account</account>
        <channel>MOTO</channel>
        <orderid>$rlx_orderid</orderid>
        <amount currency='$currency'>$pay_amount</amount>               
        <card>
                    <number>$cardNumber</number>
                    <expdate>$expiryDate</expdate>
                    <chname>$cardHolder</chname>
                    <type>$strCardType</type>
                    <cvn>
                        <number>$cvv</number>
                        <presind>1</presind>
                    </cvn>
        </card>
        <autosettle flag='1' />
        <sha1hash>$sha1hash</sha1hash>
    </request>";
    // Send the request array to Realex Payments

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $field_string);
    $response = curl_exec($ch);

    error_log(print_r($response, true));
    error_log(print_r("huuhuhuh", true));
    error_log(print_r($field_string, true));
    curl_close($ch);

    $xml = new SimpleXMLElement($response);
    $updated_arra['payment_response'] = $response;
    $sucesss_status = "";
    $sucesss_msg = "";

    /* create payment entry in dynamics */
    $service = ACRM()->getSdk();
    $payment = $service->entity('codec_payment');
    $payment->codec_contact = new AlexaCRM\CRMToolkit\Entity\EntityReference('contact', $_POST['contactId']);
    $payment->codec_name = 'Payment for: ' . $_POST["InvoiceName"];
    //$payment->codec_paymentdate = date("d/m/Y");
    $payment->codec_paymentdate = time();
    $payment->codec_Invoice = new AlexaCRM\CRMToolkit\Entity\EntityReference('invoice', $_POST['InvoiceId']);
    $payment->codec_paymentamount = $_POST['amount'];
    $payment->codec_currency = $_POST['currencyId'];
    $payment->codec_transactionstatusmessage = 'Pending...';
    //$payment->codec_transactionid = $xml->orderid;
    //$payment->codec_transactionid = 'bssaljunosbznmduzrrb';
    //$payment->codec_transactionid = 'scsi28158';
    $transactionid_arr = json_decode(json_encode((array) $xml->orderid), TRUE);
    $payment->codec_transactionid = $transactionid_arr[0];
    error_log(print_r("here is contactId:" . $_POST['contactId'], true));
    error_log(print_r("here is payment_log:" . $payment, true));
    $pId = $payment->create();
    error_log(print_r("here is pid:" . $pId, true));
    if ($xml->result == '00') {
        $updated_arra['payment_status'] = 1;
        $sucesss_status = 1;
        $sucesss_msg = "Thank for your payment, your payment has now been processed.";

        /* to update status in dynamics */
        $upayment = $service->entity('codec_payment', $pId);
        $upayment->codec_transactionstatusmessage = 'Payment Succeeded.';
        $upayment->codec_transactioncompleted = 1;
        //$upayment->codec_paymentdate = strftime("%d/%m/%Y", time());
        $upayment->codec_paymentdate = time();
        //$upayment->codec_transactionid = $xml->srd;
        $upayment->codec_transactionid = $transactionid_arr['0'];
        error_log(print_r("here is end upayment", true));

        $upd = $upayment->update();

        error_log(print_r("here is upd:$upd", true));
    } elseif ($xml->result == '501') {
        error_log(print_r("Inside 501", true));
        $updated_arra['payment_status'] = 500;
        $sucesss_status = 0;
        $sucesss_msg = "This transaction has already been processed! If you feel this is incorrect please contact the merchant!";
        //send_email($_POST);
        //send_email($_POST,'','','');
    } else {
        error_log(print_r("Inside else sattus 0", true));
        $updated_arra['payment_status'] = 0;
        $sucesss_status = 0;
        $sucesss_msg = "Your Card has been decline. Please try again with different card.";
    }



    $where = array();
    $where['srno'] = $lastid;
    error_log(print_r("LatID: $lastid", true));
    //$wpdb->update( 'wp_dynamics_invoice_payment_online', $updated_arra, $where); 
    echo json_encode(array('sucreg' => $sucesss_status, 'msg' => $sucesss_msg));
} else {
    echo json_encode(array('sucreg' => '2', 'msg' => 'Captcha Error'));
}

function useWebApi($method, $data, $odata) {
//GET APP ACCESS TOKEN
    $token = getAppAccessToken();
    //$url = "https://##########.crm4.dynamics.com/api/data/v8.2/";
    $url = "https://##########.api.crm4.dynamics.com/api/data/v9.2/";
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);

    curl_setopt_array($curl, array(
        CURLOPT_URL => $url . $odata,
        CURLOPT_HEADER => 1,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => $method,
        CURLOPT_POSTFIELDS => $data,
        CURLOPT_HTTPHEADER => array(
            "Authorization: Bearer " . $token["access_token"],
            "cache-control: no-cache",
            "content-type: application/json"
        ),
    ));

    $response = curl_exec($curl);
    $err = curl_error($curl);

    curl_close($curl);

    if ($err) {
        return "cURL Error #:" . $err;
    } else {
        return $response;
    }
}

function getCreatedPaymentGuid($jsonResponse) {
    list($headers, $response) = explode("\r\n\r\n", $jsonResponse, 2);

    $headers = explode("\n", $headers);
    foreach ($headers as $header) {
        if (stripos($header, 'OData-EntityId:') !== false) {
            $OData = $header;
        }
    }
    $guid = substr($OData, strrpos($OData, '(') + 1, 36);
    return $guid;
}

function getAppAccessToken() {

    $tenantID = '############';
    $clientid = '############';
    $clientsecret = urlencode('############');

    //live site
    //############
    //$clientsecret = urlencode('############');    
    $username = urlencode('############');
    $password = '############';
    $grant_type = urlencode('client_credentials');
    $resource = urlencode('https://############.crm4.dynamics.com/');

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);

    curl_setopt_array($curl, array(
        CURLOPT_URL => "https://login.microsoftonline.com/" . $tenantID . "/oauth2/token",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => "username=" . $username . "&password=" . $password . "&grant_type=" . $grant_type . "&resource=" . $resource . "&client_id=" . $clientid . "&client_secret=" . $clientsecret,
        CURLOPT_HTTPHEADER => array(
            "cache-control: no-cache",
            "content-type: application/x-www-form-urlencoded"
        ),
    ));

    $responseJson = curl_exec($curl);
    $err = curl_error($curl);

    curl_close($curl);

    if ($err) {
        echo "cURL Error #:" . $err;
    } else {

        return $response = json_decode($responseJson, true);
    }
}

Any help would be greatly appreciated. Realex documentation isn't very clear and whilst we have tried contacting support, they are stumped as well.

  • @GlobalPayments any help in diagnosing the issue would be appreciated. We contacted GlobalPayments and confirmed that the secret specified is in fact correct. Payment goes through but generates an error when parsing user data using payer-new request. – Rytis Joseph Jan Dec 09 '21 at 17:26

1 Answers1

0

Solved error by using the following code:

$payer_temp_var = "$timestamp.$merchantid.$rlx_orderid...$payer_ref";

And removing $pay_amount.$currency