PayPal Rest API complete the payment but not shown in sandbox transactions - paypal

I created a PHP script with PayPal Rest API. When I complete the payment the site redirect to the finish page with the label of the payment success, but when I go to the sandbox paypal site, I can't see any transactions. What I can do for solve this issue?
Here there are the 3 scripts:
start.php
<?php
require 'vendor/autoload.php';
define('SITE_URL', 'http://192.168.1.105/Fenix/Include/pay.php');
$paypal = new \PayPal\Rest\ApiContext(
new \PayPal\Auth\OAuthTokenCredential(
'AX5IC3G3s-XRzfMgmSUjEPGbHAjD6PL80skf7Xck50OKWXQ2nGf-9NWk5FjSaMCh1FPpxFvUioqZEbjy',
'EJ8GDd08PwnRM1VxYzT2-fBmxAYzykYZ_zlwHi_zqmFGOQzaoXHAffM5DSiBDTcd8L6OpyDzGt5gtmMU'
)
);
?>
checkout.php
<?php
include "./vendor/autoload.php";
use PayPal\Api\Payer;
use PayPal\Api\Item;
use PayPal\Api\ItemList;
use PayPal\Api\Details;
use PayPal\Api\Amount;
use PayPal\Api\Transaction;
use PayPal\Api\RedirectUrls;
use PayPal\Api\Payment;
require 'start.php';
/*
if (!isset($_POST['product'], $_POST['price'])){
die();
}
*/
$product = "Fenix ID";
$price = 0.01;
$shipping = 0;
$total = $price+$shipping;
$payer = new Payer();
$payer->setPaymentMethod('paypal');
$item = new Item();
$item->setName($product)
->setCurrency('EUR')
->setQuantity(1)
->setPrice($price);
$itemList = new ItemList();
$itemList->setItems([$item]);
$details = new Details();
$details->setShipping($shipping)
->setSubtotal($price);
$amount = new Amount();
$amount->setCurrency('EUR')
->setTotal($total)
->setDetails($details);
$transaction = new Transaction();
$transaction->setAmount($amount)
->setItemList($itemList)
->setDescription('Fenix ID')
->setInvoiceNumber(uniqid());
$redirectUrls = new RedirectUrls();
$redirectUrls->setReturnUrl(SITE_URL . '/pay.php?success=true')
->setCancelUrl(SITE_URL . '/pay.php?success=false');
$payment = new Payment();
$payment->setIntent('sale')
->setPayer($payer)
->setRedirectUrls($redirectUrls)
->setTransactions([$transaction]);
try {
$payment->create($paypal);
}catch (Exception $e){
die($e);
}
$approvalUrl = $payment->getApprovalLink();
header("Location: {$approvalUrl}");
?>
pay.php
<?php
use PayPal\Api\Payment;
use PayPal\Api\PaymentExecution;
require 'start.php';
if (!isset($_GET['success'], $_GET['paymentId'], $_GET['PayerID'])) {
die();
}
if ((bool)$_GET['success'] === false) {
die();
}
$paymentId = $_GET['paymentId'];
$payment = Payment::get($paymentId, $paypal);
$execution = new PaymentExecution();
$execution->setPayerId($_GET['PayerID']);
echo "Payment success!";
?>
Thanks for the help.

Related

PayPal Checkout without Details and Subtotal

I use the PayPal SDK for PHP and want to go to the checkout without showing details and total instead of subtotal (like on the picture left).
Thanks!
Example Picture
This is the Code i use.
$arrPrices = $this->getPrices();
$apiContext = $this->getApiContext();
$payer = new \PayPal\Api\Payer();
$payer->setPaymentMethod("paypal");
$arrItems = [];
$item = new \PayPal\Api\Item();
$item->setName($saveValues['title'])->setCurrency('EUR')->setQuantity(1)->setPrice($arrPrices['raw']);
$arrItems[] = $item;
$itemList = new \PayPal\Api\ItemList();
$itemList->setItems($arrItems);
$details = new \PayPal\Api\Details();
$details->setTax($arrPrices['tax'])->setSubtotal($arrPrices['raw']);
$amount = new \PayPal\Api\Amount();
$amount->setCurrency("EUR")->setTotal($arrPrices['total'])->setDetails($details);
$transaction = new \PayPal\Api\Transaction();
$transaction->setAmount($amount)->setItemList($itemList)->setDescription("Vielen Dank für Deine Buchung & bis bald!");
$redirectUrls = new \PayPal\Api\RedirectUrls();
$url = \Environment::get('url') . '/' . $GLOBALS['SCRIPT_URL'];
$redirectUrls->setReturnUrl("$url?success=true")->setCancelUrl("$url?success=false");
$payment = new \PayPal\Api\Payment();
$payment->setIntent("sale")->setPayer($payer)->setRedirectUrls($redirectUrls)->addTransaction($transaction);
try {
$payment->create($apiContext);
}
catch (\Exception $ex) {
return $ex->getData();
}
return $payment->getApprovalLink();
If you don't provide the details you will not see the details ? there isn't a way by which you will provide the details and then not have display it on the paypal approval page (of which you are showing the screen shot)

