Code Samples
  • 29 Aug 2022
  • 8 Minutes to read
  • Contributors
  • Dark
    Light

Code Samples

  • Dark
    Light

PHP5 (Using CURL) with Full HTML



    // CHECK IF THE FORM WAS SUBMITTED
    if(@$_POST['submit']){

        // SET URL
        $url = 'https://gateway.helcim.com/';

        // SET TRANSACTION VALUES
        $merchantId        = '9999111111';
        $token            = '1a2b3c4d5e6f7g8h9i';
        $type            = 'purchase';
        $amount            = @$_POST['amount'];
        $cardNumber        = @$_POST['cardNumber'];
        $expiryDate        = @$_POST['expiryDate'];
        $cvvIndicator    = '1';
        $cvv            = @$_POST['cvv'];
        $orderId        = @$_POST['orderId'];
        $test            = '1';

        // CREATE POST STRING
        $postString =    'merchantId='.$merchantId.'&'.
                        'token='.$token.'&'.
                        'type='.$type.'&'.
                        'amount='.$amount.'&'.
                        'cardNumber='.$cardNumber.'&'.
                        'expiryDate='.$expiryDate.'&'.
                        'cvvIndicator='.$cvvIndicator.'&'.
                        'cvv='.$cvv.'&'.
                        'orderId='.$orderId.'&'.
                        'test='.$test;

        // SET CURL OPTIONS
        $curlOptions = array(    CURLOPT_RETURNTRANSFER => 1,
                                CURLOPT_AUTOREFERER => TRUE,
                                CURLOPT_FRESH_CONNECT => TRUE,
                                CURLOPT_HEADER => FALSE,
                                CURLOPT_POST => TRUE,
                                CURLOPT_POSTFIELDS => $postString,
                                CURLOPT_TIMEOUT => 30 );

        // CREATE NEW CURL RESOURCE
        $curl = curl_init($url);

        // SET CURL OPTIONS
        curl_setopt_array($curl,$curlOptions);

        // PROCESS TRANSACTION - GET RESPONSE
        $response = curl_exec($curl);

        // CLOSE CURL REOURCE
        curl_close($curl);

        // CONVERT CARRIAGE RETURN LINE FEED TO AMPERSAND
        $response = preg_replace("/\x0D/",'&',$response);
        $response = preg_replace("/\x0A/",'&',$response);

        // PARSE RESPONSE INTO AN ARRAY
        parse_str($response,$responseArray);

        // CHECK FOR APPROVAL
        if($responseArray['response'] == 1){

            // APPROVED
            echo 'TRANSACTION APPROVED!';

            // DISPLAY RESPONSE ARRAY
            print_r($responseArray);

            // KILL PROCESS
            exit;

        }else{

            // DECLINED
            echo 'TRANSACTION DECLINED!';

            // DISPLAY RESPONSE ARRAY
            print_r($responseArray);

            // KILL PROCESS
            exit;

        }

    }

?>

<html>
<head>
<title>Payment Formtitle>
<body>

<h1>Enter Payment Informationh1>

<form action="your-checkout-page.php" method="POST">

<table>
<tr>
<td>Credit Card #:td>
<td><input type="text" name="cardNumber" value="">td>
tr>
<tr>
<td>Expiry Date (MMYY):td>
<td><input type="text" name="expiryDate" value="">td>
tr>
<tr>
<td>CVV Security Code:td>
<td><input type="text" name="cvv" value="">td>
tr>
<tr>
<td>Amount:td>
<td><input type="text" name="amount" value="0.00">td>
tr>
<tr>
<td>Invoice #:td>
<td><input type="text" name="orderId" value="">td>
tr>
<tr>
<td>td>
<td><input type="submit" name="submit" value="Submit Payment">td>
tr>
table>

form>

body>
html>

