PayPal IPN sometimes not updating database - paypal

For several weeks PayPal has not updated my database for some transactions. Maybe 3 out of 10 transactions are added to the database. Have no idea what's goin on. Before that, everything was fine. There are no errors, every single transaction in PayPal history is completed. I have no idea where the problem is.
Here's my ipn.php
<?php
if (gethostbyaddr($_SERVER['REMOTE_ADDR']) !== 'notify.paypal.com') {
exit();
}
// Require the functions to connect to database and fetch config values
require 'config.php';
require 'db.php';
// Fetch and sanitize POST and GET values
function getValue($value) {
return (!empty($value)) ? sanitize($value) : false;
}
function sanitize($data) {
return htmlentities(strip_tags(mysql_znote_escape_string($data)));
}
function VerifyPaypalIPN(array $IPN = null){
if(empty($IPN)){
$IPN = $_POST;
}
if(empty($IPN['verify_sign'])){
return null;
}
$IPN['cmd'] = '_notify-validate';
$PaypalHost = (empty($IPN['test_ipn']) ? 'www' : 'www.sandbox').'.paypal.com';
$cURL = curl_init();
curl_setopt($cURL, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($cURL, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($cURL, CURLOPT_SSLVERSION, 6);
curl_setopt($cURL, CURLOPT_CAINFO, __DIR__ . '/cert/cacert.pem');
curl_setopt($cURL, CURLOPT_URL, "https://{$PaypalHost}/cgi-bin/webscr");
curl_setopt($cURL, CURLOPT_ENCODING, 'gzip');
curl_setopt($cURL, CURLOPT_BINARYTRANSFER, true);
curl_setopt($cURL, CURLOPT_POST, true); // POST back
curl_setopt($cURL, CURLOPT_POSTFIELDS, $IPN); // the $IPN
curl_setopt($cURL, CURLOPT_HEADER, false);
curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);
curl_setopt($cURL, CURLOPT_FORBID_REUSE, true);
curl_setopt($cURL, CURLOPT_FRESH_CONNECT, true);
curl_setopt($cURL, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($cURL, CURLOPT_TIMEOUT, 60);
curl_setopt($cURL, CURLINFO_HEADER_OUT, true);
curl_setopt($cURL, CURLOPT_HTTPHEADER, array(
'Connection: close',
'Expect: ',
));
$Response = curl_exec($cURL);
$Status = (int)curl_getinfo($cURL, CURLINFO_HTTP_CODE);
curl_close($cURL);
if(empty($Response) or !preg_match('~^(VERIFIED|INVALID)$~i', $Response = trim($Response)) or !$Status){
return null;
}
if(intval($Status / 100) != 2){
return false;
}
return !strcasecmp($Response, 'VERIFIED');
}
// Fetch paypal configurations
$paypal = $config['paypal'];
$prices = $config['paypal_prices'];
// Send an empty HTTP 200 OK response to acknowledge receipt of the notification
header('HTTP/1.1 200 OK');
// Build the required acknowledgement message out of the notification just received
$req = 'cmd=_notify-validate';
foreach ($_POST as $key => $value) {
$value = urlencode(stripslashes($value));
$req .= "&$key=$value";
}
$postdata = $req;
// Assign payment notification values to local variables
$item_name = $_POST['item_name'];
$item_number = $_POST['item_number'];
$payment_status = $_POST['payment_status'];
$payment_amount = $_POST['mc_gross'];
$payment_currency = $_POST['mc_currency'];
$txn_id = getValue($_POST['txn_id']);
$receiver_email = getValue($_POST['receiver_email']);
$payer_email = getValue($_POST['payer_email']);
$custom = (int)$_POST['custom'];
$connectedIp = $_SERVER['REMOTE_ADDR'];
mysql_insert("INSERT INTO `paypal` VALUES ('0', '$txn_id', 'Connection from IP: $connectedIp', '0', '0', '0')");
$status = VerifyPaypalIPN();
if ($status) {
// Check that the payment_status is Completed
if ($payment_status == 'Completed') {
// Check that txn_id has not been previously processed
$txn_id_check = mysql_select_single("SELECT `txn_id` FROM `paypal` WHERE `txn_id`='$txn_id'");
if ($txn_id_check !== false) {
// Check that receiver_email is your Primary PayPal email
if ($receiver_email == $paypal['email']) {
$status = true;
$paidMoney = 0;
$paidPoints = 0;
foreach ($prices as $priceValue => $pointsValue) {
if ($priceValue == $payment_amount) {
$paidMoney = $priceValue;
$paidPoints = $pointsValue;
}
}
if ($paidMoney == 0) $status = false; // Wrong amount of money
if ($payment_currency != $paypal['currency']) $status = false; // Wrong currency
// Verify that the user haven't messed around with POST data
if ($status) {
// transaction log
mysql_insert("INSERT INTO `paypal` VALUES ('0', '$txn_id', '$payer_email', '$custom', '".$paidMoney."', '".$paidPoints."')");
// Process payment
$data = mysql_select_single("SELECT `premium_points` AS `old_points` FROM `accounts` WHERE `id`='$custom';");
// Give points to user
$new_points = $data['old_points'] + $paidPoints;
mysql_update("UPDATE `accounts` SET `premium_points`='$new_points' WHERE `id`='$custom'");
}
} else {
$pmail = $paypal['email'];
mysql_insert("INSERT INTO `paypal` VALUES ('0', '$txn_id', 'ERROR: Wrong mail. Received: $receiver_email, configured: $pmail', '0', '0', '0')");
}
}
}
} else {
// Something is wrong
mysql_insert("INSERT INTO `paypal` VALUES ('0', '$txn_id', 'ERROR: Invalid data. $postdata', '0', '0', '0')");
}
?>

You can review your account's IPN history at https://www.paypal.com/cgi-bin/webscr?cmd=_display-ipns-history
If you are receiving all the IPNs you expect, then you need to debug your listener. Add logging to determine where it's going wrong, such as not being able to do the post back to verify the IPN. Log everything to determine what the error is. Check your webserver logs as well.
Documentation regarding IPN is available at: https://developer.paypal.com/docs/api-basics/notifications/ipn/

Related

How to access data from onesignal additional data object in cordova ionic app

I want to access data i have assigned to the data variable of feilds array to be sent in onesignal message.
function sendMessage($received)
{
$content = array(
"en" => 'Current Data'
);
$data = $received;
$fields = array(
'app_id' => "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
'included_segments' => array('All'),
'contents' => $content,
'data' => $data, // => This is the data i want to access on
client side.
);
$response['feilds'] = $fields;
$fields = json_encode($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,
"https://onesignal.com/api/v1/notifications");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:
application/json; charset=utf-8',
'Authorization:Basic
Nzg0YmM2NzUtZWYyMC00NDZmLWE1ODItZDExZTU3OTXXXXXX'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$response['resp'] = curl_exec($ch);
curl_close($ch);
return $response;
}
I need help that how i can access the data variable there on client side in ionic app.
Below is what i am trying.
this.oneSignal.startInit('XXXXXXX-32ae-4025-b26b-
XXXXXXXXXX','XXXXXXXXX');
this.oneSignal.handleNotificationReceived().subscribe((jsonData) => {
if(jsonData.payload.additionalData)
{
this.myService.NotirefreshData(jsonData.payload.additionalData);
let ten = JSON.stringify(jsonData.payload.additionalData);
this.storage.set('current',ten);
this.presentAlert('From Server',ten);
this.storage.get('past').then((pri) => {
this.presentAlert('From Storage',JSON.parse(pri));
});
}
How should be the below statement to access the data variable to array feild received from server?
(jsonData.payload.additionalData.??????????????)
I have tried
(jsonData.payload.additionalData.feilds)
(jsonData.payload.additionalData.current) // as current is the name of an array
You don't need that subscribe() call. Simply pass in the handler into the function.
window.plugins.OneSignal
.startInit("YOUR_APP_ID")
.handleNotificationReceived(function(notificationData) {
alert("Notification Data Received:\n" + JSON.stringify(notificationData));
console.log('Notification Data Received: ' + JSON.stringify(notificationData));
})
.endInit();

Paypal transaction to me is verified (by API), but my account balance is $0.00

Paypal transaction yesterday was verified (by API (https://api.paypal.com/v1/payments/payment/)), but my account balance was $0.00.
Today the same API answers me ----> ["name"]=> string(19) "INVALID_RESOURCE_ID" ["message"]=> string(39) "The requested resource ID was not found" ["information_link"]=> string(54) "https://developer.paypal.com/docs/api/payments/#errors" ["debug_id"]=> string(13) "b39d1f444064e"
And balance is $0 again. How to fix it, there in my online store are verified payments, they get "verified" status during payment, by API query.. what to do now? Where to search the problem?
(Before that the Sandbox version worked fine).
Payment execution:
if($test_mode_paypal)
$execute_url = 'https://api.sandbox.paypal.com/v1/payments/payment/'.$pay_key.'/execute';
else
$execute_url = 'https://api.paypal.com/v1/payments/payment/'.$pay_key.'/execute';
$header = array();
$header[] = 'Content-type: application/json';
$header[] = 'Accept: application/json';
$header[] = 'Authorization: Bearer '.$accessToken;
$data ='{
"payer_id":"'.$payer_id.'"
}';
//open connection
$curl = curl_init();
//set connection properties
curl_setopt($curl, CURLOPT_URL, $execute_url);
curl_setopt($curl, CURLOPT_POST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_HTTPHEADER,$header);
//execute post
$response = curl_exec($curl);
//close connection
curl_close($curl);
$result = json_decode($response);
$response_arr = array();
if($result->state == 'approved')
{
$response_arr['status'] = 'ok';
$response_arr['message'] = $response;
return $response_arr;
}
Sounds like you created the payment but you never executed it.

Paypal error:14094410:SSL routines:SSL3_READ_BYTES:sslv3 alert handshake failure(35)

Hello i'm using paypal class in my e-commerce but when i put the code in my serverhost the paypal show me the mensage:
SetExpressCheckout failed: error:14094410:SSL routines:SSL3_READ_BYTES:sslv3 alert handshake failure(35)
this is my class:
class MyPayPal {
function PPHttpPost($methodName_, $nvpStr_, $PayPalApiUsername, $PayPalApiPassword, $PayPalApiSignature, $PayPalMode) {
// Set up your API credentials, PayPal end point, and API version.
$API_UserName = urlencode($PayPalApiUsername);
$API_Password = urlencode($PayPalApiPassword);
$API_Signature = urlencode($PayPalApiSignature);
$paypalmode = ($PayPalMode=='sandbox') ? '.sandbox' : '';
$API_Endpoint = "https://api-3t".$paypalmode.".paypal.com/nvp";
$version = urlencode('109.0');
// Set the curl parameters.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $API_Endpoint);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
// Turn off the server and peer verification (TrustManager Concept).
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
// Set the API operation, version, and API signature in the request.
$nvpreq = "METHOD=$methodName_&VERSION=$version&PWD=$API_Password&USER=$API_UserName&SIGNATURE=$API_Signature$nvpStr_";
// Set the request as a POST FIELD for curl.
curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);
// Get response from the server.
$httpResponse = curl_exec($ch);
if(!$httpResponse) {
exit("$methodName_ failed: ".curl_error($ch).'('.curl_errno($ch).')');
}
// Extract the response details.
$httpResponseAr = explode("&", $httpResponse);
$httpParsedResponseAr = array();
foreach ($httpResponseAr as $i => $value) {
$tmpAr = explode("=", $value);
if(sizeof($tmpAr) > 1) {
$httpParsedResponseAr[$tmpAr[0]] = $tmpAr[1];
}
}
if((0 == sizeof($httpParsedResponseAr)) || !array_key_exists('ACK', $httpParsedResponseAr)) {
exit("Invalid HTTP Response for POST request($nvpreq) to $API_Endpoint.");
}
return $httpParsedResponseAr;
}
}
Any idea how can i solve this problem?
Thanks a lot.

Paypal NVP REFUND API getting Error 10007

I am trying to refund the amount using the paypal nvp. And I am getting the following error
[TIMESTAMP] => 2013 04 06T13 48 19
[CORRELATIONID] => aac23709cc94a
[ACK] => Failure [VERSION] => 51 0
[BUILD] => 5618210
[L_ERRORCODE0] => 10007
[L_SHORTMESSAGE0] => Permission denied
[L_LONGMESSAGE0] => You do not have permission to refund this transaction
[L_SEVERITYCODE0] => Error )
What is that I am doing wrong?
I have set the api keys of the emailid to which payment is made
Please let me know what is problem and how can I make refund work.
Code
$API_Endpoint = "https://api-3t.sandbox.paypal.com/nvp";
$version = urlencode('51.0');
$API_UserName = 'example';
$API_Password = 'example';
$API_Signature = 'example';
$API_Endpoint = 'example';
$sandboxmode = 'example';
$methodName_ = 'RefundTransaction';
$transactionID = urlencode('example');
$refundType = urlencode('example');
if($partial) {
$amount = 'example';
$memo = 'Refunding the amount ';
$nvpStr_ = "&TRANSACTIONID=$transactionID&REFUNDTYPE=$refundType&CURRENCYCODE=$currencyID&AMT=$amount&NOTE=$memo";
} else {
$nvpStr_ = "&TRANSACTIONID=$transactionID&REFUNDTYPE=$refundType&CURRENCYCODE=$currencyID";
}
$currencyID = urlencode('CAD');
$API_Endpoint = "https://api-3t.sandbox.paypal.com/nvp";
$version = urlencode('51.0');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $API_Endpoint);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
// Turn off the server and peer verification (TrustManager Concept).
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
// Set the API operation, version, and API signature in the request.
$nvpreq = "METHOD=$methodName_&VERSION=$version&PWD=$API_Password&USER=$API_UserName&SIGNATURE=$API_Signature$nvpStr_";
// Set the request as a POST FIELD for curl.
curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);
// Get response from the server.
$httpResponse = curl_exec($ch);

facebook api returning "Got EOF while waiting for outstanding responses" error message

I am posting images through my app to users wall on their behalf (they step in front of a camera at events). MY app was working successfully last week now its not working and reporting "Got EOF while waiting for outstanding responses".
There is a related bug report but its for an iphone app while mine is a web based php.
Can anyone shed light on this error message? my code is below but its broken down a lot for pic processing and db calls..
//initial calling code
$data = array('title' => $station_info->title,
'message' => $station_info->message,
'token' => $result['access_token'],
'item' => $item,
'pic_source' => $image,
'fb_id' => $result['fb_id'],
'album_id' => $station_info->pic_station_album_id,
'user_id' => $user_id_data['id'],
);
//$result = $this->__do_facebook_image_post($data);
$feedback = "FACEBOOKIMG: " . $this->__do_facebook_image_post($data, 'x');
///processing code
private function __do_facebook_image_post($data,$type = "normal"){
$attachment = array(
'title' => $data['title'],
'message' => $data['message'],
'token' => $data['token']
);
if($type =="normal"){
$folder = "webcam";
}else if($type="x"){
$folder = "x";
}
$upload_path = FCPATH . "/pic_uploads/".$folder."/".$data['item'];
echo $upload_path;
if(is_file($upload_path))
{
$attachment['source'] = '#' . realpath(FCPATH . "/img_uploads/".$folder."/". $upload_path);
}
else
{
$attachment['source'] = '#' . realpath(FCPATH . "/img_uploads/".$folder."/". $data['pic_source']);
}
return $this->facebook_img_post($data['fb_id'],$attachment,$this->__get_facebook_album_id($data['album_id'],$data['user_id'],$data['token']),$data['token']);
}
private function __do_facebook_image_post($data,$type = "normal"){
$attachment = array(
'title' => $data['title'],
'message' => $data['message'],
'token' => $data['token']
);
if($type =="normal"){
$folder = "webcam";
}else if($type="x"){
$folder = "x";
}
$upload_path = FCPATH . "/pic_uploads/".$folder."/".$data['item'];
echo $upload_path;
if(is_file($upload_path))
{
$attachment['source'] = '#' . realpath(FCPATH . "/img_uploads/".$folder."/". $upload_path);
}
else
{
$attachment['source'] = '#' . realpath(FCPATH . "/img_uploads/".$folder."/". $data['pic_source']);
}
return $this->facebook_img_post($data['fb_id'],$attachment,$this->__get_facebook_album_id($data['album_id'],$data['user_id'],$data['token']),$data['token']);
}
private function __post_to_facebook($url,$attachment)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // This i added as the URL is https
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); // This i added as the URL is https
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POST, true); // Do I need this ?
curl_setopt($ch, CURLOPT_POSTFIELDS, $attachment);
$result= curl_exec($ch);
curl_close ($ch);
return $result;
}
function facebook_img_post($fb_id,$data,$album_id ='')
{
if(!empty($album_id)){
$url = "https://graph.facebook.com/".$album_id."/photos";
}else{
$url = "https://graph.facebook.com/".$fb_id."/photos";
}
$attachment = array(
'access_token' => $data['token'],
'message'=> $data['message'],
'source' => $data['source'] . ";type=".get_mime_by_extension($data['source'])
);
return $this->__post_to_facebook($url,$attachment);
}
The error message that got returned didn't really match the problem.
I fixed this error as I was trying to upload a photo but was not passing the correct file path.