I am getting the following error when switching from sandbox to live paypal.please help me how to solve this error.
Array
(
[TIMESTAMP] => 2015-06-10T01:59:03Z
[CORRELATIONID] => 4ce24a1abd742
[ACK] => Failure
[VERSION] => 85.0
[BUILD] => 16770825
[L_ERRORCODE0] => 10501
[L_SHORTMESSAGE0] => Invalid Configuration
[L_LONGMESSAGE0] => This transaction cannot be processed due to an invalid merchant configuration.
[L_SEVERITYCODE0] => Error
[AMT] => 555.00
[CURRENCYCODE] => USD
)
Controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Checkout extends CI_Controller {
public function direct_payment() {
$item = $this->session->userdata['item_data']['item'];
$price = $this->session->userdata['item_data']['price'];
$quantity = $this->session->userdata['item_data']['quantity'];
$card_type = $this->input->post('card_type');
$card_fname = $this->input->post('card_fname');
$card_lname = $this->input->post('card_lname');
$creditcard_number = $this->input->post('creditcard_number');
$crd_month=$this->input->post('crd_month');
$crd_year=$this->input->post('crd_year');
$security_code=$this->input->post('security_code');
//$order_id = $this->payment_model->save_order();
$respounse = $this->payment_model->do_direct_payment($card_type,$card_fname,$card_lname,$creditcard_number,$crd_month,$crd_year,$security_code);
echo '<pre>';
print_r($respounse);
exit;
if($respounse['ACK'] == 'SuccessWithWarning' or $respounse['ACK']== 'Success' or $respounse['ACK']== 'Pending') {
//$this->db->update('orders', array('order_status'=>'New', 'transaction_id'=>$respounse['TRANSACTIONID'], 'payment_type' =>'Credit Card',
//'payment_status' =>$respounse['ACK'],'payment_recevied'=>$respounse['AMT'], 'payment_symbol'=>$respounse['CURRENCYCODE']), array('id'=> $order_id));
//$this->cart->destroy();
//$this->session->set_userdata(array(
//'last_id'=> $order_id,'transaction'=>$respounse['TRANSACTIONID']));
$this->session->set_flashdata("succes","Your Order is succesfully placed.");
redirect("contents/credit");
} else {
//$this->db->update('orders', array('order_status'=>'Failed', 'payment_type' =>'Credit Card',
//'payment_status' =>$respounse['ACK']), array('id'=> $order_id));
$this->session->set_flashdata("error","Error occur in your payment transacion.");
redirect("contents/credit");
}
}
}
Model:
class payment_model extends CI_Model {
function do_direct_payment($card_type,$card_fname,$card_lname,$creditcard_number,$crd_month,$crd_year,$security_code) {
$sandbox = TRUE;
// Set PayPal API version and credentials.
$api_version = '85.0';
$api_endpoint = ($sandbox == 0 )? 'https://api-3t.sandbox.paypal.com/nvp' : 'https://api-3t.paypal.com/nvp';
$api_username = ($sandbox == 0) ? '------' : '-------';
$api_password = ($sandbox == 0) ? '-------' : '------';
$api_signature = ($sandbox == 0) ? '--------' : '-------';
$request_params = array (
'METHOD' => 'DoDirectPayment',
'USER' => $api_username,
'PWD' => $api_password,
'SIGNATURE' => $api_signature,
'VERSION' => $api_version,
'PAYMENTACTION' => 'Sale',
'IPADDRESS' => $_SERVER['REMOTE_ADDR'],
'CREDITCARDTYPE' => $card_type,
'ACCT' => $creditcard_number,
'EXPDATE' => $crd_month.$crd_year,
'CVV2' => $security_code,
'FIRSTNAME' => 'ibad',
'LASTNAME' => 'anjum',
'STREET' => '11 gg',
'CITY' => 'peshawar',
'STATE' => 'state',
'COUNTRYCODE' => 'PK',
'ZIP' => '10200',
'EMAIL' => '-----',
'AMT' => 555,
'CURRENCYCODE' => 'USD',
'DESC' => 'Testing Payments Pro'
);
// Loop through $request_params array to generate the NVP string.
$nvp_string = '';
foreach($request_params as $var=>$val)
{
$nvp_string .= '&'.$var.'='.urlencode($val);
}
// Send NVP string to PayPal and store response
$curl = curl_init();
curl_setopt($curl, CURLOPT_VERBOSE, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURLOPT_URL, $api_endpoint);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $nvp_string);
$result = curl_exec($curl);
//print_r($result);
return $result_array = $this->NVPToArray($result);
}
public function NVPToArray($NVPString) {
$proArray = array();
while(strlen($NVPString)) {
// name
$keypos= strpos($NVPString,'=');
$keyval = substr($NVPString,0,$keypos);
// value
$valuepos = strpos($NVPString,'&') ? strpos($NVPString,'&'): strlen($NVPString);
$valval = substr($NVPString,$keypos+1,$valuepos-$keypos-1);
// decoding the respose
$proArray[$keyval] = urldecode($valval);
$NVPString = substr($NVPString,$valuepos+1,strlen($NVPString));
}
return $proArray;
}
}
As per the docs, the error code 10501 occurs when the billing agreement is disabled or inactive.You should enable your PayPal Payment Pro in your account.
You could try doing the following::
Open your developer.paypal.com account.
Open applications to access your account.
Click the account you are trying to upgrade to Payment Pro.
Click Profile to find the option Upgrade to Pro in the dialogue box.
If it worked on your Sandbox, it seems to me an account issue.
For account issues I would recommend getting contact with PayPal (bottom of http://www.paypal.com), and they will get the right team to support you.
Even if later they find it's technical, they will ask merchant technical services to support. But again, I think this is account issue. They will guide you through the necessary process.
Related
I want to transfer/pay money on click 'pay' button in admin panal from company's paypal account to payal account of client using adaptive payments in php.
I tried lot of more for this but every time fail. please help..
I also follow this
How to transfer money from one PayPal account to another PayPal account?
Note:- I run it on localhost and using pay sandbox accounts
I currently use below code and use sdk adaptivepayments-sdk-php
my configration.php file is
<?php
class Configuration {
public static function getConfig() {
$config = array(
"mode" => "sandbox"
);
return $config;
}
public static function getAcctAndConfig() {
$config = array(
// Signature Credential
"acct1.UserName" => "*************.************.com",
"acct1.Password" => "**********************",
"acct1.Signature" => "***************************************",
"acct1.AppId" => "APP-**********************"
);
return array_merge($config, self::getConfig());
;
}
}
and my process.php file's cose is
<?php
session_start();
require_once('../PPBootStrap.php');
require_once('../Common/Constants.php');
define("DEFAULT_SELECT", "- Select -");
$returnUrl = "http://localhost/paypal/adaptive/parallel/success.php";
$cancelUrl = "http://localhost/paypal/adaptive/parallel/index.php";
$memo = "Adaptive Payment";
$actionType = "PAY";
$currencyCode = "USD";
$senderEmail ="info#birddog.com";
$receiverEmail = array("manojrana#gmail.com");
$receiverAmount = array("300.00");
$primaryReceiver = array("false");
$_SESSION['facilty_provider'] = array("AirGo Airline's Test Store");
if (isset($receiverEmail)) {
$receiver = array();
for ($i = 0; $i < count($receiverEmail); $i++) {
$receiver[$i] = new Receiver();
$receiver[$i]->email = $receiverEmail[$i];
$receiver[$i]->amount = $receiverAmount[$i];
$receiver[$i]->primary = $primaryReceiver[$i];
}
$receiverList = new ReceiverList($receiver);
}
$payRequest = new PayRequest(new RequestEnvelope("en_US"), $actionType, $cancelUrl, $currencyCode, $receiverList, $returnUrl);
// Add optional params
if ($memo != "") {
$payRequest->memo = $memo;
}
$service = new AdaptivePaymentsService(Configuration::getAcctAndConfig());
try {
**$response = $service->Pay($payRequest);**
$ack = strtoupper($response->responseEnvelope->ack);
if ($ack == "SUCCESS") {
$_SESSION['pay_key'] = $payKey = $response->payKey;
$payKey = $response->payKey;
$payPalURL = PAYPAL_REDIRECT_URL . '_ap-payment&paykey=' . $payKey;
header('Location: ' . $payPalURL);
}
} catch (Exception $ex) {
require_once '../Common/Error.php';
exit;
}
and i got blank screen as output because of $response = $service->Pay($payRequest); return as below when i try to print this
PayResponse Object
(
[responseEnvelope] => ResponseEnvelope Object
(
[timestamp] => 2017-10-11T22:20:35.114-07:00
[ack] => Failure
[correlationId] => aebfb26213bbe
[build] => 39000598
)
[payKey] =>
[paymentExecStatus] =>
[payErrorList] =>
[paymentInfoList] =>
[sender] =>
[defaultFundingPlan] =>
[warningDataList] =>
[error] => Array
(
[0] => ErrorData Object
(
[errorId] => 520003
[domain] => PLATFORM
[subdomain] => Application
[severity] => Error
[category] => Application
[message] => Authentication failed. API credentials are incorrect.
[exceptionId] =>
[parameter] =>
)
)
)
Please help me
I'm trying to use Paypal Mass Payment API with this code, but I got this error.
I saved this code to a file 'MassPay.php' and uploaded it to my localhost. I'm trying to test the code and if I can make it work I'll use it inside core php, to monthly mass pay teachers.
Array
(
[TIMESTAMP] => 2015-07-03T06:55:19Z
[CORRELATIONID] => 437cfd2eedc02
[ACK] => Failure
[VERSION] => 74.0
[BUILD] => 17235934
[L_ERRORCODE0] => 10004
[L_SHORTMESSAGE0] => Transaction refused because of an invalid argument. See additional error messages for details.
[L_LONGMESSAGE0] => The number of input records is less than or equal to zero
[L_SEVERITYCODE0] => Error
[ERRORS] => Array
(
[0] => Array
(
[L_ERRORCODE] => 10004
[L_SHORTMESSAGE] => Transaction refused because of an invalid argument. See additional error messages for details.
[L_LONGMESSAGE] => The number of input records is less than or equal to zero
[L_SEVERITYCODE] => Error
)
)
[REQUESTDATA] => Array
(
[USER] => dudhat-facilitator_api1.artoongames.com
[PWD] => AXAT8HSZRR4XANFZ
[VERSION] => 74.0
[BUTTONSOURCE] => AngellEYE_PHPClass
[SIGNATURE] => AFcWxV21C7fd0v3bYYYRCpSSRl31Ab1QV5bWA6uEZ.6emUAkZaZEhjiA
[METHOD] => MassPay
[EMAILSUBJECT] => dudhat#artoongames.com
[CURRENCYCODE] => USD
[RECEIVERTYPE] => EmailAddress
)
[RAWREQUEST] => USER=dudhat-facilitator_api1.artoongames.com&PWD=AXAT8HSZRR4XANFZ&VERSION=74.0&BUTTONSOURCE=AngellEYE_PHPClass&SIGNATURE=AFcWxV21C7fd0v3bYYYRCpSSRl31Ab1QV5bWA6uEZ.6emUAkZaZEhjiA&METHOD=MassPay&EMAILSUBJECT=dudhat%40artoongames.com&CURRENCYCODE=USD&RECEIVERTYPE=EmailAddress
[RAWRESPONSE] => TIMESTAMP=2015%2d07%2d03T06%3a55%3a19Z&CORRELATIONID=437cfd2eedc02&ACK=Failure&VERSION=74%2e0&BUILD=17235934&L_ERRORCODE0=10004&L_SHORTMESSAGE0=Transaction%20refused%20because%20of%20an%20invalid%20argument%2e%20See%20additional%20error%20messages%20for%20details%2e&L_LONGMESSAGE0=The%20number%20of%20input%20records%20is%20less%20than%20or%20equal%20to%20zero&L_SEVERITYCODE0=Error
)
Use this code "MassPay.php"
<?php
// Include required library files.
require_once('includes/config.php');
require_once('includes/paypal.class.php');
// Create PayPal object.
$PayPalConfig = array('Sandbox' => $sandbox, 'APIUsername' => $api_username, 'APIPassword' => $api_password, 'APISignature' => $api_signature);
$PayPal = new PayPal($PayPalConfig);
// Prepare request arrays
$MPFields = array(
'emailsubject' => 'dudhat#artoongames.com', // The subject line of the email that PayPal sends when the transaction is completed. Same for all recipients. 255 char max.
'currencycode' => 'USD', // Three-letter currency code.
'receivertype' => 'EmailAddress' // Indicates how you identify the recipients of payments in this call to MassPay. Must be EmailAddress or UserID
);
// Typically, you'll loop through some sort of records to build your MPItems array.
// Here I simply include 3 items individually.
$Item1 = array(
'l_email' => 'dudhat#gmail.com', // Required. Email address of recipient. You must specify either L_EMAIL or L_RECEIVERID but you must not mix the two.
'l_receiverid' => 'dudhat#gmail.com', // Required. ReceiverID of recipient. Must specify this or email address, but not both.
'l_amt' => '10.00', // Required. Payment amount.
'l_uniqueid' => '522', // Transaction-specific ID number for tracking in an accounting system.
'l_note' => 'test payment' // Custom note for each recipient.
);
$Item2 = array(
'l_email' => 'dilip#gmail.com', // Required. Email address of recipient. You must specify either L_EMAIL or L_RECEIVERID but you must not mix the two.
'l_receiverid' => 'dilip#gmail.com', // Required. ReceiverID of recipient. Must specify this or email address, but not both.
'l_amt' => '1.00', // Required. Payment amount.
'l_uniqueid' => '523', // Transaction-specific ID number for tracking in an accounting system.
'l_note' => 'test payment' // Custom note for each recipient.
);
$MPItems = array($Item1,$Item2); // etc
$PayPalRequestData = array('MPFields' => $MPFields, 'MPItems' => $MPFields);
// Pass data into class for processing with PayPal and load the response array into $PayPalResult
$PayPalResult = $PayPal->MassPay($PayPalRequestData);
// Write the contents of the response array to the screen for demo purposes.
echo '<pre />';
print_r($PayPalResult);
?>
You assembled some payment items in $MPItems, but did not add $MPItems into the PayPal request data. So PayPal rejected the mass payment as containing no payment items.
You can use below class for to make transaction of mass pay
define your constants with actual your credentials of paypal with mode(live/sandbox).
class PaypalnvpComponent {
private static $API_Username = PAYPAL_API_USERNAME;
private static $API_Password = PAYPAL_API_PASSWORD;
private static $API_Signature = PAYPAL_API_SIGNATURE;
private static $API_Environment = PAYPAL_API_MODE;
private static $API_Version = '116.0';
public static function Call($methodName,$params){
if(self::$API_Environment == 'LIVE'){
$API_Endpoint = "https://api-3t.paypal.com/nvp";
}else{
$API_Endpoint = "https://api-3t.sandbox.paypal.com/nvp";
}
$nvpstr = "";
foreach($params as $k=>$v){
$nvpstr .="&".$k."=".urlencode($v);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $API_Endpoint);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
//Turn of server and pakagemanager
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,API signature in requrest
$nvpreq ="";
$nvpreq .= "METHOD=".urlencode($methodName);
$nvpreq .= "&VERSION=".urlencode(self::$API_Version);
$nvpreq .= "&PWD=".urlencode(self::$API_Password);
$nvpreq .= "&USER=".urlencode(self::$API_Username);
$nvpreq .= "&SIGNATURE=".urlencode(self::$API_Signature);
$nvpreq .= $nvpstr;
//set the request as POST field for curl
curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);
//get the response from server
$httpResponse = curl_exec($ch);
if(!$httpResponse){
return "$methodName failed:".curl_error($ch).'('.curl_errno($ch).')';
}
//Extract the response details
$httpResponseArray = explode('&', $httpResponse);
$httpParsedResponseArray = array();
foreach ($httpResponseArray as $i=>$value){
$tmpArray = explode('=', $value);
if(sizeof($tmpArray) > 1){
$httpParsedResponseArray[$tmpArray[0]] = urldecode($tmpArray[1]);
}
}
if((0 == sizeof($httpParsedResponseArray)) || !array_key_exists('ACK',$httpParsedResponseArray)){
return "Invalid HTTP Response for POST request($nvpreq) to $API_Endpoint.";
}
return $httpParsedResponseArray;
}
#----------------------------
# #$hok
# mass payment with multiple users in one go
# paypal transaction status will be : Completed, Failed, Returned, Reversed, Unclaimed, Pending, Blocked
#----------------------------
public static function MassPay($params){
$methodName = "MassPay";
return self::Call($methodName, $params);
}
public static function GetTransactionDetail($params){
$methodName = "GetTransactionDetails";
return self::Call($methodName, $params);
}
public static function TransactionSearch($params){
$methodName = "TransactionSearch";
return self::Call($methodName, $params);
}
}
# below is the example how to use above class
$params = array();
$params["RECEIVERTYPE"] = "EmailAddress";
$params["EMAILSUBJECT"] = "Your withdraw request was processed";
$params["L_AMT0"] = 1;
$params["L_EMAIL0"] = "xyz#xyz.abc";
$params["L_UNIQUEID0"] = rand(11111,9999999);
$params["L_AMT1"] = 2;
$params["L_EMAIL1"] = "hamed-buyer#lifeofu.com";
$params["L_UNIQUEID1"] = rand(11111,9999999);
$params["L_AMT2"] = 3;
$params["L_EMAIL2"] = "testuser1#test1.com";
$params["L_UNIQUEID2"] = rand(11111,9999999);
$params["CURRENCYCODE"] = "USD";
$result = PaypalnvpComponent::MassPay($params);
//transaction detial
$params = array();
$params["TRANSACTIONID"] = TRANSACTIONID_HERE;
$result = PaypalnvpComponent::GetTransactionDetail($params);
i ve been playing with the paypal api for exprescheckout.
the problem: i can not call the L_PAYMENTREQUEST_n_ methods.
the PAYMENTREQUEST_0_ works. but i can use this only for price or itemprice.
for the description and quantity i need to use L_PAYMENTREQUEST_n_ methods.
thx for any help
<?php
// EXpress Checkout Paypal
$paketdata = array(
array(
"name" => "Premium",
"desc" => "Mein Beschreibung",
"preis" => '9.96',
"count" => '2'
)
);
$endpreis = "18.97";
$desc = 'meine beschreibung name';
$paypal ="#";
$user = "paypalap#email.com";
$password = "passwd1234";
$signature ="fhhasHDJKHSAHJAL74327327dbsasahbsdcsadb7434";
$version = "93";
$currency = "EUR";
$params = array(
'METHOD' => 'SetExpressCheckout',
'USER' => $user,
'SIGNATURE' => $signature,
'PWD' => $password,
'RETURNURL' => 'https://localhost/env/paypal/geschafft.php',
'CANCELURL' => 'https://localhost/env/paypal/cancel.php',
'VERSION' => $version,
'PAYMENTREQUEST_0_AMT' => $endpreis,
'PAYMENTREQUEST_0_CURRENCYCODE' => $currency,
);
foreach ($paketdata as $k => $paket){
$params['L_PAYMENTREQUEST_0_NAME$k'] = $paket['name'];
$params['L_PAYMENTREQUEST_0_DESC$k'] = '';
$params['L_PAYMENTREQUEST_0_ITEMAMT$k'] = $paket['preis'];
}
$params = http_build_query($params);
$endpoint = 'https://api-3t.sandbox.paypal.com/nvp';
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $endpoint,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $params,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_VERBOSE => 1
));
$response = curl_exec($curl);
$responseArray = array();
parse_str($response, $responseArray);
if (curl_errno($curl)) {
var_dump(curl_errno($curl));
curl_close($curl);
die();
}else{
if ($responseArray['ACK'] == 'Success') {
}else{
curl_close($curl);
}
}
curl_close($curl);
$paypal = 'https://www.sandbox.paypal.com/webscr?cmd=_express-checkout&useraction=commit&token=' . $responseArray['TOKEN'];
echo '<pre>';
print_r($paket);
echo '</pre>';
print_r($paypal)
?>
PAyPal
Your request is coming out like this...
Array
(
[METHOD] => SetExpressCheckout
[USER] => paypalap#email.com
[SIGNATURE] => fhhasHDJKHSAHJAL74327327dbsasahbsdcsadb7434
[PWD] => passwd1234
[RETURNURL] => https://localhost/env/paypal/geschafft.php
[CANCELURL] => https://localhost/env/paypal/cancel.php
[VERSION] => 93
[PAYMENTREQUEST_0_AMT] => 18.97
[PAYMENTREQUEST_0_CURRENCYCODE] => EUR
[L_PAYMENTREQUEST_0_NAME$k] => Premium
[L_PAYMENTREQUEST_0_DESC$k] =>
[L_PAYMENTREQUEST_0_ITEMAMT$k] => 9.96
)
You need to use double quotes around the param name in order to use $k directly inside like that, so you need this...
foreach ($paketdata as $k => $paket){
$params["L_PAYMENTREQUEST_0_NAME$k"] = $paket['name'];
$params["L_PAYMENTREQUEST_0_DESC$k"] = '';
$params["L_PAYMENTREQUEST_0_ITEMAMT$k"] = $paket['preis'];
}
That change then gives me this, which should go through just fine.
Array
(
[METHOD] => SetExpressCheckout
[USER] => paypalap#email.com
[SIGNATURE] => fhhasHDJKHSAHJAL74327327dbsasahbsdcsadb7434
[PWD] => passwd1234
[RETURNURL] => https://localhost/env/paypal/geschafft.php
[CANCELURL] => https://localhost/env/paypal/cancel.php
[VERSION] => 93
[PAYMENTREQUEST_0_AMT] => 18.97
[PAYMENTREQUEST_0_CURRENCYCODE] => EUR
[L_PAYMENTREQUEST_0_NAME0] => Premium
[L_PAYMENTREQUEST_0_DESC0] =>
[L_PAYMENTREQUEST_0_ITEMAMT0] => 9.96
)
On another note, though, you don't want to use localhost in your return and cancel URL's. PayPal's server is the one redirecting to that URL, so localhost at that time is their own server, which isn't going to do what you want, of course.
You need to use your public IP address or setup a domain that resolves to your IP that you can use.
In fact, it's funny, I just tried to use http:// on the front of localhost here, and Stack won't let me post links with that because of that very reason...they would be linking to themselves.
I'm using the Paypal API to create a subscription system where there are two types of subscriptions
Monthly subscription (5dlls)
Annual subscription (50dlls)
I currently have the following code:
For setting the checkout:
public function do_purchase($type){
$this->load->library('paypal');
$requestParams = array(
'RETURNURL' => site_url('restaurant/get_purchase_details'),
'CANCELURL' => site_url('restaurant/afiliaturestaurante')
);
$orderParams = array(
'L_BILLINGTYPE0' => 'RecurringPayments',
'L_BILLINGAGREEMENTDESCRIPTION0' => 'Monthly',
'AMT' => 0
);
$paypal = new Paypal();
$response = $paypal -> request('SetExpressCheckout',$requestParams + $orderParams);
if(is_array($response) && $response['ACK'] == 'Success') { //Request successful
$token = $response['TOKEN'];
header( 'Location: https://www.sandbox.paypal.com/webscr?cmd=_express-checkout&token=' . urlencode($token) );
}
}
For creating the recurring Paypal profile:
public function get_purchase_details(){
if( isset($_GET['token']) && !empty($_GET['token']) ) { // Token parameter exists
// Get checkout details, including buyer information.
// We can save it for future reference or cross-check with the data we have
$this->load->library('paypal');
$paypal = new Paypal();
$checkoutDetails = $paypal -> request('GetExpressCheckoutDetails', array('TOKEN' => $_GET['token']));
// Complete the checkout transaction
$requestParams = array(
'TOKEN' => $_GET['token'],
'PAYERID' => $checkoutDetails['PAYERID'],
'PROFILESTARTDATE' => '2014-03-7T05:38:48Z',
'DESC' => 'Monthly',
'BILLINGPERIOD' => 'Month',
'BILLINGFREQUENCY' => '1',
'AMT' => '5',
'CURRENCYCODE' => 'USD',
'COUNTRYCODE' => 'US',
'MAXFAILEDPAYMENTS' => '3',
);
$response = $paypal -> request('CreateRecurringPaymentsProfile',$requestParams);
if( is_array($response) && $response['ACK'] == 'Success') { // Payment successful
// We'll fetch the transaction ID for internal bookkeeping
$profileID = $response['PROFILEID'];
}
}
}
I need to use $type variable on get_purchase_details for setting the amount of the profile, how can I pass the variable through Paypal so I can user on the other function? I'm using a Paypal library for creating the cURL requests.
Thanks in advance
You could just set the value of $type in a session variable, and that would be available upon return from PayPal.
Alternatively, you could pass your $type value in the CUSTOM parameter of SetExpressCheckout and that way it'll be returned in the GetExpressCheckoutDetails response.
I'm trying to setup recurring payments in paypal with PHP. But the problem that I'm having is that I don't know if I'm doing the right thing. I have this class which makes the request to the Paypal API:
<?php
class Paypal {
protected $_errors = array();
protected $_credentials = array(
'USER' => 'my-user-id',
'PWD' => 'my-pass',
'SIGNATURE' => 'my-signature',
);
protected $_endPoint = 'https://api-3t.sandbox.paypal.com/nvp';
protected $_version = '74.0';
public function request($method,$params = array()) {
$this -> _errors = array();
if( empty($method) ) {
$this -> _errors = array('API method is missing');
return false;
}
$requestParams = array(
'METHOD' => $method,
'VERSION' => $this -> _version
) + $this -> _credentials;
$request = http_build_query($requestParams + $params);
$http_header = array(
'X-PAYPAL-SECURITY-USERID' => 'my-user-id',
'X-PAYPAL-SECURITY-PASSWORD' => 'my-pass',
'X-PAYPAL-SECURITY-SIGNATURE' => 'my-signature',
'X-PAYPAL-REQUEST-DATA-FORMAT' => 'JSON',
'X-PAYPAL-RESPONSE-DATA-FORMAT' => 'JSON'
);
$curlOptions = array (
CURLOPT_HTTPHEADER => $http_header,
CURLOPT_URL => $this -> _endPoint,
CURLOPT_VERBOSE => 1,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $request
);
$ch = curl_init();
curl_setopt_array($ch,$curlOptions);
$response = curl_exec($ch);
if (curl_errno($ch)) {
$this -> _errors = curl_error($ch);
curl_close($ch);
return false;
} else {
curl_close($ch);
$responseArray = array();
parse_str($response,$responseArray);
return $responseArray;
}
}
}
?>
Then I'm making the initial request like this:
session_start();
require_once('Paypal.php');
$paypal = new Paypal();
$amount = 1;
$requestParams = array(
'RETURNURL' => 'http://localhost/tester/paypal/new_test/test_done.php',
'CANCELURL' => 'http://localhost/tester/paypal/new_test/test_cancel.php',
'NOSHIPPING' => '1',
'ALLOWNOTE' => '1',
'L_BILLINGTYPE0' => 'RecurringPayments',
'L_BILLINGAGREEMENTDESCRIPTION0' => 'site donation'
);
$orderParams = array(
'PAYMENTREQUEST_0_AMT' => '1',
'PAYMENTREQUEST_0_CURRENCYCODE' => 'USD',
'PAYMENTREQUEST_0_ITEMAMT' => $amount
);
$item = array(
'L_PAYMENTREQUEST_0_NAME0' => 'site donation',
'L_PAYMENTREQUEST_0_DESC0' => 'site donation',
'L_PAYMENTREQUEST_0_AMT0' => $amount,
'L_PAYMENTREQUEST_0_QTY0' => '1'
);
$response = $paypal->request('SetExpressCheckout', $requestParams + $orderParams + $item);
$sandbox_location = 'https://www.sandbox.paypal.com/webscr?cmd=_express-checkout&token=';
if(is_array($response) && $response['ACK'] == 'Success'){
$token = $response['TOKEN'];
$_SESSION['token'] = $token;
header('Location: ' . $sandbox_location . urlencode($token));
}
?>
As you can see I'm using the SetExpressCheckout API method to get the token that I need and store it in a session so that I can use it later with the request for CreateRecurringPaymentsProfile.
I'm currently redirected to a page similar to this:
Once the user is done logging in with paypal and confirming the amount it redirects to the success page that I've specified which contains this code:
session_start();
require_once('Paypal.php');
$amount = 1;
$paypal = new Paypal();
$token_param = array('TOKEN' => $_SESSION['token']);
$current_date = date('Y-m-d');
$recurring_payment_params = array(
'PROFILESTARTDATE' => gmdate('Y-m-d H:i:s', strtotime($current_date . ' + 1 months')),
'DESC' => 'site donation',
'BILLINGPERIOD' => 'Month',
'BILLINGFREQUENCY' => '1',
'TOTALBILLINGCYCLES' => '0',
'AMT' => $amount
);
$recurringpayment_response = $paypal->request('CreateRecurringPaymentsProfile', $recurring_payment_params + $token_param);
This works, I've verified in the sandbox account that the recurring payment profile was created and that the next billing due is next month. But the problem is that its not really visible in the paypal interface (the screenshot earlier) that they're paying for a subscription. Perhaps I'm getting the redirect url wrong? (https://www.sandbox.paypal.com/webscr?cmd=_express-checkout&token=) or do I have to add additional arguments to the SetExpressCheckout method? Please help.
You're only showing the login screen. After you login you'll see information about the subscription and the button will see "Agree and Pay" or "Agree and Continue" (depending on your useraction value in the return URL) instead of just "Pay" or "Continue".