Monday, July 15, 2013

How to get the current URL in jQuery

To get the path, you can use:

var pathname = window.location.pathname;
 
http://stackoverflow.com/questions/406192/how-to-get-the-current-url-in-jquery 

Credit card validation using php


<?php
define("CARD_TYPE_MASTERCARD","CARD_TYPE_MASTERCARD");
define("CARD_TYPE_VISA","CARD_TYPE_VISA");
define("CARD_TYPE_AEX","CARD_TYPE_AEX");
define("CARD_TYPE_DINERS","CARD_TYPE_DINERS");
define("CARD_TYPE_DISCOVER","CARD_TYPE_DISCOVER");
define("CARD_TYPE_JCB","CARD_TYPE_JCB");

function getCardType($cardNumber){
    $cardNumber = preg_replace('/\D/', '', $cardNumber);
    $len = strlen($cardNumber);
    if ($len < 15 || $len > 16) {
        return null;
    } else {
        switch($cardNumber) {
            case(preg_match ('/^4/', $cardNumber) >= 1):
                return CARD_TYPE_VISA;
            case(preg_match ('/^5[1-5]/', $cardNumber) >= 1):
                return CARD_TYPE_MASTERCARD;
            case(preg_match ('/^3[47]/', $cardNumber) >= 1):
                return CARD_TYPE_AEX;
            case(preg_match ('/^3(?:0[0-5]|[68])/', $cardNumber) >= 1):
                return CARD_TYPE_DINERS;
            case(preg_match ('/^6(?:011|5)/', $cardNumber) >= 1):
                return CARD_TYPE_DISCOVER;
            case(preg_match ('/^(?:2131|1800|35\d{3})/', $cardNumber) >= 1):
                return CARD_TYPE_JCB;
            default:
                return null;
                break;
        }
    }
    return null;
}
?>

Thursday, July 4, 2013

PUTting data fields with PHP cURL

This is a little post about how to PUT multiple data fields using the PHP cURL extension. Why I wanted to do this in the first place is beyond the scope of this post, since its quite a long story. The curl command line allows data fields to be sent with a PUT request, and I wanted to do the same from PHP. Here is a snippet of code to show how I did it.
<?php
$data 
= array(
    
"id" => 10,
    
'name' => 'Pritom K Mondal',
    
"roll" => "00+060238=25 & this would be a nice day &amp; hmm.",
    
'items' => array(
        
'Yellow Jacket',
        
'item_2' => "Red Shirt",
        
'attributes' => array(
            
'color' => "Red",
            
"Size of Shirt" => array(
                
"Normal" => "1 inch",
                
"Midium Shirt" => "10 inch"
            
)
        )
    )
);
 

$ch   curl_init("http://localhost/ck/put2.php");
curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
curl_setopt($chCURLOPT_CUSTOMREQUEST"PUT"); 
curl_setopt($chCURLOPT_POSTFIELDSmakeRawQuery($data)); 
$response curl_exec($ch);
if (!
$response) {
    return 
false;
}
 

print_r($response);

function 
makeRawQuery($data$keyPrefix "")
{
    
$query "";
    foreach (
$data as $key => $value) {
        if (
is_array($value)) {
            if (
strlen($keyPrefix) > 0) {
                
$keyPrefixDummy $keyPrefix "[" $key "]";
            } else {
                
$keyPrefixDummy $key;
            }
            
$query .= makeRawQuery($value$keyPrefixDummy);
        } else {
            if (
strlen($keyPrefix) > 0) {
                
$key $keyPrefix "[" $key "]";
            }
            
$query .= $key "=" rawurlencode($value) . "&";
        }
    }
    return 
$query;
}
 

?>

put2.php

<?php
echo "RECEIVED DATA: \n"; parse_str(file_get_contents("php://input"), $post_vars);
print_r($post_vars);
echo 
"\nREQUEST METHOD: " $_SERVER['REQUEST_METHOD'];?>

And output is as following of print_r($response) in put.php:

RECEIVED DATA: 
Array
(
    [id] => 10
    [name] => Pritom K Mondal
    [roll] => 00+060238=25 & this would be a nice day &amp; hmm.
    [items] => Array
        (
            [0] => Yellow Jacket
            [item_2] => Red Shirt
            [attributes] => Array
                (
                    [color] => Red
                    [Size of Shirt] => Array
                        (
                            [Normal] => 1 inch
                            [Midium Shirt] => 10 inch
                        )

                )

        )

)

REQUEST METHOD: PUT

Wednesday, July 3, 2013

Cloudant built in function for sum count and stats


Built-in reduces

