Integrate Authorize.net (Echeck.net) payment method in Magento 1.7.0.2 - magento-1.7

I need to integrate the Authorize.net (Echeck.net) payment method for my magento site.I have googled but i dont find Please suggest if there is any extensions for the payment method or else can we achieve this by coding.I am using magento 1.7.0.2.
Thanks in Advance!

The Official Beta release from authorize.net is available on Magento market(Magento Connect). This module is tested only in sandbox and currently in Beta status and probably compateble with 1.4 and 1.6. have not tried with 1.7 yet. you can try it if works. Please find the module at following link
http://www.magentocommerce.com/magento-connect/echeck-payment-method-authorize-net.html
If you need to customise the extention feel free to contact at contact#sgssandhu.com or http://oxosolutions.com/
Thanks

Hi here is working example of ECHECK through curl request & parsing of Response with delimiter:
public function curlProcessECHECK(){
$query = "";
// Login Information
$query .= "x_login=" . urlencode($this->credentials->username) . "&";
$query .= "x_tran_key=" . urlencode($this->credentials->password) . "&";
$query .= "x_version=" . "3.1" . "&";
$query .= "x_delim_data=" . "TRUE" . "&";
$query .= "x_delim_char=" . "|" . "&";
$query .= "x_relay_response=" . "FALSE" . "&";
$query .= "x_amount=" . urlencode(number_format($data['orderTotalAmt'], 2, ".", "")) . "&";
// ECHECk payments..... code to check ECHECK request
switch ($data['bank_acct_type'])
{
case 'checking':
$echecktype = 'PPD';
break;
case 'businessChecking':
$echecktype = 'CCD';
break;
case 'savings':
$echecktype = 'PPD';
break;
default:
$echecktype = 'PPD';
break;
}
$query .= "x_method=ECHECK&";
$query .= "x_bank_name=" . urlencode($data['bank_name']) . "&";
$query .= "x_echeck_type=" . urlencode($echecktype) . "&"; //CCD, PPD, TEL ---[ARC, BOC]- bank_check_number ll be required, [WEB] recurring_billing ll be required.
$query .= "x_bank_acct_type=" . urlencode($data['bank_acct_type']) . "&";
$query .= "x_bank_acct_num=" . urlencode($data['bank_acct_num']) . "&";
$query .= "x_bank_aba_code=" . urlencode($data['bank_aba_code']) . "&"; // aba code should be valid get from google US based banks
$query .= "x_bank_acct_name=" . urlencode($data['bank_acct_name']) . "&";
$query .= "x_description=" . (isset($data['orderDescription']) ? urlencode($data['orderDescription']) : "") . "&";
$query .= "x_first_name=" . (isset($data['billingFirstName']) ? urlencode($data['billingFirstName']) : $data['firstName']) . "&";
$query .= "x_last_name=" . (isset($data['billingLastName']) ? urlencode($data['billingLastName']) : $data['lastName']) . "&";
$query .= "x_address=" . (isset($data['billingAddress1']) ? urlencode($data['billingAddress1']) : "") . "&";
$query .= "x_state=" . (isset($data['billingState']) ? urlencode($data['billingState']) : "") . "&";
$query .= "x_zip=" . (isset($data['billingZip']) ? urlencode($data['billingZip']) : "") . "&";
if($this->env == 1) {
$query .= "x_test_request=TRUE&";
}
$query .= "x_type=AUTH_CAPTURE";
$output = array();
$url = 'https://test.authorize.net/gateway/transact.dll';// TestMode
$ch_response = null;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
// curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
$ch_response = curl_exec($ch);
// Check that a connection was made
if (curl_error($ch)) {
// If it wasn't...
$output['status'] = "Failure";
$output['response']['code'] = '-1';
$output['data'] = null;
$output['response']['responseMsg'] = curl_error($ch);
$output['response']['gateway_response_code'] ='000';
$output['response']['responsetext']= " No response from gateway";
$output['response']['transactionid'] = '';
$output['response']['init'] ="no";
$output['response']['response_code']='000';
} else {
$output['status'] = 'Success';
$output['data'] = $ch_response;
$output = $this->processResponse($output);
}
echo '<pre>';print_r($output);die;
}
Now parse the result
public function processResponse($output){
$response_array=$output;
if ($response_array) {
// Split Array
$encap_char = "|";
$response_array = explode($encap_char, $response_array['data']);
//echo"<pre>";print_r($response_array);die;
/**
* If AuthorizeNet doesn't return a delimited response.
*/
if (count($response_array) < 10) {
$approved = false;
$error = true;
$error_message = "Unrecognized response from AuthorizeNet: ";
return;
}
// Set all fields
$response_code = $response_array[0];
$response_subcode = $response_array[1];
$response_reason_code = $response_array[2];
$response_reason_text = $response_array[3];
$authorization_code = $response_array[4];
$avs_response = $response_array[5];
$transaction_id = $response_array[6];
$invoice_number = $response_array[7];
$description = $response_array[8];
$amount = $response_array[9];
$method = $response_array[10];
$transaction_type = $response_array[11];
$customer_id = $response_array[12];
$first_name = $response_array[13];
$last_name = $response_array[14];
$company = $response_array[15];
$address = $response_array[16];
$city = $response_array[17];
$state = $response_array[18];
$zip_code = $response_array[19];
$country = $response_array[20];
$phone = $response_array[21];
$fax = $response_array[22];
$email_address = $response_array[23];
$ship_to_first_name = $response_array[24];
$ship_to_last_name = $response_array[25];
$ship_to_company = $response_array[26];
$ship_to_address = $response_array[27];
$ship_to_city = $response_array[28];
$ship_to_state = $response_array[29];
$ship_to_zip_code = $response_array[30];
$ship_to_country = $response_array[31];
$tax = $response_array[32];
$duty = $response_array[33];
$freight = $response_array[34];
$tax_exempt = $response_array[35];
$purchase_order_number = $response_array[36];
$md5_hash = $response_array[37];
$card_code_response = $response_array[38];
$cavv_response = $response_array[39];
$account_number = $response_array[50];
$card_type = $response_array[51];
$split_tender_id = $response_array[52];
$requested_amount = $response_array[53];
$balance_on_card = $response_array[54];
// $approved = ($response_code == self::APPROVED);
// $declined = ($response_code == self::DECLINED);
// $error = ($response_code == self::ERROR);
// $held = ($response_code == self::HELD);
$approved = "";
$declined = "";
$error = "";
$held = "";
if ($response_code == 1) {
$result['response']['response_code'] = 100;
$result['response']['gateway_response_code'] = 100;
$result['response']['responsetext'] = "Success";
$result['status'] = 'success';
} elseif ($response_code == 2) {
$result['response']['response_code'] = 800;
$result['response']['gateway_response_code'] = 800;
$result['response']['responsetext'] = "Declined";
$result['status'] = $response_reason_text;
} else {
$result['response']['response_code'] = $response_code;
$result['response']['gateway_response_code'] = $response_code;
$result['response']['responsetext'] = $response_reason_text;
$result['status'] = $response_reason_text;
}
$result['method'] = $method;
$result['md5_hash'] = $md5_hash;
$result['card_type'] = $card_type;
$result['account_number'] = $account_number;
$result['response']['transactionid'] = $transaction_id;
$result['response']['processor_id'] = "";
$result['response']['cvvresponse'] = $cavv_response;
$result['response']['avsresponse'] = $avs_response;
$result['response']['authcode'] = $authorization_code;
$result['response']['type'] = "Sale";
$result['response']['init'] = "no";
return $result;
}
}