Retrieve Lead Ads Facebook API

I have problems retrieving Lead Ads.
I have the Ad-ID and the Page-ID. I haven't created them, but was added as a developer.
I was trying to use the PHP SDK and this https://developers.facebook.com/docs/marketing-api/guides/lead-ads/v2.9
Nothing is working. I cannot find a nice tutorial about that.
I just want to retrieve the leading Ads!
Anyone?
Assuming you have already installed FB API SDK and configured your FB app, you can use this to get all results from all LeadAds of your $page_id
use FacebookAds\Api;
use FacebookAds\Object\Page;
use FacebookAds\Object\Ad;
$access_token = 'YOUR TOKEN';
$app_id = 'YOUR APP ID';
$app_secret = 'YOUR APP SECRET';
$page_id = 'YOUR PAGE ID';
Api::init($app_id, $app_secret, $access_token);
$ads = getAllLeadsAds($page_id);
$result = array();
foreach ($ads->data as $item) {
$leads = getLeadAdInfo($item->id);
$i = 0;
foreach ($leads->data as $value) {
$result[$i]['ad_id'] = $item->id;
$result[$i]['lead_id'] = $value->id;
$result[$i]['form'] = $value->field_data;
$i++;
}
}
print_r($result);
function getAllLeadsAds($page)
{
$page = new Page($page);
return $page->getLeadgenForms()->getResponse()->getBody();
}
function getLeadAdInfo($ad)
{
$ad = new Ad($ad);
return $ad->getLeads()->getResponse()->getBody();
}
Its possible that you not calling all ads inside adset.
You can use facebook cursor.
$cursor->fetchAfter();
use FacebookAds\Object\AdAccount;
use FacebookAds\Object\Values\ArchivableCrudObjectEffectiveStatuses;
use FacebookAds\Object\Fields\CampaignFields;
use FacebookAds\Object\AdCampaign;
use FacebookAds\Object\Fields\AdSetFields;
use FacebookAds\Object\AdSet;
use FacebookAds\Object\Fields\AdFields;
use FacebookAds\Object\Ad;
use FacebookAds\Object\Campaign;
function getadsetname($adset_id,$acc_id){
$adset = new AdSet($adset_id, $acc_id);
$adset->read(array(
AdSetFields::NAME,
));
return $adset->name; // Outputs name of adset.
}
function get_campaignname($campaign_id){
$campaign = new Campaign($campaign_id);
$campaign->read(array(
CampaignFields::NAME,
));
return $campaign->name;
}
$account = new AdAccount($account_id);
echo $adset_name = getadsetname($adset_id,$account_id);
echo $campaign_name = get_campaignname($campaign_id);
echo "<hr>";
$adcampaign = new AdAccount($campaign_id);
$adset = new AdSet($adset_id);
$ads = $adset->getAds(array(
AdFields::NAME,
AdFields::CONFIGURED_STATUS,
AdFields::EFFECTIVE_STATUS,
AdFields::CREATIVE,
));
$ads->fetchAfter();
foreach ($ads as $ad) {
$ad_id = $ad->id;
$ad_name = $ad->name;
if($ad->configured_status=="ACTIVE"){
$ad1 = new Ad($ad_id);
$leads = $ad1->getLeads();
$leads->fetchAfter();
foreach ($leads as $lead) {
$fname = $lead->field_data;
//var_dump($fname);
$data = array();
$data['lead_id'] = $lead->id;
$data['created_time'] = $lead->created_time;
$data['ad_id'] = $ad_id;
$data['ad_name'] = $ad_name;
$data['adset_id'] = $adset_id;
$data['adset_name'] = $adset_name;//$adset_name;
$data['campaign_id'] = $campaign_id;
$data['campaign_name'] = $campaign_name;
$data['form_id'] = $lead->form_id;//$lead->id;
$data['is_organic'] = $lead->is_organic;//$lead->id;
}
}
}
$ads->fetchAfter(); will get the next list of ads and
$leads->fetchAfter(); will get the next list of leads

Paypal CC Direct Payment error