PHP5 (Using CURL) 



    // CHECK IF THE FORM WAS SUBMITTED
    if(@$_POST['submit']){

        // SET URL
        $url = 'https://gateway.helcim.com/';

        // SET TRANSACTION VALUES
        $merchantId        = '9999111111';
        $token            = '1a2b3c4d5e6f7g8h9i';
        $type            = 'purchase';
        $amount            = '100.00';
        $cardNumber        = '5454545454545454';
        $expiryDate        = '1020';
        $cvvIndicator    = '1';
        $cvv            = '200';
        $orderId        = 'INV091293123';
        $test            = '1';

        // CREATE POST STRING
        $postString =    'merchantId='.$merchantId.'&'.
                        'token='.$token.'&'.
                        'type='.$type.'&'.
                        'amount='.$amount.'&'.
                        'cardNumber='.$cardNumber.'&'.
                        'expiryDate='.$expiryDate.'&'.
                        'cvvIndicator='.$cvvIndicator.'&'.
                        'cvv='.$cvv.'&'.
                        'orderId='.$orderId.'&'.
                        'test='.$test;

        // SET CURL OPTIONS
        $curlOptions = array(    CURLOPT_RETURNTRANSFER => 1,
                                CURLOPT_AUTOREFERER => TRUE,
                                CURLOPT_FRESH_CONNECT => TRUE,
                                CURLOPT_HEADER => FALSE,
                                CURLOPT_POST => TRUE,
                                CURLOPT_POSTFIELDS => $postString,
                                CURLOPT_TIMEOUT => 30 );

        // CREATE NEW CURL RESOURCE
        $curl = curl_init($url);

        // SET CURL OPTIONS
        curl_setopt_array($curl,$curlOptions);

        // PROCESS TRANSACTION - GET RESPONSE
        $response = curl_exec($curl);

        // CLOSE CURL REOURCE
        curl_close($curl);

        // CONVERT CARRIAGE RETURN LINE FEED TO AMPERSAND
        $response = preg_replace("/\x0D/",'&',$response);
        $response = preg_replace("/\x0A/",'&',$response);

        // PARSE RESPONSE INTO AN ARRAY
        parse_str($response,$responseArray);

        // CHECK FOR APPROVAL
        if($responseArray['response'] == 1){

            // APPROVED
            echo 'TRANSACTION APPROVED!';

            // DISPLAY RESPONSE ARRAY
            print_r($responseArray);

            // KILL PROCESS
            exit;

        }else{

            // DECLINED
            echo 'TRANSACTION DECLINED!';

            // DISPLAY RESPONSE ARRAY
            print_r($responseArray);

            // KILL PROCESS
            exit;

        }

    }

?>