Related

page has Too many redirects from mail.php file?

I hope someone can help me. I have a page with a form and then the information
is emailed to me. the code below seems to be redirecting to the same page over and over again. It used to work for years now its not always working.
any help appreciated. Thanks Steve
<?php
//****************************************
//edit here
$senderName = 'WEB';
$senderEmail = 'site#example.com';
$targetEmail = 'contact#sellmydiabeticteststrips.com';
$messageSubject = 'Message from web-site';
$redirectToReferer = true;
$redirectURL = 'contact.html';
//****************************************
// mail content
$ufname = $_POST['ufname'];
$uaddress = $_POST['uaddress'];
$uemail = $_POST['uemail'];
$utel = $_POST['utel'];
$ucity = $_POST['ucity'];
$ustate = $_POST['ustate'];
$uzip = $_POST['uzip'];
$ubrand = $_POST['ubrand'];
$unumber = $_POST['unumber'];
$ucheck = $_POST['ucheck'];
$agree = $_POST['agree'];
// collect interests data
$interestsString = '';
for($i = 0; $i < count($interests); $i++) {
$interestsString .= $interests[$i].($i < count($interests) - 1 ? ', ' : '');
}
// prepare message text
$messageText = 'First Name: '.$ufname."\n".
'Address: '.$uaddress."\n".
'Email: '.$uemail."\n".
'Telephone: '.$utel."\n".
'City: '.$ucity."\n".
'State: '.$ustate."\n".
'Zip: '.$uzip."\n".
'Brand of test strips: '.$ubrand."\n".
'Number of boxes: '.$unumber."\n".
'Check: '.$ucheck."\n".
'Terms and Conditions: '.$agree."\n";
if($interestsString) {
$messageText .= 'Kinderen wonen bij mij: '.$interestsString."\n";
}
// send email
$senderName = "=?UTF-8?B?" . base64_encode($senderName) . "?=";
$messageSubject = "=?UTF-8?B?" . base64_encode($messageSubject) . "?=";
$messageHeaders = "From: " . $senderName . " <" . $senderEmail . ">\r\n"
. "MIME-Version: 1.0" . "\r\n"
. "Content-type: text/plain; charset=UTF-8" . "\r\n";
if (preg_match('/^[_.0-9a-z-]+#([0-9a-z][0-9a-z-]+.)+[a-z]{2,4}$/',$targetEmail,$matches))
mail($targetEmail, $messageSubject, $messageText, $messageHeaders);
// redirect
if($redirectToReferer) {
header("Location: ".#$_SERVER['HTTP_REFERER'].'#sent');
} else {
header("Location: ".$redirectURL);
}
?>

Facebook messenger bot - receives single and very first message

Facebook messenger bot - receives single and very first message continuously at every 2 minutes.
I have created bot in PHP and set webhook. But I am receiving webhook trigger at every two minutes no matter I have added/received new message or not.
One more thing is that we are receiving only very first messages. There are so many new messages after that message but we are receiving single message only.
Where am I incorrect? I have followed this article :
http://blog.adnansiddiqi.me/develop-your-first-facebook-messenger-bot-in-php/
We got the solution:
$input = json_decode(file_get_contents('php://input'), true);
$sender = $input['entry'][0]['messaging'][0]['sender']['id'];
$message = isset($input['entry'][0]['messaging'][0]['message']['text']) ? $input['entry'][0]['messaging'][0]['message']['text'] : '';
if (!empty($input['entry'][0]['messaging'])) {
foreach ($input['entry'][0]['messaging'] as $message) {
$command = "";
// When bot receive message from user
if (!empty($message['message'])) {
$command = $message['message']['text'];
}
// When bot receive button click from user
else if (!empty($message['postback'])) {
$command = $message['postback']['payload'];
}
}
}
$pagetoken = "PAGE TOKEN"; // Facebook TOKEN
if ($command) {
if ($command == "hii") {
$message_to_reply = "test_response";
} else if ($command == "need more info") {
$message_to_reply = "Please fill form at link ";
} else if ($command == "\ud83d\ude00") {
$message_to_reply = "smiley";
}
if ($message_to_reply != "") {
$url = "https://graph.facebook.com/v2.6/me/messages?access_token=$pagetoken";
//Initiate cURL.
$ch = curl_init($url);
//The JSON data.
$jsonData = '{
"recipient":{
"id":"' . $sender . '"
},
"message":{
"text":"' . $message_to_reply . '"
}
}';
$jsonDataEncoded = $jsonData;
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
if (!empty($input['entry'][0]['messaging'][0]['message'])) {
$result = curl_exec($ch);
}
curl_close($ch);
}
}
header('HTTP/1.1 200 OK'); // This line needs to be added
die;

