I am integrating paypal payment gateway in one of site.After successful payment i am redirecting it to success.php file. In success.php file i have included all the insert parameters and a success message. It is redirecting to success.php file properly after making payment but showing payment failed message and no data is inserting to the database. following is my success.php page code
<?php
include 'dbConfig.php';
//Get payment information from PayPal
$item_number = $_GET['item_number'];
$txn_id = $_GET['tx'];
$payment_gross = $_GET['amt'];
$currency_code = $_GET['cc'];
$payment_status = $_GET['st'];
//Get product price from database
$productResult = $db->query("SELECT price FROM products WHERE id = = '".$item_number."'");
$productRow = $productResult->fetch_assoc();
$productPrice = $productRow['price'];
if(!empty($txn_id) && $payment_gross == $productPrice){
//Check if payment data exists with the same TXN ID.
$prevPaymentResult = $db->query("SELECT payment_id FROM payments WHERE txn_id = '".$txn_id."'");
if($prevPaymentResult->num_rows > 0){
$paymentRow = $prevPaymentResult->fetch_assoc();
$last_insert_id = $paymentRow['payment_id'];
}else{
//Insert tansaction data into the database
$insert = $db->query("INSERT INTO payments(item_number,txn_id,payment_gross,currency_code,payment_status) VALUES('".$item_number."','".$txn_id."','".$payment_gross."','".$currency_code."','".$payment_status."')");
$last_insert_id = $db->insert_id;
}
?>
<h1>Your payment has been successful.</h1>
<h1>Your Payment ID - <?php echo $last_insert_id; ?></h1>
<?php }else{ ?>
<h1>Your payment has failed.</h1>
<?php } ?>
what i am doing wrong?
As suggested by Van Hoa, paypal does not send payment information as parameters when you redirect a user to your success page. PayPal will only send back a token and a payer ID.
When redirecting the buyer back to your website from paypal.com,
PayPal appends the Express Checkout transaction token and the unique
PayPal buyer ID as GET parameters to your RETURN URL;
these GET parameters are named token and PayerID.
PayPal docs (emphasis added)
You can use the returned token to get the payment details using GetExpressCheckoutDetails and passing it the token you get back from PayPal.
Related
when i am paying to pay-pal business account, I got transaction-id(tx) & payment status(st) in return URL. but when i am paying to buyers/personal account then I did not get anything in return URL.
//paypal.php ($ll_pp_email will be buyers email id)
$this_script = BASE_URL.'admin/ukorder/paypal';
$this->paypal_class->add_field('business', $ll_pp_email);
$this->paypal_class->add_field('cmd', '_xclick');
$this->paypal_class->add_field('upload', '1');
$this->paypal_class->add_field('amount', $landlord_amount);
$this->paypal_class->add_field('item_name', this->input->post('prop_title'));
$this->paypal_class->add_field('return', $this_script.'/success');
$this->paypal_class->add_field('cancel_return', $this_script.'/cancel');
$this->paypal_class->add_field('notify_url', $this_script.'/ipn');
$this->paypal_class->add_field('currency_code', 'GBP');
$this->paypal_class->add_field('invoice', $invoice);
$this->paypal_class->add_field('email', ADMIN_EMAIL_ADD);
$this->paypal_class->submit_paypal_post($sandbox);
//on success
if(!empty($_GET['st']) && !empty($_GET['tx']))
{
$payment_status = $_GET['st'];
$transaction_id = $_GET['tx'];
if($payment_status=='Completed')
{
//further coding
}
}
But when I am paying from business to personal/buyer account, I didn't get paypal parameters in return url.
Im using PayPal REST API with PHP, I have created a rest app in sandbox and everything as in documentation.
but it returns error
Got Http response code 401 when accessing https://api.sandbox.paypal.com/v1/oauth2/token.
not sure where Im going wrong on this, tried many other sample codes using rest api but same error everywhere.
can some one help me on this?
code is here
define('CLIENT_ID', 'MY CLIENT ID'); //your PayPal client ID
define('CLIENT_SECRET', 'MY SECRET'); //PayPal Secret
define('RETURN_URL', 'http://domain.com/order_process.php'); //return URL where PayPal redirects user
define('CANCEL_URL', 'http://domain.com/payment_cancel.html'); //cancel URL
define('PP_CURRENCY', 'USD'); //Currency code
define('PP_CONFIG_PATH', ''); //PayPal config path (sdk_config.ini)
include_once "vendor/autoload.php"; //include PayPal SDK
include_once "functions.inc.php"; //our PayPal functions
$item_name = 'Test Product'; //get item code
$item_code = 'sku123'; //get item code
$item_price = '10'; //get item price
$item_qty = '1'; //get quantity
/*
Note: DO NOT rely on item_price you get from products page, in production mode get only "item code"
from the products page and then fetch its actual price from Database.
Example :
$results = $mysqli->query("SELECT item_name, item_price FROM products WHERE item_code= '$item_code'");
while($row = $results->fetch_object()) {
$item_name = $row->item_name;
$item_price = item_price ;
}
*/
//set array of items you are selling, single or multiple
$items = array(
array('name'=> $item_name, 'quantity'=> $item_qty, 'price'=> $item_price, 'sku'=> $item_code, 'currency'=>PP_CURRENCY)
);
//calculate total amount of all quantity.
$total_amount = ($item_qty * $item_price);
try{ // try a payment request
//if payment method is paypal
$result = create_paypal_payment($total_amount, PP_CURRENCY, '', $items, RETURN_URL, CANCEL_URL);
//if payment method was PayPal, we need to redirect user to PayPal approval URL
if($result->state == "created" && $result->payer->payment_method == "paypal"){
$_SESSION["payment_id"] = $result->id; //set payment id for later use, we need this to execute payment
header("location: ". $result->links[1]->href); //after success redirect user to approval URL
exit();
}
}catch(PPConnectionException $ex) {
echo parseApiError($ex->getData());
} catch (Exception $ex) {
echo $ex->getMessage();
}
Ok, here is what I did:
Created a PayRequest
SetPaymentOptions - https://developer.paypal.com/webapps/developer/docs/classic/api/adaptive-payments/SetPaymentOptions_API_Operation/
ExecutePayment - "This payment request must be authorized by the sender". I have ran out of idea on why am I not able to execute the payment. From what I understand, once I execute the payment successfully, I will be given a payKey which I shall use this to redirect user to paypal. https://developer.paypal.com/webapps/developer/docs/classic/api/adaptive-payments/ExecutePayment_API_Operation/
Attached are the source codes that I used. The values are all hardcoded. I have tried my best to look through at similar questions, and it makes no sense to me as it contradicts what I understand. Some answers were pointing out that the buyer needs to approve the payment first before you executePayment.
I just want to see the details of all items when I reach the paypal login page.
//1. Obtain endpoint. For live, no need sandbox?
$endPoint = "https://svcs.sandbox.paypal.com/AdaptivePayments/Pay";
//2. Format the HTTP headers needed to make the call.
$appID = "xxx"; //Sandbox test AppID:
$username = "xxx;
$password = "xxx";
$signature = "xxx";
$paypalHeaders = array(
"X-PAYPAL-SECURITY-USERID :" . $username,
"X-PAYPAL-SECURITY-PASSWORD :" . $password,
"X-PAYPAL-SECURITY-SIGNATURE :" . $signature,
"X-PAYPAL-APPLICATION-ID :" . $appID,
"X-PAYPAL-REQUEST-DATA-FORMAT : JSON",
"X-PAYPAL-RESPONSE-DATA-FORMAT : JSON"
);
$data = array();
$data['actionType'] = "CREATE"; //PAY
$data['currencyCode'] = "SGD";
$receiver['amount'] = $orderTotal;
$receiver['email'] = $receiverEmail;
$data['receiverList'] = array();
$data['receiverList']['receiver'][] = $receiver;
$data['returnUrl'] = $returnURL;
$data['cancelUrl'] = $cancleURL;
$requestEnvelope = array();
$requestEnvelope['errorLanguage'] = "en_US";
$data['requestEnvelope'] = $requestEnvelope;
//I omitted the POST call
//print_r($returnedData);
$payKey = $returnedData->payKey;
$paymentStatus = $returnedData->paymentExecStatus;
/*
* Set payment options
*/
$endPoint = "https://svcs.sandbox.paypal.com/AdaptivePayments/SetPaymentOptions";
//paymentDetailsData
$paymentDetailsData = array();
//set payKey
echo "payKey: " . $payKey;
$paymentDetailsData['payKey'] = $payKey;
//displayOptions
$displayOptions['businessName'] = "My Business";
$paymentDetailsData['displayOptions'] = $displayOptions;
//senderOptions
$senderOptions = array();
$senderOptions['requireShippingAddressSelection'] = true; //set to true if courier is chosen
$senderOptions['shippingAddress']['addresseeName'] = "Ny Name";
$senderOptions['shippingAddress']['street1'] = "Address 1Avenue 3";
$senderOptions['shippingAddress']['street2'] = "#xx-112";
$senderOptions['shippingAddress']['city'] = "Singapore";
$senderOptions['shippingAddress']['state'] = "Singapore";
$senderOptions['shippingAddress']['zip'] = "123456";
$senderOptions['shippingAddress']['country'] = "Singapore";
$paymentDetailsData['senderOptions'] = $senderOptions;
//item
$item = array();
$item['name'] = "Korea";
$item['itemPrice'] = 11;
//there is still price, and itemcount
//invoiceData
$invoiceData = array();
$invoiceData['item'] = $item;
//receiverOptions
$receiverOptions = array();
$receiverOptions['description'] = "Product description.";
$receiverOptions['invoiceData'] = $invoiceData;
$paypalEmail = "test#test.com"; //I may need to change this
$receiver['email'] = $paypalEmail;
$receiverOptions['receiver'] = $receiver;
$paymentDetailsData['receiverOptions'] = $receiverOptions;
//requestEnvelope. I have set the request envelope above. It is the same. Can still be used.
$paymentDetailsData['requestEnvelope'] = $requestEnvelope;
makePaypalCall($endPoint, $paypalHeaders, $paymentDetailsData);
/*
* Get payment options. I can see the result of get payment options correctly,
*/
echo "GETTING PAYMENT OPTIONS";
$endPoint = "https://svcs.sandbox.paypal.com/AdaptivePayments/GetPaymentOptions";
$getPaymentData['payKey'] = $payKey;
$getPaymentData['requestEnvelope'] = $requestEnvelope;
makePaypalCall($endPoint, $paypalHeaders, $getPaymentData);
$endPoint = "https://svcs.sandbox.paypal.com/AdaptivePayments/ExecutePayment";
/*
* ExecutePayment. Ok, I get the error here. This payment request must be authorized by the sender
*/
$executePaymentData = array();
echo "paykey: " . $payKey;
$executePaymentData['payKey'] = $payKey;
//$executePaymentData['actionType'] = "PAY";
$executePaymentData['requestEnvelope'] = $requestEnvelope;
I hope I understand you correctly.
To me it seems like you are skipping the step where the user needs to authorize the payment. When you do a Pay (Create) operation you should see get a RedirectURL in the response from PayPal. You need to redirect the user to this URL for them to authorize the payment on PayPal.
Once they have approved the payment, then you'll be able to execute the payment.
Your steps need to change to:
Create PayRequest
Set PaymentOptions
Redirect to PayPal (RedirectURL from the PayRequest response) for user authorization
If authorized, ExecutePayment
PayPal hints at this on the Pay API operation page
URL to redirect the sender's browser to after the sender has logged into PayPal and approved a payment; it is always required but only used if a payment requires explicit approval
After the step 3, the user will be returned to the URL your provided in $data['returnUrl'] = $returnURL;
I am using Delayed Chained Payment and often i end up with this error "This payment request must be authorized by the sender". Actually it was due to a small mistake in the logic.
wrong procedure (# step 3)
generate a payKey successfully
save it to database
refresh the page for some reason which results in generating new payKey (this new payKey doesn't update to database)
payRequest = pay();
.....
if(empty(db_record)) {
.....
db_record->payKey = payRequest->payKey;
db_record->save();
}
paid with new payKey ( ie. payment approved by sender)
trying to execute payment with payKey from database (which is indeed old one. That payKey was not used to make payment)
Solution
update database with last payKey which used for making payment by getting approval of sender
step 3 should be like
if(empty(db_record) || is_expired(db_record->payKey)) {
payRequest = pay();
.....
.....
db_record->payKey = payRequest->payKey;
db_record->save();
}
I am trying to integrate the PAYPAL Express Checkout which the PHP API. All the code is fine as per the documentation provided by the Paypal. I have added the merchant email and also all the parameter are correct.
But then i use to test, a popup is opened and sandbox account logged in successfully. The item detail is shown over there and after that clicking on the pay now button, the popup is closed and I am left at this page :
https://www.sandbox.paypal.com/webapps/checkout/webflow/sparta/expresscheckoutvalidatedataflow?execution=e1s2
and never returns to the merchant site. And below is the controller code which sends user to paypal :
/**
* Purchase the item and then redirect to the paypal page
* #param type $id
*/
public function purchase($id = '') {
//Loading the required helpers and the libraries which is to be used in this function
$this->load->helper('paypal');
//Get all the item fields from the database
//----------------------------------------------------------------------
$item_fields = itemsfieldsquery::create()->filterByitemid($id)->find();
//Fetch the requested item form the database with its detail
//----------------------------------------------------------------------
$item = itemsquery::create()->filterByid($id)->findOne();
//Fetch the item author detail from the database
//----------------------------------------------------------------------
$user_detail = userprofilequery::create()->filterByid(useritemsquery::create()->filterByitemid($id)->findOne()->getuserid())->findOne();
//set the array wit the kay
foreach ($item_fields as $fields) {
$data[categoriesfieldquery::create()->filterByid($fields->getfieldid())->findOne()->getfieldtype()] = $fields->getfieldvalue();
}
// ==================================
// PayPal Express Checkout Module
// ==================================
//'------------------------------------
//' The paymentAmount is the total value of
//' the purchase.
//'
//' TODO: Enter the total Payment Amount within the quotes.
//' example : $paymentAmount = "15.00";
//'------------------------------------
$paymentAmount = $data['item_price'];
//'------------------------------------
//' The currencyCodeType
//' is set to the selections made on the Integration Assistant
//'------------------------------------
$currencyCodeType = "USD";
$paymentType = "Sale";
//'------------------------------------
//' The returnURL is the location where buyers return to when a
//' payment has been succesfully authorized.
//'
//' This is set to the value entered on the Integration Assistant
//'------------------------------------
$returnURL = site_url('item/transaction');
//'------------------------------------
//' The cancelURL is the location buyers are sent to when they hit the
//' cancel button during authorization of payment during the PayPal flow
//'
//' This is set to the value entered on the Integration Assistant
//'------------------------------------
$cancelURL = site_url('item/transaction');
//'------------------------------------
//' Calls the SetExpressCheckout API call
//'
//' The CallSetExpressCheckout function is defined in the file PayPalFunctions.php,
//' it is included at the top of this file.
//'-------------------------------------------------
$items = array();
$items[] = array('name' => $item->getitemname(), 'amt' => $paymentAmount, 'qty' => 1, 'custom' => $id);
//::ITEMS::
// to add anothe item, uncomment the lines below and comment the line above
// $items[] = array('name' => 'Item Name1', 'amt' => $itemAmount1, 'qty' => 1);
// $items[] = array('name' => 'Item Name2', 'amt' => $itemAmount2, 'qty' => 1);
// $paymentAmount = $itemAmount1 + $itemAmount2;
// assign corresponding item amounts to "$itemAmount1" and "$itemAmount2"
// NOTE : sum of all the item amounts should be equal to payment amount
$resArray = SetExpressCheckoutDG($paymentAmount, $currencyCodeType, $paymentType, $returnURL, $cancelURL, $items);
$ack = strtoupper($resArray["ACK"]);
if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING") {
$token = urldecode($resArray["TOKEN"]);
//Redirect user to the paypal
RedirectToPayPalDG($token);
} else {
//Display a user friendly Error on the page using any of the
//following error information returned by PayPal
//------------------------------------------------------------------
$ErrorCode = urldecode($resArray["L_ERRORCODE0"]);
$ErrorShortMsg = urldecode($resArray["L_SHORTMESSAGE0"]);
$ErrorLongMsg = urldecode($resArray["L_LONGMESSAGE0"]);
$ErrorSeverityCode = urldecode($resArray["L_SEVERITYCODE0"]);
$data['error'] = "SetExpressCheckout API call failed. ";
$data['error'] .= "Detailed Error Message: " . $ErrorLongMsg;
$data['error'] .= "Short Error Message: " . $ErrorShortMsg;
$data['error'] .= "Error Code: " . $ErrorCode;
$data['error'] .= "Error Severity Code: " . $ErrorSeverityCode;
//Paint the page if we got the error
//------------------------------------------------------------------
$this->stencil->paint('item/thanks', $data);
}
return;
}
Can anyone help me out to resolve this error or have any idea?
In my site I want to integrate a paypal subscription method in which I want to transfer a particular amount from a user's paypal account to an admin's paypal account daily, weekly or monthly depending on the choice. For that i use the below code:
$obj=new paypal_recurring;
$obj->environment = 'sandbox'; // or 'beta-sandbox' or 'live'
$obj->paymentType = urlencode('Authorization'); // or 'Sale' or 'Order'
// Set request-specific fields.
$obj->startDate = urlencode("2011-9-6T0:0:0");
$obj->billingPeriod = urlencode("Month"); // or "Day", "Week", "SemiMonth", "Year"
$obj->billingFreq = urlencode("4"); // combination of this and billingPeriod must be at most a year
$obj->paymentAmount = urlencode('10');
$obj->currencyID = urlencode('USD'); // or other currency code ('GBP', 'EUR', 'JPY', 'CAD', 'AUD')
/* PAYPAL API DETAILS */
$obj->API_UserName = urlencode('sdfsdfsdfbiz_api1.website.us');
$obj->API_Password = urlencode('543564353');
$obj->API_Signature = urlencode('sdfsdfsdf ');
$obj->API_Endpoint = "https://api-3t.paypal.com/nvp";
/*SET SUCCESS AND FAIL URL*/
$obj->returnURL = urlencode("http://www.mysite.com/index.php?task=getExpressCheckout");
$obj->cancelURL = urlencode('http://www.mysite.comindex.php?task=error');
$task="setExpressCheckout"; //set initial task as Express Checkout
switch($task)
{
case "setExpressCheckout":
$obj->setExpressCheckout();
exit;
case "getExpressCheckout":
$obj->getExpressCheckout();
exit;
case "error":
echo "setExpress checkout failed";
exit;
}
But in this code how can i add the admin's paypal email id so that i can transfer funds to that account?
You need to create an account with paypal,sign up for the API keys, and then the money would go to your account. You can't transfer it to an arbitrary account.