.NET(C#)

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Net" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Text" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
    protected void Page_Load(object sender, EventArgs e)
    {
        // Gateway URL
        string Url = "https://gateway.helcim.com/";

        // Required Request Variables
        string MerchantId   = "9999111111";        
        string Token        = "1a2b3c4d5e6f7g8h9i";
        string Type         = "purchase";
        string Amount       = "10.00";
        string CardNumber   = "4242424242424242";
        string ExpiryDate   = "0912";
        string CvvIndicator = "1"; 
        string Cvv          = "432";
        string CardholderName = "John Doe";
        string CardholderAddress = "#503 - 111 25th Ave SW"; 
        string CardholderPostalCode = "T2S3G4";
        string Test = "1";

        string PostData = "merchantId=" + MerchantId + "&token=" + Token + "&type=" + Type +
                          "&amount=" + Amount + "&cardNumber=" + CardNumber +
                          "&expiryDate=" + ExpiryDate + "&cvvIndicator=" + CvvIndicator +
                          "&cvv=" + Cvv + "&cardholderName=" + CardholderName +
                          "&cardholderAddress=" + CardholderAddress +
                          "&cardholderPostalCode=" + CardholderPostalCode + "&test=" + Test;
     // Create a new web request
        HttpWebRequest GatewayRequest = (HttpWebRequest)WebRequest.Create(Url);

     // Set HTTP header information
        GatewayRequest.Method = "POST";
        GatewayRequest.ContentType = "application/x-www-form-urlencoded";

        byte[] byteArray = Encoding.UTF8.GetBytes(PostData);
        GatewayRequest.ContentLength = byteArray.Length;

     // Send request    
        Stream SendStream = GatewayRequest.GetRequestStream();
        SendStream.Write(byteArray, 0, byteArray.Length);
        SendStream.Close();

     // Get response
        HttpWebResponse GatewayResponse = (HttpWebResponse)GatewayRequest.GetResponse();
        Stream ReceiveStream = GatewayResponse.GetResponseStream();
        StreamReader ReadStream = new StreamReader(ReceiveStream, Encoding.UTF8);
        string Response = ReadStream.ReadToEnd();

     // Close resources
        GatewayResponse.Close();
        ReadStream.Close();
     // Parse response (HttpUtility requires .NET Framework 2.0)
        NameValueCollection Nvc = HttpUtility.ParseQueryString(Response.Replace("\r\n", "&"));
        ResponseLiteral.Text = Nvc["responseMessage"];
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Helcim Gateway Test</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:Literal  id="ResponseLiteral"
                  runat="server" />
    </div>
    </form>
</body>
</html>

PHP5 (Using CURL) Recurring Transaction with Full HTML


// Check for Form Submitted
if(@$_POST['submit']){

    // Required Request Variables
    $Url = 'https://gateway.helcim.com/';
    $MerchantId            = '9999111111';
    $Token                = '1a2b3c4d5e6f7g8h9i';
    $Type                = 'purchase';
    $Amount                = @$_POST['amount'];
    $CardNumber            = @$_POST['cardNumber'];
    $ExpiryDate            = @$_POST['expiryDate'];
    $CvvIndicator            = '1';
    $Cvv                = @$_POST['cvv'];
    $recurringPeriod        = '1 month';
    $recurringStartDate        = '20131201';
    $recurringAmount        = '100.00';
    $recurringTimes            = '999';
    $Test                = '1';

    // Create POST string
    $PostFields = "merchantId={$MerchantId}&token={$Token}&type={$Type}".
             "&amount={$Amount}&cardNumber={$CardNumber}".
             "&expiryDate={$ExpiryDate}&cvvIndicator={$CvvIndicator}".
             "&cvv={$Cvv}&recurringPeriod={$recurringPeriod}".
             "&recurringStartDate={$recurringStartDate}".
             "&recurringAmount={$recurringAmount}".
             "&recurringTimes={$recurringTimes}&test={$Test}";

    // CURL Options Array
    $CurlOptions = array( CURLOPT_RETURNTRANSFER => 1,
                  CURLOPT_AUTOREFERER => TRUE,
                  CURLOPT_FRESH_CONNECT => TRUE,
                  CURLOPT_HEADER => FALSE,
                  CURLOPT_POST => TRUE,
                  CURLOPT_POSTFIELDS => $PostFields,
                  CURLOPT_TIMEOUT => 30 );

    // New CURL resource                      
    $Curl = curl_init($Url);
    // Set CURL options array
    curl_setopt_array($Curl, $CurlOptions);
    // Get URL response
    $Response = curl_exec($Curl);
    // Close CURL resource
    curl_close($Curl);

    // Parse response into an array
    $Response = eregi_replace("\x0D\x0A", "&", $Response);
    parse_str($Response, $ResponseArray);

}

?>

<html>
<head>
<title>Payment Formtitle>
<body>



// Check for Form Not Submitted
if(!@$_POST['submit']){

?>

<h1>Enter Payment Informationh1>

<form action="payment.php" method="POST">

<table>
<tr>
<td>Credit Card #:td>
<td><input type="text" name="cardNumber" value="">td>
tr>
<tr>
<td>Expiry Date (MMYY):td>
<td><input type="text" name="expiryDate" value="">td>
tr>
<tr>
<td>CVV Security Code:td>
<td><input type="text" name="cvv" value="">td>
tr>
<tr>
<td>Amount:td>
<td><input type="text" name="amount" value="0.00">td>
tr>
<tr>
<td>Invoice #:td>
<td><input type="text" name="orderId" value="">td>
tr>
<tr>
<td>td>
<td><input type="submit" name="submit" value="Submit Payment">td>
tr>
table>

form>



// Check for Form Submitted
}else{

?>

<h1>Transaction Receipth1>



    // Check gateway response
    if(@$ResponseArray['response'] == 1){

?>

<h2>APPROVED!h2>



    }else{

?>

<h2>DECLINEDh2>
<h3>ERROR:  @$ResponseArray['responseMessage'] ?>h3>



    }

?>

<table>
<tr>
<td>Date & Time:td>
<td> @$ResponseArray['date'] ?>  @$ResponseArray['time'] ?>td>
tr>
<tr>
<td>Invoice Number:td>
<td> @$ResponseArray['orderId'] ?>td>
tr>
<tr>
<td>Amount:td>
<td> @$ResponseArray['amount'] ?>td>
tr>
<tr>
<td>Approval Code:td>
<td> @$ResponseArray['approvalCode'] ?>td>
tr>
<tr>
<td>Card Type:td>
<td> @$ResponseArray['cardType'] ?>td>
tr>
<tr>
<td>Credit Card #:td>
<td> @$ResponseArray['cardNumber'] ?>td>
tr>
table>



}

?>

body>
html>

PHP - Auto-Void Based On AVS Results



    // SET ACCEPTABLE AVS RESPONSE
    $acceptableArray[] = 'W'; // 9 digit Zip matches, Address (Street) does not
    $acceptableArray[] = 'X'; // Exact AVS Match
    $acceptableArray[] = 'Y'; // Address (Street) and 5 digit Zip match
    $acceptableArray[] = 'Z'; // 5 digit Zip matches, Address (Street) does not

    // DEFAULT AVS RESULT
    $avsGood = false;

    // GO THROUGH RESULTS
    foreach($acceptableArray as $avs){

        // CHECK FOR AVS RESPONSE
        if($responseArray['avsResponse'] == $avs){

            // SET AVS
            $avsGood = true;

            // END FOREACH LOOP
            break;

        }

    }

    // CHECK AVS
    if($avsGood){

        // DISPLAY
        echo 'APPROVED';

    }else{

        // SETTINGS
        $type = 'void';
        $transactionId = $responseArray['transactionId'];

        // CREATE POST STRING
        $postString =    'merchantId='.$merchantId.'&'.
                        'token='.$token.'&'.
                        'type='.$type.'&'.
                        'transactionId='.$transactionId.'&'.
                        'test='.$test;

        // CREATE NEW CURL RESOURCE
        $curl = curl_init($url);

        // SET CURL OPTIONS
        curl_setopt_array($curl,$curlOptions);

        // PROCESS TRANSACTION - GET RESPONSE
        $response = curl_exec($curl);

        // CLOSE CURL REOURCE
        curl_close($curl);

        // DISPLAY
        echo 'TRANSACTION REVERSED - BAD AVS';

    }

?>

IOS (Objective C)

// TEXT FIELD FOR RESPONSE
    @property (weak, nonatomic) IBOutlet UITextView *txtResponseField;

    // SETTINGS
    @property (retain, nonatomic) NSURLConnection *connection;
    @property (retain, nonatomic) NSMutableData *receivedData;

    ///////////////////
    // CONNECT HTTP BUTTON
    - (IBAction)btnConnect:(id)sender {
        
        // CLEAR CONNECTION IF THERE IS ONE (mainly if you click the button twice)
        [self.connection cancel];
        
        //INITALIZE DATA
        NSMutableData *data = [[NSMutableData alloc] init];
        self.receivedData = data;

        
        //INITALIZE URL
        NSURL *url = [NSURL URLWithString:@"https://gateway.qa.helcim.com/"];
        
        //INITALIZE REQUEST
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[url standardizedURL]];
        
        // SET METHOD
        [request setHTTPMethod:@"POST"];
        
        //INITALIZE POST STRING
        NSString *postData = @"merchantId=9999999999&token=ABC1123123ABC123123&type=purchase&amount=10.00&cardNumber=5454545454545454&expiryDate=1020&cvvIndicator=1&cvv=100";
        
        //SET REQUEST TYPE !!HAS TO BE SET!!
        [request setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
        
        // SET POST DATA OF REQUEST
        [request setHTTPBody:[postData dataUsingEncoding:NSUTF8StringEncoding]];
        
        // INITALIZE A CONNECTION WITH REQUEST
        NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
        self.connection = connection;

        
        // START CONNECTION
        [connection start];
        
    }

    /*
     this method might be calling more than one times according to incoming data size
     */
    -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
        [self.receivedData appendData:data];
    }

    /*
     if there is an error occured, this method will be called by connection
     */
    -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
        
        NSLog(@"%@" , error);

    }

    /*
     if data is successfully received, this method will be called by connection
     */
    -(void)connectionDidFinishLoading:(NSURLConnection *)connection{
        
        // CONVERT RECIEVED DATA INTO STRING
        NSString *htmlSTR = [[NSString alloc] initWithData:self.receivedData
                                                  encoding:NSUTF8StringEncoding];
        
        // SET TEXTFIELD
        self.txtResponseField.text = htmlSTR;
        
    }

    ///////////////////////
    // BUTTON PARSE DATA
    - (IBAction)btnParse:(id)sender {
        
        // PARSED ARRAY
        NSArray *responseArray = [self.txtResponseField.text componentsSeparatedByString:@"\r\n"];
        
        // CREATE A DICTIONARY TO SET KEY AND VALUE
        NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
        
        // LOOP THROUGH RESPONSE ARRAY
        for (int i; i < [responseArray count]-1; i++) {

            // EXPLODE VALUE
            NSArray *tempArray = [responseArray[i] componentsSeparatedByString:@"="];

            // SET KEY AND VALUE
            [dictionary setObject:tempArray[1] forKey:tempArray[0]];

        }

        // CLEAR TEXT
        self.txtResponseField.text = @"";
        
        // LOOP THROUGH DICTIONARY
        for (NSString *key in dictionary) {
            
            // SHOW PARSED DATA
            self.txtResponseField.text =[self.txtResponseField.text stringByAppendingString:[NSString stringWithFormat:@"%@ = \"%@\"\n\n",key,[dictionary objectForKey:key]]];
            
        }
    }