PAY PAL IPN stop working

My code stop working, I have made some changes like $res=trim($res); as I saw in another question but still not working.
The code was perfectly working including automatic post in Facebook and Tweeter.
Please, could someone check my code and help me to fix it?
<?php
// Revision Notes
// 11/04/11 - changed post back url from https://www.paypal.com/cgi-bin/webscr to https://ipnpb.paypal.com/cgi-bin/webscr
// For more info see below:
// https://www.x.com/content/bulletin-ip-address-expansion-paypal-services
// "ACTION REQUIRED: if you are using IPN (Instant Payment Notification) for Order Management and your IPN listener script is behind a firewall that uses ACL (Access Control List) rules which restrict outbound traffic to a limited number of IP addresses, then you may need to do one of the following:
// To continue posting back to https://www.paypal.com to perform IPN validation you will need to update your firewall ACL to allow outbound access to *any* IP address for the servers that host your IPN script
// OR Alternatively, you will need to modify your IPN script to post back IPNs to the newly created URL https://ipnpb.paypal.com using HTTPS (port 443) and update firewall ACL rules to allow outbound access to the ipnpb.paypal.com IP ranges (see end of message)."
/////////////////////////////////////////////////
/////////////Begin Script below./////////////////
/////////////////////////////////////////////////
// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-validate';
foreach ($_POST as $key => $value) {
$value = urlencode(stripslashes($value));
$value = preg_replace('/(.*[^%^0^D])(%0A)(.*)/i','${1}%0D%0A${3}',$value);// IPN fix
$req .= "&$key=$value";
}
// post back to PayPal system to validate
$header .= "POST /cgi-bin/webscr HTTP/1.1\r\n";
$header .= "Host: www.paypal.com\r\n";
//$header .= "Host: www.sandbox.paypal.com\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
// If testing on Sandbox use:
//$fp = fsockopen ('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30);
$fp = fsockopen ('ssl://ipnpb.paypal.com', 443, $errno, $errstr, 30);
// assign posted variables to local variables
$item_name = $_POST['item_name'];
$business = $_POST['business'];
$item_number = $_POST['item_number'];
$payment_status = $_POST['payment_status'];
$mc_gross = $_POST['mc_gross'];
$payment_currency = $_POST['mc_currency'];
$txn_id = $_POST['txn_id'];
$receiver_email = $_POST['receiver_email'];
$receiver_id = $_POST['receiver_id'];
$quantity = $_POST['quantity'];
$num_cart_items = $_POST['num_cart_items'];
$payment_date = $_POST['payment_date'];
$first_name = $_POST['fir st_name'];
$last_name = $_POST['last_name'];
$payment_type = $_POST['payment_type'];
$payment_status = $_POST['payment_status'];
$payment_gross = $_POST['payment_gross'];
$payment_fee = $_POST['payment_fee'];
$settle_amount = $_POST['settle_amount'];
$memo = $_POST['memo'];
$payer_email = $_POST['payer_email'];
$txn_type = $_POST['txn_type'];
$payer_status = $_POST['payer_status'];
$address_street = $_POST['address_street'];
$address_city = $_POST['address_city'];
$address_state = $_POST['address_state'];
$address_zip = $_POST['address_zip'];
$address_country = $_POST['address_country'];
$address_status = $_POST['address_status'];
$item_number = $_POST['item_number'];
$tax = $_POST['tax'];
$option_name1 = $_POST['option_name1'];
$option_selection1 = $_POST['option_selection1'];
$option_name2 = $_POST['option_name2'];
$option_selection2 = $_POST['option_selection2'];
$for_auction = $_POST['for_auction'];
$invoice = $_POST['invoice'];
$custom = $_POST['custom'];
$notify_version = $_POST['notify_version'];
$verify_sign = $_POST['verify_sign'];
$payer_business_name = $_POST['payer_business_name'];
$payer_id =$_POST['payer_id'];
$mc_currency = $_POST['mc_currency'];
$mc_fee = $_POST['mc_fee'];
$exchange_rate = $_POST['exchange_rate'];
$settle_currency = $_POST['settle_currency'];
$parent_txn_id = $_POST['parent_txn_id'];
$pending_reason = $_POST['pending_reason'];
$reason_code = $_POST['reason_code'];
// subscription specific vars
$subscr_id = $_POST['subscr_id'];
$subscr_date = $_POST['subscr_date'];
$subscr_effective = $_POST['subscr_effective'];
$period1 = $_POST['period1'];
$period2 = $_POST['period2'];
$period3 = $_POST['period3'];
$amount1 = $_POST['amount1'];
$amount2 = $_POST['amount2'];
$amount3 = $_POST['amount3'];
$mc_amount1 = $_POST['mc_amount1'];
$mc_amount2 = $_POST['mc_amount2'];
$mc_amount3 = $_POST['mcamount3'];
$recurring = $_POST['recurring'];
$reattempt = $_POST['reattempt'];
$retry_at = $_POST['retry_at'];
$recur_times = $_POST['recur_times'];
$username = $_POST['username'];
$password = $_POST['password'];
//auction specific vars
$for_auction = $_POST['for_auction'];
$auction_closing_date = $_POST['auction_closing_date'];
$auction_multi_item = $_POST['auction_multi_item'];
$auction_buyer_id = $_POST['auction_buyer_id'];
//DB connect creds and email
$notify_email = "xxxxxx#gmail.com"; //email address to which debug emails are sent to
$DB_Server = "localhost"; //your MySQL Server
$DB_Username = "xxxxx"; //your MySQL User Name
$DB_Password = "xxxxx"; //your MySQL Password
$DB_DBName = "xxxxx"; //your MySQL Database Name
if (!$fp)
{
// HTTP ERROR
}
else
{
fputs ($fp, $header . $req);
while (!feof($fp))
{
$res = fgets ($fp, 1024);
$res=trim($res);
if (strcmp ($res, "VERIFIED") == 0)
//if (strcmp ($res, "VERIFIED\r\n") == 0)
{
//create MySQL connection
$Connect = #mysql_connect($DB_Server, $DB_Username, $DB_Password)
or die("Couldn't connect to MySQL:<br>" . mysql_error() . "<br>" . mysql_errno());
//select database
$Db = #mysql_select_db($DB_DBName, $Connect)
or die("Couldn't select database:<br>" . mysql_error(). "<br>" . mysql_errno());
$fecha = date("m")."/".date("d")."/".date("Y");
$fecha = date("Y").date("m").date("d");
//check if transaction ID has been processed before
$checkquery = "select txnid from paypal_payment_info where txnid='".$txn_id."'";
$sihay = mysql_query($checkquery) or die("Duplicate txn id check query failed:<br>" . mysql_error() . "<br>" . mysql_errno());
$nm = mysql_num_rows($sihay);
if ($nm == 0)
{
//execute query
$strQuery = "insert into paypal_payment_info(paymentstatus,buyer_email,receiver_email,firstname,lastname,street,city,state,zipcode,country,mc_gross,mc_fee,quantity,memo,paymenttype,paymentdate,txnid,pendingreason,reasoncode,tax,datecreation) values ('".$payment_status."','".$payer_email."','".$receiver_email."','".$first_name."','".$last_name."','".$address_street."','".$address_city."','".$address_state."','".$address_zip."','".$address_country."','".$mc_gross."','".$mc_fee."','".$quantity."','".$memo."','".$payment_type."','".$payment_date."','".$txn_id."','".$pending_reason."','".$reason_code."','".$tax."','".$fecha."')";
$result = mysql_query("insert into paypal_payment_info(paymentstatus,buyer_email,receiver_email,firstname,lastname,street,city,state,zipcode,country,mc_gross,mc_fee,quantity,memo,paymenttype,paymentdate,txnid,pendingreason,reasoncode,tax,datecreation) values ('".$payment_status."','".$payer_email."','".$receiver_email."','".$first_name."','".$last_name."','".$address_street."','".$address_city."','".$address_state."','".$address_zip."','".$address_country."','".$mc_gross."','".$mc_fee."','".$quantity."','".$memo."','".$payment_type."','".$payment_date."','".$txn_id."','".$pending_reason."','".$reason_code."','".$tax."','".$fecha."')")
or die("Default - paypal_payment_info, Query failed:<br>" . mysql_error() . "<br>" . mysql_errno());
{
$consumerKey = 'ccYgLrtBUrgIPJDQ';
$consumerSecret = '4qXLLXdQPcKqAqKscYQH9p9m3cznyVWYc4v8';
$oAuthToken = 'uVgkQTC0BLNT9V9vTpc25poxDgIomCgMbw';
$oAuthSecret = 'L8rfc6A1Ii5cMeuYEhf6hwkc3aATyo';
require_once('twitteroauth.php');
$tweet = new TwitterOAuth($consumerKey, $consumerSecret, $oAuthToken, $oAuthSecret);
$tweet->post('statuses/update', array('status' => 'Last donation US$ '.$mc_gross.' to '.$item_name.' '));
}
mail($notify_email, "VERIFIED IPN", "$res\n $req\n $strQuery\n $struery\n $strQuery2");
$sql = mysql_query(" UPDATE cadastros SET amount='$mc_gross'-'$mc_fee'+amount, mc_gross = '$mc_gross' , mc_fee ='$mc_fee', payment_date = '$payment_date',pay_date = now() WHERE receiver_email='$receiver_email'");
$result = mysql_query($sql) or die( mysql_error() );
}
else
{
// send an email
mail($notify_email, "VERIFIED DUPLICATED TRANSACTION", "$res\n $req\n $strQuery\n $struery\n $strQuery2");
}
// if the IPN POST was 'INVALID'...do this
}
else if (strcmp ($res, "INVALID") == 0)
{
// log for manual investigation
mail($notify_email, "INVALID IPN", "$res\n $req");
}
}
fclose ($fp);
}
?>
The HOST tag in the header has to match the URL you are using with fsockopen.
Try this:
$sandbox = 1;
$paypalURL = $sandbox ? 'www.sandbox.paypal.com' : 'www.paypal.com';
// Create http header
$header = "POST /cgi-bin/webscr HTTP/1.1\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n";
$header .= "Host: $paypalURL\r\n";
$header .= "Connection: close\r\n\r\n";
// Post back to PayPal system to verify
$fp = fsockopen('ssl://'.$paypalURL, 443, $errno, $errstr, 30);