I need some help to figure out paypal's API, all I'm trying to do is run a cc charge to my sandbox account, I've been looking at their documentation and code samples but I just can't find the right information right now, like where to add the sandbox endpoint. So, when I run the function below I get the following error:
string(213) "{"name":"MALFORMED_REQUEST","message":"Incoming JSON request does not map to API request","information_link":"https://developer.paypal.com/webapps/developer/docs/api/#MALFORMED_REQUEST","debug_id":"6eb15180f8d92"}"
This is the function I'm calling:
public static function ccPayment($paymentInfo, $credentials)
{
$apiContext = new \PayPal\Rest\ApiContext(
new \PayPal\Auth\OAuthTokenCredential(
$credentials['clientId'],
$credentials['secret']
)
);
$card = new CreditCard();
$card->setType("visa")
->setNumber("xxxxxxxxxxxxxxxx")
->setExpireMonth("11")
->setExpireYear("2019")
->setCvv2("012")
->setFirstName("Joe")
->setLastName("Shopper");
$fi = new FundingInstrument();
$fi->setCreditCard($card);
$payer = new Payer();
$payer->setPaymentMethod("credit_card")
->setFundingInstruments(array($fi));
$item1 = new Item();
$item1->setName('Ground Coffee 40 oz')
->setDescription('Ground Coffee 40 oz')
->setCurrency('USD')
->setQuantity(1)
->setTax(0.3)
->setPrice(7.50);
$itemList = new ItemList();
$itemList->setItems(array($item1));
$transaction = new Transaction();
$transaction->setAmount(489)
->setItemList($itemList)
->setDescription("Payment description")
->setInvoiceNumber(uniqid());
$payment = new Payment();
$payment->setIntent("sale")
->setPayer($payer)
->setTransactions(array($transaction));
// $request = clone $payment;
try
{
$payment->create($apiContext);
}
catch (Exception $ex)
{
dd($ex->getData());
}
dd($paymentInfo);
}
Been coding since the morning so I need another set of eyes right now because I just can't see what I'm doing wrong. I will appreciate any help.
PS. Apologies if it's something dumb. Eg. a missing comma.
Thanks.
Got it working !! Here's the working code:
$apiContext = new \PayPal\Rest\ApiContext(
new \PayPal\Auth\OAuthTokenCredential(
$credentials['clientId'],
$credentials['secret']
)
);
$apiContext->setConfig(
array(
'log.LogEnabled' => true,
'log.FileName' => '../app/storage/paypal/PayPal.log',
'log.LogLevel' => 'FINE'
)
);
$card = new CreditCard();
$card->setType("visa")
->setNumber("xxxxxxxxxxxxxxxxx")
->setExpireMonth("11")
->setExpireYear("2019")
->setCvv2("012")
->setFirstName("Joe")
->setLastName("Shopper");
$fi = new FundingInstrument();
$fi->setCreditCard($card);
$payer = new Payer();
$payer->setPaymentMethod("credit_card")
->setFundingInstruments(array($fi));
$item1 = new Item();
$item1->setName('Ground Coffee 40 oz')
->setDescription('Ground Coffee 40 oz')
->setCurrency('USD')
->setQuantity(1)
->setPrice(49.99);
$itemList = new ItemList();
$itemList->setItems(array($item1));
$details = new Details();
$details->setSubtotal(49.99);
$amount = new Amount();
$amount->setCurrency("USD")
->setTotal(49.99)
->setDetails($details);
$transaction = new Transaction();
$transaction->setAmount($amount)
->setItemList($itemList)
->setDescription("Payment description")
->setInvoiceNumber(uniqid());
$payment = new Payment();
$payment->setIntent("sale")
->setPayer($payer)
->setTransactions(array($transaction));
try
{
$payment->create($apiContext);
}
catch (Exception $ex)
{
dd($ex->getData());
}
dd($payment);
I was missing new Amount & new Details. Also, for the sake of documentation, your monetary totals must add up. Eg. tax, subtotal, total.

htmlPurifier not working with Froala editor WYSIWYG

When i Input.:
<script>alert("XSS")</script>Cleaning Test
My output should be
Cleaning Test
but i get same as input <script>alert("XSS")</script>Cleaning Test
can someone help me to solve this problem
and tried a lot but doesn't works i need to check my htmlpurifie is working
this is my code
<?php
require_once 'htmlpurifier/library/HTMLPurifier.auto.php';
ini_set("display_errors", 1);
error_reporting(E_ALL);
define('DB_SERVER', "localhost");
define('DB_USER', "sanoj");
define('DB_PASSWORD', "123456");
define('DB_DATABASE', "test");
define('DB_DRIVER', "mysql");
$country = filter_input(INPUT_POST, 'title');
$dirty_html = filter_input(INPUT_POST, 'wysiwyg');
$purifier = new HTMLPurifier();
$clean_html = $purifier->purify($dirty_html);
try {
$db = new PDO(DB_DRIVER . ":dbname=" . DB_DATABASE . ";host=" . DB_SERVER, DB_USER, DB_PASSWORD);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $db->prepare("INSERT INTO final(title, wysiwyg) VALUES (:title, :wysiwyg)");
$stmt->bindParam(':title', $country, PDO::PARAM_STR, 100);
$stmt->bindParam(':wysiwyg', $clean_html, PDO::PARAM_STR, 100);
if ($stmt->execute()) {
echo '1 row has been inserted';
}
$db = null;
} catch (PDOException $e) {
trigger_error('Error occured while trying to insert into the DB:' . $e->getMessage(), E_USER_ERROR);
}
?>

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.