Android (Java)

 ////////////////////////////////////////////////////////////
// PRIVATE FUNCTION - SEND POST DATA TO URL
////////////////////////////////////////////////////////////
private void sendPost() {

    // SETTINGS
    final String[] responseArray = new String[1];
    final CountDownLatch latch = new CountDownLatch(1);

    // THREAD TO SEND POST
    new Thread(new Runnable() {
        @Override
        public void run() {

            // SETTINGS
            String postString = "merchantId=CHANGEME"
                    + "&token=CHANGEME"
                    + "&type=purchase"
                    + "&test=1"
                    + "&amount=66.00"
                    + "&cardNumber=CHANGEME"
                    + "&cardExpiry=CHANGEME"
                    + "&cardCVV=CHANGEME";

            // CHECK FOR +
            while (postString.contains("+")){

                // REPLACE TO CODE
                postString = postString.replace("+","%2B");

            }

            try {

                // SET URL AND POST STRING
                URL toUrl = new URL("https://gateway.helcim.com/");

                // CREATE CONNECTION
                HttpURLConnection connection = (HttpURLConnection) toUrl.openConnection();

                // SET CONNECTION TIMEOUT
                connection.setConnectTimeout(5000);

                // SET PROPERTIES
                connection.setRequestMethod("POST");
                connection.setRequestProperty("USER-AGENT", "Mozilla/5.0");
                connection.setRequestProperty("ACCEPT-LANGUAGE", "en-US,en;0.5");
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

                // SET OUTPUT
                connection.setDoOutput(true);
                DataOutputStream dStream = new DataOutputStream(connection.getOutputStream());

                // GET RESPONSE
                dStream.writeBytes(postString);

                // CLOSE
                dStream.close();

                // CREATE READER AND READ DATA
                BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String line = null;
                StringBuilder responseOutput = new StringBuilder();
                while ((line = br.readLine()) != null) {
                    responseOutput.append(line);
                }

                // CLOSE READER
                br.close();

                // SET RESPONSE AND ALLOW RETURN
                responseArray[0] = responseOutput.toString();
                latch.countDown();

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (SocketTimeoutException e) {

                // CONNECTION TIMED OUT
                responseArray[0] = "Connection timed out. Please try again.";
                latch.countDown();

            } catch (IOException e) {

                // ERROR WITH CONNECTION
                responseArray[0] = e.getLocalizedMessage();
                latch.countDown();
            }
        }
    }).start();


    try {

        // WAIT TO MAKE SURE WE HAVE DATA
        latch.await();

    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    // RETURN ANSWER
    return responseArray[0];

} // END FUNCTION