Modify code to auto complete on taxonomies instead of title

I've been trying for hours to modify this plugin to work with custom taxonomies instead of post titles and/or post content
http://wordpress.org/extend/plugins/kau-boys-autocompleter/
Added the code / part of the plugin where I think the modification should be done. I could post some stuff I tried but I think it would just confuse people, I don't think I ever came close. Normally I can modify code perfectly but just can't seem to find it. I've tried this method posted here.
http://wordpress.org/support/topic/autocomplete-taxonomy-in-stead-of-title-or-content
But it doesn't work. I've tried searching for possible solutions around his suggestion but I'm starting to think his suggestion isn't even close to fixing it.
if(WP_DEBUG){
error_reporting(E_ALL);
} else {
error_reporting(0);
}
header('Content-Type: text/html; charset=utf-8');
// remove the filter functions from relevanssi
if(function_exists('relevanssi_kill')) remove_filter('posts_where', 'relevanssi_kill');
if(function_exists('relevanssi_query')) remove_filter('the_posts', 'relevanssi_query');
if(function_exists('relevanssi_kill')) remove_filter('post_limits', 'relevanssi_getLimit');
$choices = get_option('kau-boys_autocompleter_choices');
$framework = get_option('kau-boys_autocompleter_framework');
$encoding = get_option('kau-boys_autocompleter_encoding');
$searchfields = get_option('kau-boys_autocompleter_searchfields');
$resultfields = get_option('kau-boys_autocompleter_resultfields');
$titlelength = get_option('kau-boys_autocompleter_titlelength');
$contentlength = get_option('kau-boys_autocompleter_contentlength');
if(empty($choices)) $choices = 10;
if(empty($framework)) $framework = 'jQuery';
if(empty($encoding)) $encoding = 'UTF-8';
if(empty($searchfields)) $searchfields = 'both';
if(empty($resultfields)) $resultfields = 'both';
if(empty($titlelength)) $titlelength = 50;
if(empty($contentlength)) $contentlength = 120;
mb_internal_encoding($encoding);
mb_regex_encoding($encoding);
$words = '%'.$_REQUEST['q'].'%';
switch($searchfields){
case 'post_title' :
$where = 'post_title LIKE "'.$words.'"';
break;
case 'post_content' :
$where = 'post_content LIKE "'.$words.'"';
default :
$where = 'post_title LIKE "'.$words.'" OR post_content LIKE "'.$words.'"';
}
$wp_query = new WP_Query();
$wp_query->query(array(
's' => $_REQUEST['q'],
'showposts' => $choices,
'post_status' => 'publish'
));
$posts = $wp_query->posts;
$results = array();
foreach ($posts as $key => $post){
setup_postdata($post);
$title = strip_tags(html_entity_decode(get_the_title($post->ID), ENT_NOQUOTES, 'UTF-8'));
$content = strip_tags(strip_shortcodes(html_entity_decode(get_the_content($post->ID), ENT_NOQUOTES, 'UTF-8')));
if(mb_strpos(mb_strtolower(($searchfields == 'post_title')? $title : (($searchfields == 'post_content')? $content : $title.$content)), mb_strtolower($_REQUEST['q'])) !== false){
$results[] = array(
'url' => get_permalink($post->ID),
'title' => highlightSearchString(strtruncate($title, $titlelength, true), $_REQUEST['q']),
'content' => (($resultfields == 'both')? highlightSearchString(strtruncate($content, $contentlength, false, '[...]', $_REQUEST['q']), $_REQUEST['q']) : '')
);
}
}
printResults($results, $framework);
function highlightSearchString($value, $searchString){
if((version_compare(phpversion(), '5.0') < 0) && (strtolower(mb_internal_encoding()) == 'utf-8')){
$value = utf8_encode(html_entity_decode(utf8_decode($value)));
}
$regex_chars = '\.+?(){}[]^$';
for ($i=0; $i<mb_strlen($regex_chars); $i++) {
$char = mb_substr($regex_chars, $i, 1);
$searchString = str_replace($char, '\\'.$char, $searchString);
}
$searchString = '(.*)('.$searchString.')(.*)';
return mb_eregi_replace($searchString, '\1<span class="ac_match">\2</span>\3', $value);
}
function strtruncate($str, $length = 50, $cutWord = false, $suffix = '...', $needle = ''){
$str = trim($str);
if((version_compare(phpversion(), '5.0') < 0) && (strtolower(mb_internal_encoding()) == 'utf-8')){
$str = utf8_encode(html_entity_decode(utf8_decode($str)));
}else{
$str = html_entity_decode($str, ENT_NOQUOTES, mb_internal_encoding());
}
if(mb_strlen($str)>$length){
if(!empty($needle) && mb_strpos(mb_strtolower($str), mb_strtolower($needle)) > 0){
$pos = mb_strpos(mb_strtolower($str), mb_strtolower($needle)) + (mb_strlen($needle) / 2);
$startToShort = ($pos - ($length / 2)) < 0;
$endToShort = ($pos + ($length / 2)) > mb_strlen($str);
// build the prefix and suffix
$prefix = $suffix;
if($startToShort){
$prefix = '';
}
if($endToShort){
$suffix = '';
}
// set maximum length
$length = $length - mb_strlen($prefix) - mb_strlen($suffix);
// get the start
if($startToShort){
$start = 0;
} elseif($endToShort){
$start = mb_strlen($str) - $length;
} else {
$start = $pos - ($length / 2);
}
// shorten the string
$string = mb_substr($str, $start, $length);
if($cutWord){
return $prefix.$string.$suffix;
} else {
$firstWhitespace = ($startToShort)? 0 : mb_strpos($string, ' ');
$lastWhitespace =($endToShort)? mb_strlen($string) : mb_strrpos($string, ' ');
return $prefix.' '.(!empty($lastWhitespace)? mb_substr($string, $firstWhitespace, ($lastWhitespace - $firstWhitespace)) : $string).' '.$suffix;
}
} else {
$string = mb_substr($str, 0, $length - mb_strlen($suffix));
return (($cutWord) ? $string : mb_substr($string, 0, mb_strrpos($string, ' ')).' ').$suffix;
}
} else {
return $str;
}
}
function printResults($results, $framework){
if($framework == 'scriptaculous'){
echo '<ul>';
foreach($results as $result){
echo ' <li>
<a href="'.$result['url'].'">
<span class="title">'.$result['title'].'</span>
<span style="display: block;">'.$result['content'].'</span>
</a>
</li>';
}
echo '</ul>';
} else {
foreach($results as $result){
echo str_replace(array("\n", "\r", '|'), array(' ',' ', '|'), '<span class="title">'.$result['title'].'</span><p>'.$result['content'].'</p>')
.'|'
.str_replace(array("\n", "\r", '|'), array(' ',' ', '|'), $result['url'])
."\n";
}
}
}