While you can define your own reduce functions, it's often the case that your reduce is going to be doing a simple count or sum operation. There are a handful of built in reduce functions; _sum, _count and _stats. If you can use these functions you should - they're faster than a javascript reduce (since they avoid serialisation between erlang and javascript) and are very well tested.
_sum
Produces the sum of all values for a key, values must be numeric
_count
Produces the row count for a given key, values can be any valid json
_stats
Produces a json structure containing sum, count, min, max and sum squared, values must be numeric
To use a built-in reduce, just put its name in place of the javascript reduce function inside your view.

{
    "_id": "_design/views103",
    "_rev": "8-1798b34c9929eb36d3bc04f99d2b5445",
    "indexes": {
        "animals": {
            "index":
                "function(doc){\n
                    index(\"default\", doc._id);\n\n
                    if (doc['customerID']){\n    index(\"customerID\", doc['customerID'], {\"store\": \"yes\"});\n  }\n\n
                    if (doc['trxnStatus']){\n    index(\"trxnStatus\", doc['trxnStatus'], {\"store\": \"yes\"});\n  }\n\n
                    if (doc['createdStamp']){\n    index(\"createdStamp\", doc['createdStamp'], {\"store\": \"yes\"});\n  }\n\n
                    if (doc['paymentType']){\n    index(\"paymentType\", doc['paymentType'], {\"store\": \"yes\"});\n  }\n\n
                    if (doc['returnAmount']){\n    index(\"returnAmount\", doc['returnAmount'], {\"store\": \"yes\"});\n  }\n\n
                    if (doc['trxnNumber']){\n    index(\"trxnNumber\", doc['trxnNumber'], {\"store\": \"yes\"});\n  }\n\n
                    if (doc['trxnReference']){\n    index(\"trxnReference\", doc['trxnReference'], {\"store\": \"yes\"});\n  }\n\n
                    if (doc['authCode']){\n    index(\"authCode\", doc['authCode'], {\"store\": \"yes\"});\n
                }\n\n
            }"
        }
    },
    "views": {
        "returnAmount_sum": {
            "map": "function(doc) {\n  if(doc.returnAmount && doc.customerID){\n    emit(doc.customerID, doc.returnAmount);\n  }\n}",
            "reduce": "function (keys, values, rereduce) {\nreturn (values);\n}"
        }
    }
}
https://pritom.cloudant.com/transactions/_design/views103/_view/returnAmount_sum
https://cloudant.com/for-developers/views/#pageArea 
{
  "_id": "_design/name",
  "views": {
    "view1": {
      "map":"function(doc){emit(doc.field, 1)}",
      "reduce": "function(key, value, rereduce){return sum(values)}"
    }
  }
}

Cloudant search by indexes and set limit pagination


$cloudantLimit = 2;
$posts = array(
    "q" => "customerID:cid_100",
    "include_docs" => "true",
    "sort" => json_encode("-createdStamp"),
    "limit" => $cloudantLimit
);
$totalResult = array();
$bookmark = null;
$skip = 0;
while(true) {
    if($bookmark != null) {
        $posts["bookmark"] = $bookmark;
    }
    $loadMore = false;
    $result = getTransactionHistory($this->userName, $this->password, $posts);
    if($result != null && isset($result["code"]) && $result["code"] == 200 && isset($result["response"]) && strlen(trim($result["response"])) > 0) {
        $result200 = json_decode($result["response"]);
        if(isset($result200->total_rows)
            && isset($result200->bookmark)
            && isset($result200->rows) && is_array($result200->rows) && count($result200->rows) > 0) {
            $bookmark = $result200->bookmark;
            array_push($totalResult, $result["response"]);
            $skip = $skip + $cloudantLimit;
            if($result200->total_rows > $skip) {
                $loadMore = true;
            }
        }
    }
    if(!$loadMore) {
        break;
    }
}

function getTransactionHistory($userName, $password, $posts = null) {
    $headers[0] = "Authorization: Basic " . base64_encode("$userName:$password");
    $headers[1] = "Content-Type: application/json";

    return makeCurlCall(
        "https://$userName.cloudant.com/transactions/_design/views103/_search/animals",
        "GET",
        $headers,
        $posts
    );
}

function makeCurlCall($url, $method = "GET", $headers = null, $gets = null, $posts = null) {
    $ch = curl_init();
    if($gets != null)
    {
        $url.="?".(http_build_query($gets));
    }
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    if($posts != null)
    {
        curl_setopt($ch, CURLOPT_POSTFIELDS, $posts);
    }
    if($method == "POST") {
        curl_setopt($ch, CURLOPT_POST, true);
    } else if($method == "PUT") {
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
    } else if($method == "HEAD") {
        curl_setopt($ch, CURLOPT_NOBODY, true);
    }
    if($headers != null && is_array($headers))
    {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    }
    $response = curl_exec($ch);
    $code = curl_getinfo($ch,CURLINFO_HTTP_CODE);

    curl_close($ch);
    return array(
        "code" => $code,
        "response" => $response
    );
}

NAB Xmlapi payment using php

Download the pdf document for transaction codes and other information

testUrl = "https://transact.nab.com.au/test/xmlapi/payment";
liveUrl = "https://transact.nab.com.au/xmlapi/payment";

NAB Transact XML API – Public Test Account Details
Merchant ID: XYZ0010
Transaction Password: abcd1234

Xml sent to NAB for processing

$nabXml = "<NABTransactMessage>
    <MerchantInfo>
        <merchantID>XYZ0010</merchantID>
        <password>abcd1234</password>
    </MerchantInfo>
    <RequestType>Payment</RequestType>
    <Payment>
        <TxnList count='1'>
            <Txn ID='1'>
                <txnType>0</txnType>
                <txnSource>23</txnSource>
                <amount>5000</amount>
                <currency>AUD</currency>
                <purchaseOrderNo>100000</purchaseOrderNo>
                <CreditCardInfo>
                    <cardNumber>4444333322221111</cardNumber>
                    <cvv>123</cvv>
                    <expiryDate>01/15</expiryDate>
                </CreditCardInfo>
            </Txn>
        </TxnList>
    </Payment>
</NABTransactMessage>";

Php code to execute payment using xml api

$result = makeCurlCall(
    $testNab, /* CURL URL */
    "POST", /* CURL CALL METHOD */
    array( /* CURL HEADERS */
        "Content-Type: text/xml; charset=utf-8",
        "Accept: text/xml",
        "Pragma: no-cache",
        "Content_length: ".strlen(trim($nabXml))
    ),
    null, /* CURL GET PARAMETERS */
    $nabXml /* CURL POST PARAMETERS AS XML */
);

makeCurlCall function

function makeCurlCall($url, $method = "GET", $headers = null, $gets = null, $posts = null) {
    $ch = curl_init();
    if($gets != null)
    {
        $url.="?".(http_build_query($gets));
    }
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    if($posts != null)
    {
        curl_setopt($ch, CURLOPT_POSTFIELDS, $posts);
    }
    if($method == "POST") {
        curl_setopt($ch, CURLOPT_POST, true);
    } else if($method == "PUT") {
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
    } else if($method == "HEAD") {
        curl_setopt($ch, CURLOPT_NOBODY, true);
    }
    if($headers != null && is_array($headers))
    {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    }
    $response = curl_exec($ch);
    $code = curl_getinfo($ch,CURLINFO_HTTP_CODE);

    curl_close($ch);
    return array(
        "code" => $code,
        "response" => $response
    );
}

And the response from NAB is like this, parse the xml received from nab


<? xml version = "1.0" encoding = "UTF-8" standalone = "no" ?>
<NABTransactMessage>
    <MessageInfo>
        <messageID/>
        <messageTimestamp>20130307120339466000+600</messageTimestamp>
        <apiVersion/>
    </MessageInfo>
    <RequestType>Payment</RequestType>
    <MerchantInfo>
        <merchantID>XYZ0010</merchantID>
    </MerchantInfo>
    <Status>
        <statusCode>000</statusCode>
        <statusDescription>Normal</statusDescription>
    </Status>
    <Payment>
        <TxnList count="1">
            <Txn ID="1">
                <txnType>0</txnType>
                <txnSource>23</txnSource>
                <amount>2500</amount>
                <currency>AUD</currency>
                <purchaseOrderNo>8547963513-1372817009</purchaseOrderNo>
                <approved>Yes</approved>
                <responseCode>00</responseCode>
                <responseText>Approved</responseText>
                <settlementDate>20130703</settlementDate>
                <txnID>503578</txnID>
                <authID/>
                <CreditCardInfo>
                    <pan>444433...111</pan>
                    <expiryDate>01/15</expiryDate>
                    <cardType>6</cardType>
                    <cardDescription>Visa</cardDescription>
                </CreditCardInfo>
            </Txn>
        </TxnList>
    </Payment>
</NABTransactMessage>
https://docs.google.com/file/d/0B5nZNPW48dpFNmVpdi1PRHkyd2c/edit?usp=sharing

Monday, July 1, 2013

Cakephp get view file content to a variable from controller

use Cake\View\View;

$html = ''; 
$this->autoRender = false; 
ob_start(); 

$view = new View($this->request);
# OR BELOW
$view = new View($this); 

$view->layout = null; 

/* controller name, a folder exists in views folder */ 
$view->viewPath = "FolderName"; 

/* variable send to view file */ 
$view->set("var", $var); 

$html .= $view->render("file_name"); 
/* a file exists in Views/FolderName/ folder/file_name.ctp */ 

ob_end_clean();