PayPal sends multiple IPN's

I have this code, everything works fine. It's just that PayPal keeps resending multiple IPNs. I have read the forum of PayPal and they say that PayPal isn't getting a HTTP/1.1 200 OK from me, so it keeps resending the IPN. How would I go about this?
function sql_execute($sql){
$sql_connect = #mysql_connect($_SERVER['HTTP_HOST'].':3306','root', '****') or
die('Could not connect: ' . mysql_error());
mysql_select_db('4bkk');
mysql_query($sql);
$rows = mysql_affected_rows($sql_connect); //mysql_insert_id();
mysql_close();
return $rows;
}
function sql_query($sql){
// echo $sql;
$sql_connect = #mysql_connect($_SERVER['HTTP_HOST'].':3306','****', 'zzz111') or
die('Could not connect: ' . mysql_error());
mysql_select_db('4bkk');
$rs = mysql_query($sql) or die(mysql_error());
mysql_close();
return $rs;
}
function logtrace($o){
$q = "INSERT INTO log (trace, trace_time) VALUES ('$o', NOW() )";
sql_query($q);
}
function send_email($t,$s,$m,$h){
//mail($t, $s, $m, $h);
$fh = fopen('result_ipn_test.txt', 'w');
fwrite($fh, $t.' '.$s.' '.$m.' '.$h);
fclose($fh);
logtrace('Mail is sent and exit called');
exit();
}
logtrace('__________NEW SESSION__________');
$url = 'https://www.sandbox.paypal.com/cgi-bin/webscr';
$postFields = 'cmd=_notify-validate';
foreach($_POST as $key => $value)
{
$postFields .= "&$key=".urlencode($value);
}
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $postFields
));
$result = curl_exec($ch);
$info = curl_getinfo($ch);
logtrace($info['url']);
curl_close($ch);
//get buyers information from PAYPAL checkout
$email = $_POST['payer_email'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$amount = $_POST['amount3'];
$plan = $_POST['option_selection1'];
logtrace($email.' -- '.$active);
$q = "SELECT * FROM users WHERE email='$email' AND user_level='' AND active='unverified'"; //Unprocessed record = no user_level and active = 'unverified'
$ex = sql_execute($q);
//logtrace("THIS ".$q." => ".$ex);
if(sql_execute($q)){
logtrace('IT IS TRUE');
$flag = TRUE;
}
else{
logtrace('FALSE');
$flag = FALSE;
}
logtrace($result.' RESPONSE FROM PAYPAL');
if(($result=='VERIFIED') && $flag){ //Checks first if PayPal is valid, email address exists in
//records and checks if user_level='' and active='unverified',
//if not enters.
logtrace('USER IS READY FOR VERIFICATION');
$q = "SELECT * FROM users WHERE email='$email'";
$data = sql_query($q);
$con = mysql_fetch_array($data);
//Get buyers information from the database
$email2 = $con['email'];
$first_name = $con['first_name'];
$last_name = $con['last_name'];
$active = $con['active'];
$user_level = $con['user_level'];
logtrace('Emails match');
$u = "UPDATE users SET active='verified', user_level='$plan' WHERE email='$email' LIMIT 1";
if (sql_query($u)) { //Successful verification
logtrace('|| Update was sucessful');
}
else{ // Unsuccessful verification.
logtrace('|| Something went wrong with update.');
}
}
else{ // The user doesn't have any record in the database.
$q = "SELECT * FROM users WHERE email='$email' AND (user_level='Monthly' OR user_level='Quarterly' OR user_level='Yearly')";
if(sql_execute($q)){ // The user is already verified
logtrace('THE USER IS ALREADY VERIFIED');
}
else{ // The user does not exist.
logtrace('THE USER HAS NO RECORD ON DATABASE');
}
}
Please refer the sample code https://www.x.com/instant-payment-notification-4
Based on the above code you can try setting curl options for
CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1
CURLOPT_HTTPHEADER, array('Connection: Close')
in your above code where you set as curl_setopt_array ...
This should resolve your HTTP/1.1 200 OK issue I think.