public function details()
 {
     $logger = new PPLoggingManager('PaymentDetails');
     // ##PaymentDetailsRequest
     // The code for the language in which errors are returned, which must be
     // en_US.
     $requestEnvelope = new RequestEnvelope("en_US");
     // PaymentDetailsRequest which takes,
     // `Request Envelope` - Information common to each API operation, such
     // as the language in which an error message is returned.
     $paymentDetailsReq = new PaymentDetailsRequest($requestEnvelope);
     // You must specify either,
     //
     // * `Pay Key` - The pay key that identifies the payment for which you want to retrieve details. This is the pay key returned in the PayResponse message.
     // * `Transaction ID` - The PayPal transaction ID associated with the payment. The IPN message associated with the payment contains the transaction ID.
     // `paymentDetailsRequest.setTransactionId(transactionId)`
     // * `Tracking ID` - The tracking ID that was specified for this payment in the PayRequest message.
     // `paymentDetailsRequest.setTrackingId(trackingId)`
     $paymentDetailsReq->payKey = "AP-86H50830VE600922B";
     // ## Creating service wrapper object
     // Creating service wrapper object to make API call and loading
     // configuration file for your credentials and endpoint
     $service = new AdaptivePaymentsService();
     try {
         // ## Making API call
         // Invoke the appropriate method corresponding to API in service
         // wrapper object
         $response = $service->PaymentDetails($paymentDetailsReq);
     } catch (Exception $ex) {
         $logger->error("Error Message : " . $ex->getMessage());
     }
     // ## Accessing response parameters
     // You can access the response parameters in
     // response object as shown below
     // ### Success values
     if ($response->responseEnvelope->ack == "Success") {
         // The status of the payment. Possible values are:
         //
         // * CREATED - The payment request was received; funds will be
         // transferred once the payment is approved
         // * COMPLETED - The payment was successful
         // * INCOMPLETE - Some transfers succeeded and some failed for a
         // parallel payment or, for a delayed chained payment, secondary
         // receivers have not been paid
         // * ERROR - The payment failed and all attempted transfers failed
         // or all completed transfers were successfully reversed
         // * REVERSALERROR - One or more transfers failed when attempting
         // to reverse a payment
         // * PROCESSING - The payment is in progress
         // * PENDING - The payment is awaiting processing
         $logger->log("Payment Status : " . $response->status);
     } else {
         $logger->error("API Error Message : " . $response->error[0]->message);
     }
     return $response;
 }
 public function preapproveDetails()
 {
     $logger = new PPLoggingManager('PreapprovalDetails');
     // ##PreapprovaDetailslRequest
     // The code for the language in which errors are returned, which must be
     // en_US.
     $requestEnvelope = new RequestEnvelope("en_US");
     // `PreapprovalDetailsRequest` object which takes mandatory params:
     //
     // * `Request Envelope` - Information common to each API operation, such
     // as the language in which an error message is returned.
     // * `Preapproval Key` - A preapproval key that identifies the
     // preapproval for which you want to retrieve details. The preapproval
     // key is returned in the PreapprovalResponse message.
     $preapprovalDetailsRequest = new PreapprovalDetailsRequest($requestEnvelope, "PA-1KM93450LF5424305");
     // ## Creating service wrapper object
     // Creating service wrapper object to make API call and loading
     // configuration file for your credentials and endpoint
     $service = new AdaptivePaymentsService();
     try {
         // ## Making API call
         // Invoke the appropriate method corresponding to API in service
         // wrapper object
         $response = $service->PreapprovalDetails($preapprovalDetailsRequest);
     } catch (Exception $ex) {
         $logger->error("Error Message : " . $ex->getMessage());
     }
     // ## Accessing response parameters
     // You can access the response parameters in
     // response object as shown below
     // ### Success values
     if ($response->responseEnvelope->ack == "Success") {
         // First date for which the preapproval is valid.
         $logger->log("Starting Date : " . $response->startingDate);
     } else {
         $logger->error("API Error Message : " . $response->error[0]->message);
     }
     return $response;
 }
Ejemplo n.º 3
0
 public function adaptive_implicit_payment_developer()
 {
     # Get the Player's Paypal ID
     $this->load->model('Developer_model');
     $this->load->model('Paymenthistory_model');
     $this->load->model('Withdrawal_requests_model');
     $where = 'id = ' . $this->input->post('player_id');
     $player = $this->Developer_model->findByCondition($where);
     $response['status'] = false;
     $response['message'] = ERROR_MESSAGE . ':Something went wrong, the request could not be completed';
     if (!empty($player) && $player[0]['paypal_id'] != '' && $player[0]['paypal_id'] != null && $this->input->post('amount') > 0 && $player[0]['amount'] >= $this->input->post('amount')) {
         $payRequest = new PayRequest();
         $receiver = array();
         $receiver[0] = new Receiver();
         $receiver[0]->amount = $this->input->post('amount');
         $receiver[0]->email = $player[0]['paypal_id'];
         $receiverList = new ReceiverList($receiver);
         $payRequest->receiverList = $receiverList;
         $payRequest->senderEmail = "*****@*****.**";
         $requestEnvelope = new RequestEnvelope("en_US");
         $payRequest->requestEnvelope = $requestEnvelope;
         $payRequest->actionType = "PAY";
         $payRequest->cancelUrl = base_url() . 'admin/payment_error';
         $payRequest->returnUrl = base_url() . 'admin/payment_success';
         $payRequest->currencyCode = "USD";
         $sdkConfig = array("mode" => "sandbox", "acct1.UserName" => "jb-us-seller_api1.paypal.com", "acct1.Password" => "WX4WTU3S8MY44S7F", "acct1.Signature" => "AFcWxV21C7fd0v3bYYYRCpSSRl31A7yDhhsPUU2XhtMoZXsWHFxu-RWy", "acct1.AppId" => "APP-80W284485P519543T");
         $adaptivePaymentsService = new AdaptivePaymentsService($sdkConfig);
         $payResponse = $adaptivePaymentsService->Pay($payRequest);
         $ack = strtoupper($payResponse->responseEnvelope->ack);
         if ($ack != "SUCCESS") {
         } else {
             $insertDataPaymentHistory = array('userID' => $player[0]['id'], 'type' => 'debit', 'reason' => 'Payment to a developer on behalf of a request', 'amount' => $this->input->post('amount'), 'referrer_id' => $player[0]['id'], 'referrer_type' => 'Developer', 'transaction_id' => '', 'gateway' => 'Paypal');
             $id = $this->Paymenthistory_model->save($insertDataPaymentHistory);
             if ($this->input->post('withdrawal_id') != '' && $this->input->post('withdrawal_id') != null) {
                 $where = 'id = ' . $this->input->post('withdrawal_id');
                 $updateDataWithdrawal = array('approved' => is_withdrawal_approved(), 'payment_id' => $id);
                 $this->Withdrawal_requests_model->updateByCondition($where, $updateDataWithdrawal);
                 $body = 'You sent a withdrawal request on your paypal id: ' . $player[0]['paypal_id'] . ' which has been approved and an amount of $' . $this->input->post('amount') . ' has been sent to your paypal account, please verify.';
             } else {
                 $new_balance = floatval(floatval($player[0]['amount']) - floatval($this->input->post('amount')));
                 $where = 'id = ' . $player[0]['id'];
                 $updateDataPlayer = array('amount' => $new_balance);
                 $id = $this->Developer_model->updateByCondition($where, $updateDataPlayer);
                 $body = 'An amount of $' . $this->input->post('amount') . ' has been sent on your paypal id: ' . $player[0]['paypal_id'] . ', please verify.';
             }
             mail_me(array('to' => $player[0]['email'], 'to_name' => $player[0]['fName'] . ' ' . $player[0]['lName'], 'from' => $this->config->item('adminEmail'), 'from_name' => $this->config->item('adminName'), 'from_pass' => $this->config->item('adminEmail_pass'), 'subject' => 'Payment Made', 'body' => $body));
             $response['status'] = true;
             $response['message'] = 'Payment Sucessfully made';
         }
     }
     return $response;
 }
<?php

$path = '../lib';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);
require_once 'services/AdaptivePayments/AdaptivePaymentsService.php';
require_once 'PPLoggingManager.php';
$logger = new PPLoggingManager('GetAvailableShippingAddresses');
// create request
$getAvailableShippingAddressesReq = new GetAvailableShippingAddressesRequest(new RequestEnvelope("en_US"), $_POST['key']);
$logger->log("Created GetAvailableShippingAddressesRequest Object");
$service = new AdaptivePaymentsService();
try {
    $response = $service->GetAvailableShippingAddresses($getAvailableShippingAddressesReq);
    $logger->error("Received GetAvailableShippingAddressesResponse:");
    $ack = strtoupper($response->responseEnvelope->ack);
} catch (Exception $ex) {
    throw new Exception('Error occurred in GetAvailableShippingAddresses method');
}
if ($ack != "SUCCESS") {
    echo "<b>Error </b>";
    echo "<pre>";
    print_r($response);
    echo "</pre>";
    require_once 'Common/Response.php';
    exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>PayPal Adaptive Payment - Get Available Shipping Addresses</title>
Ejemplo n.º 5
0
function invoice_details_callback()
{
    if (isset($_POST['inv_id']) && !empty($_POST['inv_id'])) {
        $invid = explode(",", $_POST['inv_id']);
        require_once 'paypal-invoice/PayPalInvoiceAPI.php';
        require_once 'paypal-invoice/credentials.php';
        //NOTE: edit this file with your info!
        $pAPI = new PayPalInvoiceAPI($api_username, $api_password, $api_signature, $app_id);
        foreach ($invid as $inv_id) {
            //update_post_meta( $inv_id, 'auction_active_pay_method', 'invoice' );
            $invoice_id = get_post_meta($inv_id, 'paypal_invoice_id', true);
            $invoice_data = $pAPI->getInvoiceDetails($invoice_id);
            $invoice_stat = '';
            if ($invoice_data['responseEnvelope.ack'] == "Success") {
                $invoice_stat = isset($invoice_data['invoiceDetails.status']) ? $invoice_data['invoiceDetails.status'] : '';
            } else {
                $invoice_stat = __('Failed to connect with PayPal account. Please verify your PayPal credentials or just reload this page.', 'wdm-ultimate-auction');
            }
            if (!empty($invoice_id)) {
                update_post_meta($inv_id, 'auction_invoice_status', $invoice_stat);
            }
        }
    }
    if (isset($_POST['adp_id']) && !empty($_POST['adp_id'])) {
        require_once 'paypal-adaptive/PPBootStrap.php';
        $adpid = explode(",", $_POST['adp_id']);
        foreach ($adpid as $adp_id) {
            //update_post_meta( $adp_id, 'auction_active_pay_method', 'adaptive' );
            $requestEnvelope = new RequestEnvelope("en_US");
            $paymentDetailsReq = new PaymentDetailsRequest($requestEnvelope);
            $payKey = get_post_meta($adp_id, 'paypal_invoice_id', true);
            if ($payKey != "") {
                $paymentDetailsReq->payKey = $payKey;
            }
            //if($_POST['transactionId'] != "") {
            //	$paymentDetailsReq->transactionId = $_POST['transactionId'];
            //}
            //if($_POST['trackingId'] != "") {
            //	$paymentDetailsReq->trackingId = $_POST['trackingId'];
            //}
            $service = new AdaptivePaymentsService(Configuration::getAcctAndConfig());
            try {
                /* wrap API method calls on the service object with a try catch */
                $response = $service->PaymentDetails($paymentDetailsReq);
            } catch (Exception $ex) {
            }
            update_post_meta($adp_id, 'paypal_trans_timestamp', $response->responseEnvelope->timestamp);
            $ack = strtoupper($response->responseEnvelope->ack);
            $pay_stat = '';
            if ($ack != "SUCCESS") {
                $pay_stat = __('Failed to connect with PayPal account. Please verify your PayPal credentials or just reload this page.', 'wdm-ultimate-auction');
            } else {
                $pay_stat = $response->status;
            }
            if (!empty($payKey)) {
                if (strtoupper($pay_stat) == 'CREATED') {
                    update_post_meta($adp_id, 'auction_invoice_status', 'Sent');
                } elseif (strtoupper($pay_stat) == 'COMPLETED') {
                    update_post_meta($adp_id, 'auction_invoice_status', 'Paid');
                } else {
                    update_post_meta($adp_id, 'auction_invoice_status', $pay_stat);
                }
            }
        }
    }
    die;
}
 * The PreapprovalDetailsRequest message specifies the key of the preapproval agreement whose details you want to obtain.
 */
/*
 * (Required) Information common to each API operation, such as the language in which an error message is returned.
 */
$requestEnvelope = new RequestEnvelope("en_US");
/*
 * (Required) A preapproval key that identifies the preapproval for which you want to retrieve details. The preapproval key is returned in the PreapprovalResponse message.
 */
$preapprovalDetailsRequest = new PreapprovalDetailsRequest($requestEnvelope, $_POST['preapprovalKey']);
/*
* 	 ## Creating service wrapper object
Creating service wrapper object to make API call and loading
Configuration::getAcctAndConfig() returns array that contains credential and config parameters
*/
$service = new AdaptivePaymentsService(Configuration::getAcctAndConfig());
try {
    /* wrap API method calls on the service object with a try catch */
    $response = $service->PreapprovalDetails($preapprovalDetailsRequest);
} catch (Exception $ex) {
    require_once 'Common/Error.php';
    exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>PayPal Adaptive Payments - Preapproval Details</title>
<link href="Common/sdk.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="Common/sdk_functions.js"></script>
</head>
    if ($_POST['emailMarketingImageUrl'] != "") {
        $setPaymentOptionsRequest->displayOptions->emailMarketingImageUrl = $_POST['emailMarketingImageUrl'];
    }
    if ($_POST['headerImageUrl'] != "") {
        $setPaymentOptionsRequest->displayOptions->headerImageUrl = $_POST['headerImageUrl'];
    }
    if ($_POST['businessName'] != "") {
        $setPaymentOptionsRequest->displayOptions->businessName = $_POST['businessName'];
    }
}
/*
* 	 ## Creating service wrapper object
Creating service wrapper object to make API call and loading
Configuration::getAcctAndConfig() returns array that contains credential and config parameters
*/
$service = new AdaptivePaymentsService(Configuration::getAcctAndConfig());
try {
    /* wrap API method calls on the service object with a try catch */
    $response = $service->SetPaymentOptions($setPaymentOptionsRequest);
} catch (Exception $ex) {
    require_once 'Common/Error.php';
    exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>PayPal Adaptive Payments - Set Payment Options</title>
<link href="Common/sdk.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="Common/sdk_functions.js"></script>
</head>
 public function postPaynow(Request $request, $affiliate_id)
 {
     $user_is = $request->user_infusionsoft;
     $affiliate_row = Affiliate::where('user_is_id', '=', $user_is->id)->where('aff_id', '=', $affiliate_id)->first();
     define('PAYPAL_SANDBOX', 1);
     define('PAYPAL_ACTION_URL', 'https://www.sandbox.paypal.com/cgi-bin/webscr');
     //adaptive payment request
     $payRequest = new \PayRequest();
     $receiver = array();
     $receiver[0] = new \Receiver();
     $receiver[0]->amount = $request->amount;
     $receiver[0]->email = $affiliate_row['paypal_email'];
     $receiverList = new \ReceiverList($receiver);
     $payRequest->receiverList = $receiverList;
     $payRequest->senderEmail = $user_is->paypal_business_account;
     $requestEnvelope = new \RequestEnvelope("en_US");
     $payRequest->requestEnvelope = $requestEnvelope;
     $payRequest->actionType = "PAY";
     $payRequest->cancelUrl = URL::to('affiliates/' . $affiliate_id . '/pay');
     $payRequest->returnUrl = URL::to('affiliates/' . $affiliate_id);
     $payRequest->currencyCode = "USD";
     $payRequest->ipnNotificationUrl = URL::to('paypal/ipn');
     $sdkConfig = array("mode" => PAYPAL_SANDBOX ? "sandbox" : 'live', "acct1.UserName" => $user_is->paypal_api_username, "acct1.Password" => $user_is->paypal_api_password, "acct1.Signature" => $user_is->paypal_api_signature, "acct1.AppId" => $user_is->paypal_app_id);
     $adaptivePaymentsService = new \AdaptivePaymentsService($sdkConfig);
     $payResponse = $adaptivePaymentsService->Pay($payRequest);
     $payment = new Payment();
     $payment->affiliate_id = $affiliate_row->id;
     $payment->payment_key = $payResponse->payKey;
     $payment->amount = $request['amount'];
     $payment->pay_result = json_encode($payResponse);
     $payment->status = 1;
     $payment->save();
     if ($payResponse->responseEnvelope->ack != 'Success') {
         return redirect(URL::to('affiliates/' . $affiliate_id . '/pay'))->with('error', 'Payment was not successful.');
     }
     return redirect(URL::to('affiliates/' . $affiliate_id . '/pay'))->with('success', 'Payment was successful');
 }
Ejemplo n.º 9
0
//Do przeróbki
/*$amount,
  $email,
  $ipnlink,
  $walut (PLN...),
  $api_user,
  $api_password,
  
  
  
  


*/
$payRequest = new PayRequest();
$receiver = array();
$receiver[0] = new Receiver();
$receiver[0]->amount = $amount;
$receiver[0]->email = $email;
$receiverList = new ReceiverList($receiver);
$payRequest->receiverList = $receiverList;
$requestEnvelope = new RequestEnvelope("pl_PL");
$payRequest->requestEnvelope = $requestEnvelope;
$payRequest->actionType = "PAY";
$payRequest->cancelUrl = "https://devtools-paypal.com/guide/ap_simple_payment/php?cancel=true";
$payRequest->returnUrl = "https://devtools-paypal.com/guide/ap_simple_payment/php?success=true";
$payRequest->currencyCode = $walut;
$payRequest->ipnNotificationUrl = $ipnlink;
$sdkConfig = array("mode" => "live", "acct1.UserName" => $api_user, "acct1.Password" => $api_password, "acct1.Signature" => "{API_SIGNATURE}", "acct1.AppId" => "APP-80W284485P519543T");
$adaptivePaymentsService = new AdaptivePaymentsService($sdkConfig);
$payResponse = $adaptivePaymentsService->Pay($payRequest);
		 be converted.
		 * `ConvertToCurrencyList` - A list of currencies to convert to.
*/
$convertCurrencyReq = new ConvertCurrencyRequest(new RequestEnvelope("en_US"), $baseAmountList, $convertToCurrencyList);
if ($_POST['countryCode'] != "") {
    $convertCurrencyReq->countryCode = $_POST['countryCode'];
}
if ($_POST['conversionType'] != "" && $_POST['conversionType'] != "- Select -") {
    $convertCurrencyReq->conversionType = $_POST['conversionType'];
}
/*
* 	 ## Creating service wrapper object
Creating service wrapper object to make API call and loading
Configuration::getAcctAndConfig() returns array that contains credential and config parameters
*/
$service = new AdaptivePaymentsService(Configuration::getAcctAndConfig());
try {
    /* wrap API method calls on the service object with a try catch */
    $response = $service->ConvertCurrency($convertCurrencyReq);
} catch (Exception $ex) {
    require_once 'Common/Error.php';
    exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>PayPal Adaptive Payments - Convert Currency</title>
<link href="Common/sdk.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="Common/sdk_functions.js"></script>
</head>
Ejemplo n.º 11
0
 public function paypalstatus()
 {
     $request = Requests::find(Session::get('request_id'));
     $requestEnvelope = new RequestEnvelope("en_US");
     $paymentDetailsRequest = new PaymentDetailsRequest($requestEnvelope);
     $paymentDetailsRequest->payKey = "AP-2K156847LU642333B";
     $sdkConfig = array("mode" => Config::get('app.paypal_sdk_mode'), "acct1.UserName" => Config::get('app.paypal_sdk_UserName'), "acct1.Password" => Config::get('app.paypal_sdk_Password'), "acct1.Signature" => Config::get('app.paypal_sdk_Signature'), "acct1.AppId" => Config::get('app.paypal_sdk_AppId'));
     $adaptivePaymentsService = new AdaptivePaymentsService($sdkConfig);
     $paymentDetailsResponse = $adaptivePaymentsService->PaymentDetails($paymentDetailsRequest);
     Log::info('paymentDetailsResponse = ' . print_r($paymentDetailsResponse, true));
     Log::info('payKey = ' . print_r($paymentDetailsResponse->{'payKey'}, true));
     $request->payment_id = $paymentDetailsResponse->{'payKey'};
     $request->is_paid = 1;
     $request->save();
     return Redirect::to('/user/request-trip');
 }
require_once 'PPBootStrap.php';
// create request
$requestEnvelope = new RequestEnvelope("en_US");
$confirmPreapprovalReq = new ConfirmPreapprovalRequest($requestEnvelope, $_POST['preapprovalKey']);
// set optional params
if ($_POST['fundingSourceId'] != "") {
    $confirmPreapprovalReq->fundingSourceId = $_POST['fundingSourceId'];
}
if ($_POST['pin'] != "") {
    $confirmPreapprovalReq->pin = $_POST['pin'];
}
/*
Configuration::getAcctAndConfig() returns array that contains credential and config parameters
*/
$service = new AdaptivePaymentsService(Configuration::getAcctAndConfig());
try {
    $response = $service->ConfirmPreapproval($confirmPreapprovalReq);
} catch (Exception $ex) {
    require_once 'Common/Error.php';
    exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>PayPal Adaptive Payments - Confirm Preapproval</title>
<link href="Common/sdk.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="Common/sdk_functions.js"></script>
</head>
<?php

require_once 'PPBootStrap.php';
// create request
$requestEnvelope = new RequestEnvelope("en_US");
$getAllowedFundingSourcesReq = new GetAllowedFundingSourcesRequest($requestEnvelope, $_POST['key']);
/*
Configuration::getAcctAndConfig() returns array that contains credential and config parameters
*/
$service = new AdaptivePaymentsService(Configuration::getAcctAndConfig());
try {
    $response = $service->GetAllowedFundingSources($getAllowedFundingSourcesReq);
} catch (Exception $ex) {
    require_once 'Common/Error.php';
    exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>PayPal Adaptive Payments - Get Allowed Funding Sources</title>
<link href="Common/sdk.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="Common/sdk_functions.js"></script>
</head>

<body>
	<div id="wrapper">
		<img src="https://devtools-paypal.com/image/bdg_payments_by_pp_2line.png"/>
		<div id="response_form">
			<h3>Get Allowed Funding Sources</h3>
<?php 
Ejemplo n.º 14
0
 public function preapprove()
 {
     $logger = new PPLoggingManager('Preapproval');
     // ##PreapprovalRequest
     // The code for the language in which errors are returned, which must be
     // en_US.
     $requestEnvelope = new RequestEnvelope("en_US");
     // `PreapprovalRequest` takes mandatory params:
     //
     // * `RequestEnvelope` - Information common to each API operation, such
     // as the language in which an error message is returned.
     // * `Cancel URL` - URL to redirect the sender's browser to after
     // canceling the preapproval
     // * `Currency Code` - The code for the currency in which the payment is
     // made; you can specify only one currency, regardless of the number of
     // receivers
     // * `Return URL` - URL to redirect the sender's browser to after the
     // sender has logged into PayPal and confirmed the preapproval
     // * `Starting Date` - First date for which the preapproval is valid. It
     // cannot be before today's date or after the ending date.
     $preapprovalRequest = new PreapprovalRequest($requestEnvelope, "http://localhost/cancel", "USD", "http://localhost/return", "2013-12-18");
     // The URL to which you want all IPN messages for this preapproval to be
     // sent.
     // This URL supersedes the IPN notification URL in your profile
     $preapprovalRequest->ipnNotificationUrl = "http://localhost/ipn";
     // ## Creating service wrapper object
     // Creating service wrapper object to make API call and loading
     // configuration file for your credentials and endpoint
     $service = new AdaptivePaymentsService();
     try {
         // ## Making API call
         // Invoke the appropriate method corresponding to API in service
         // wrapper object
         $response = $service->Preapproval($preapprovalRequest);
     } catch (Exception $ex) {
         $logger->error("Error Message : " . $ex->getMessage());
     }
     // ## Accessing response parameters
     // You can access the response parameters in
     // response object as shown below
     // ### Success values
     if ($response->responseEnvelope->ack == "Success") {
         // The status of the payment. Possible values are:
         //
         // * CREATED - The payment request was received; funds will be
         // transferred once the payment is approved
         // * COMPLETED - The payment was successful
         // * INCOMPLETE - Some transfers succeeded and some failed for a
         // parallel payment or, for a delayed chained payment, secondary
         // receivers have not been paid
         // * ERROR - The payment failed and all attempted transfers failed
         // or all completed transfers were successfully reversed
         // * REVERSALERROR - One or more transfers failed when attempting
         // to reverse a payment
         // * PROCESSING - The payment is in progress
         // * PENDING - The payment is awaiting processing
         //$logger->log("Payment Status : ".$response);
         var_dump($response);
     } else {
         $logger->error("API Error Message : " . $response->error[0]->message);
     }
     return $response;
 }
 public function convert()
 {
     $logger = new PPLoggingManager('ConvertCurrency');
     // ##ConvertCurrencyRequest
     // The ConvertCurrencyRequest message enables you to have your
     // application get an estimated exchange rate for a list of amounts.
     // This API operation does not affect PayPal balances.
     // The code for the language in which errors are returned, which must be
     // en_US.
     $requestEnvelope = new RequestEnvelope("en_US");
     // `CurrencyList` which takes two arguments:
     //
     // * `CurrencyCodeType` - The currency code. Allowable values are:
     // * Australian Dollar - AUD
     // * Brazilian Real - BRL
     // `Note:
     // The Real is supported as a payment currency and currency balance only
     // for Brazilian PayPal accounts.`
     // * Canadian Dollar - CAD
     // * Czech Koruna - CZK
     // * Danish Krone - DKK
     // * Euro - EUR
     // * Hong Kong Dollar - HKD
     // * Hungarian Forint - HUF
     // * Israeli New Sheqel - ILS
     // * Japanese Yen - JPY
     // * Malaysian Ringgit - MYR
     // `Note:
     // The Ringgit is supported as a payment currency and currency balance
     // only for Malaysian PayPal accounts.`
     // * Mexican Peso - MXN
     // * Norwegian Krone - NOK
     // * New Zealand Dollar - NZD
     // * Philippine Peso - PHP
     // * Polish Zloty - PLN
     // * Pound Sterling - GBP
     // * Singapore Dollar - SGD
     // * Swedish Krona - SEK
     // * Swiss Franc - CHF
     // * Taiwan New Dollar - TWD
     // * Thai Baht - THB
     // * Turkish Lira - TRY
     // `Note:
     // The Turkish Lira is supported as a payment currency and currency
     // balance only for Turkish PayPal accounts.`
     // * U.S. Dollar - USD
     // * `amount`
     $baseAmountList = new CurrencyList();
     $baseAmountList->currency[] = new CurrencyType("USD", "4.00");
     // `CurrencyCodeList` which contains
     //
     // * `Currency Code` - Allowable values are:
     // * Australian Dollar - AUD
     // * Brazilian Real - BRL
     // `Note:
     // The Real is supported as a payment currency and currency balance only
     // for Brazilian PayPal accounts.`
     // * Canadian Dollar - CAD
     // * Czech Koruna - CZK
     // * Danish Krone - DKK
     // * Euro - EUR
     // * Hong Kong Dollar - HKD
     // * Hungarian Forint - HUF
     // * Israeli New Sheqel - ILS
     // * Japanese Yen - JPY
     // * Malaysian Ringgit - MYR
     // `Note:
     // The Ringgit is supported as a payment currency and currency balance
     // only for Malaysian PayPal accounts.`
     // * Mexican Peso - MXN
     // * Norwegian Krone - NOK
     // * New Zealand Dollar - NZD
     // * Philippine Peso - PHP
     // * Polish Zloty - PLN
     // * Pound Sterling - GBP
     // * Singapore Dollar - SGD
     // * Swedish Krona - SEK
     // * Swiss Franc - CHF
     // * Taiwan New Dollar - TWD
     // * Thai Baht - THB
     // * Turkish Lira - TRY
     // `Note:
     // The Turkish Lira is supported as a payment currency and currency
     // balance only for Turkish PayPal accounts.`
     // * U.S. Dollar - USD
     $convertToCurrencyList = new CurrencyCodeList();
     $convertToCurrencyList->currencyCode[] = "GBP";
     // `ConvertCurrencyRequest` which takes params:
     //
     // * `Request Envelope` - Information common to each API operation, such
     // as the language in which an error message is returned
     // * `BaseAmountList` - A list of amounts with associated currencies to
     // be converted.
     // * `ConvertToCurrencyList` - A list of currencies to convert to.
     $convertCurrencyReq = new ConvertCurrencyRequest($requestEnvelope, $baseAmountList, $convertToCurrencyList);
     // ## Creating service wrapper object
     // Creating service wrapper object to make API call and loading
     // configuration file for your credentials and endpoint
     $service = new AdaptivePaymentsService();
     try {
         // ## Making API call
         // Invoke the appropriate method corresponding to API in service
         // wrapper object
         $response = $service->ConvertCurrency($convertCurrencyReq);
     } catch (Exception $ex) {
         $logger->error("Error Message : " . $ex->getMessage());
     }
     // ## Accessing response parameters
     // You can access the response parameters using getter methods in
     // response object as shown below
     // ### Success values
     if ($response->responseEnvelope->ack == "Success") {
         if ($response->estimatedAmountTable->currencyConversionList != null && sizeof($response->estimatedAmountTable->currencyConversionList) > 0) {
             $currencyConversionList = $response->estimatedAmountTable->currencyConversionList;
             foreach ($currencyConversionList as $fromCurrency) {
                 $logger->log("Amount to be Converted : " . $fromCurrency->baseAmount->amount . $fromCurrency->baseAmount->code);
                 $toCurrency = $fromCurrency->currencyList->currency;
                 foreach ($toCurrency as $convertedTo) {
                     $logger->log("Converted amount : " . $convertedTo->amount . $convertedTo->code);
                 }
             }
         }
     } else {
         $logger->error("API Error Message : " . $response->error[0]->message);
     }
     return $response;
 }
Ejemplo n.º 16
0
 private function makeAPICall($payRequest)
 {
     $logger = new PPLoggingManager('Pay');
     // ## Creating service wrapper object
     // Creating service wrapper object to make API call and loading
     // configuration file for your credentials and endpoint
     $service = new AdaptivePaymentsService();
     try {
         // ## Making API call
         // Invoke the appropriate method corresponding to API in service
         // wrapper object
         $response = $service->Pay($payRequest);
     } catch (Exception $ex) {
         $logger->error("Error Message : " . $ex->getMessage());
     }
     // ## Accessing response parameters
     // You can access the response parameters in
     // response object as shown below
     // ### Success values
     if ($response->responseEnvelope->ack == "Success") {
         // The pay key, which is a token you use in other Adaptive
         // Payment APIs (such as the Refund Method) to identify this
         // payment. The pay key is valid for 3 hours; the payment must
         // be approved while the pay key is valid.
         $logger->log("Pay Key : " . $response->payKey);
         // Once you get success response, user has to redirect to PayPal
         // for the payment. Construct redirectURL as follows,
         // `redirectURL=https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_ap-payment&paykey="
         // + $response->payKey`
     } else {
         $logger->error("API Error Message : " . $response->error[0]->message);
     }
     return $response;
 }
Ejemplo n.º 17
0
 /**
  *
  *
  * @param unknown $pay_key
  * @param unknown $order_id
  *
  * @return unknown
  */
 public function set_paypal_author_specifics($pay_key, $order_id)
 {
     global $woocommerce;
     $this->include_paypal_sdk();
     $order = new WC_Order($order_id);
     // Create request
     $setPaymentOptionsRequest = new SetPaymentOptionsRequest(new RequestEnvelope("en_US"));
     $setPaymentOptionsRequest->payKey = $pay_key;
     if ($this->instapay) {
         $setPaymentOptionsRequest = $this->set_vendor_items($order, $setPaymentOptionsRequest);
     }
     if ($this->debug_me) {
         foreach ($setPaymentOptionsRequest->receiverOptions as $k) {
             var_dump($k->invoiceData);
         }
         exit;
     }
     $setPaymentOptionsRequest->senderOptions = new SenderOptions();
     $setPaymentOptionsRequest->senderOptions->requireShippingAddressSelection = true;
     $service = new AdaptivePaymentsService();
     try {
         $response = $service->SetPaymentOptions($setPaymentOptionsRequest);
     } catch (Exception $ex) {
         wc_add_notice(sprintf(__('Error: %s', 'wcvendors'), $ex->getMessage()), 'error');
         return false;
     }
     $this->logger->error("Received SetPaymentOptionsResponse:");
     $ack = strtoupper($response->responseEnvelope->ack);
     if ($ack != "SUCCESS") {
         $order->update_status('cancelled', __(sprintf('Error ID: %s. %s', $response->error[0]->errorId, $response->error[0]->message), 'wcvendors'));
         wc_add_notice(sprintf('Error ID: %s. %s', $response->error[0]->errorId, $response->error[0]->message), 'error');
         return false;
     }
     return true;
 }
Ejemplo n.º 18
0
        if ($_POST['paymentType'][$i] != "" && $_POST['paymentType'][$i] != DEFAULT_SELECT) {
            $receiver[$i]->paymentType = $_POST['paymentType'][$i];
        }
        if ($_POST['paymentSubType'][$i] != "") {
            $receiver[$i]->paymentSubType = $_POST['paymentSubType'][$i];
        }
        if ($_POST['phoneCountry'][$i] != "" && $_POST['phoneNumber'][$i]) {
            $receiver[$i]->phone = new PhoneNumberType($_POST['phoneCountry'][$i], $_POST['phoneNumber'][$i]);
            if ($_POST['phoneExtn'][$i] != "") {
                $receiver[$i]->phone->extension = $_POST['phoneExtn'][$i];
            }
        }
    }
    $refundRequest->receiverList = new ReceiverList($receiver);
}
$service = new AdaptivePaymentsService();
try {
    $response = $service->Refund($refundRequest);
    $logger->error("Received RefundResponse:");
    $ack = strtoupper($response->responseEnvelope->ack);
} catch (Exception $ex) {
    throw new Exception('Error occurred in Refund method');
}
if ($ack != "SUCCESS") {
    echo "<b>Error </b>";
    echo "<pre>";
    print_r($response);
    echo "</pre>";
    require_once 'Common/Response.php';
    exit;
}
 * (Optional) The pay key that identifies the payment to be executed. This is the pay key returned in the PayResponse message. 
 */
$executePaymentRequest = new ExecutePaymentRequest(new RequestEnvelope("en_US"), $_POST['payKey']);
$executePaymentRequest->actionType = $_POST["actionType"];
/*
 * The ID of the funding plan from which to make this payment.
 */
if ($_POST["fundingPlanID"] != "") {
    $executePaymentRequest->fundingPlanId = $_POST["fundingPlanID"];
}
/*
* 	 ## Creating service wrapper object
Creating service wrapper object to make API call and loading
Configuration::getAcctAndConfig() returns array that contains credential and config parameters
*/
$service = new AdaptivePaymentsService(Configuration::getAcctAndConfig());
try {
    /* wrap API method calls on the service object with a try catch */
    $response = $service->ExecutePayment($executePaymentRequest);
} catch (Exception $ex) {
    require_once 'Common/Error.php';
    exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>PayPal Adaptive Payments - Execute Payment</title>
<link href="Common/sdk.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="Common/sdk_functions.js"></script>
</head>
Ejemplo n.º 20
0
 function doCancelPreapproval($backing)
 {
     // $backing is projectbacking record
     extract($backing);
     $this->con->update("update projectbacking set payment_status='c' where backingId='" . $backingId . "'");
     if (isset($paypalId) && !empty($paypalId) && $paypalid != 0) {
         $this->con->update("update paypaltransaction set status='CANCELLED' where paypalId='" . $paypalId . "'");
     }
     $requestEnvelope = new RequestEnvelope("en_US");
     $cancelPreapprovalReq = new CancelPreapprovalRequest($requestEnvelope, $preapproval_key);
     wrtlog("DEBUG cancelPreapprovalReq=" . print_r($cancelPreapprovalReq, true));
     $service = new AdaptivePaymentsService(Configuration::getAcctAndConfig());
     try {
         $response = $service->CancelPreapproval($cancelPreapprovalReq);
         $final_arr = array();
         $preq = dismount($cancelPreapprovalReq);
         foreach ($preq as $K => $P) {
             $final_arr[addslashes($K)] = addslashes(is_array($P) ? json_encode($P) : $P);
         }
         if (is_object($response)) {
             $newarray = dismount($response);
             $response = $newarray;
         }
         foreach ($response as $K => $P) {
             $final_arr[addslashes($K)] = addslashes(is_array($P) ? json_encode($P) : $P);
         }
         $final_arr['url'] = get_url();
         $this->con->insert("insert into preapproval_detail (detail) values ('" . mysql_real_escape_string(json_encode($final_arr)) . "')");
         $cancel_detail_id = mysql_insert_id();
         $this->con->update("update projectbacking set cancel_detail_id='" . $cancel_detail_id . "' where backingId='" . $backingId . "'");
         wrtlog("DEBUG doCancelPreapproval response for project {$projectId} : " . print_r($response, true));
     } catch (Exception $ex) {
         wrtlog("DEBUG doCancelPreapproval error: " . $ex->getMessage());
         wrtlog("DEBUG doCancelPreapproval request: " . print_r($cancelPreapprovalReq, true));
         require_once 'Common/Error.php';
         /// THIS IS CALLED BY automatic_cron.php ////
         /// SO TBD IF WE SHOULD STOP IT          ////
         exit;
     }
 }
*/
if ($_POST['payKey'] != "") {
    $paymentDetailsReq->payKey = $_POST['payKey'];
}
if ($_POST['transactionId'] != "") {
    $paymentDetailsReq->transactionId = $_POST['transactionId'];
}
if ($_POST['trackingId'] != "") {
    $paymentDetailsReq->trackingId = $_POST['trackingId'];
}
/*
* 	 ## Creating service wrapper object
Creating service wrapper object to make API call and loading
Configuration::getAcctAndConfig() returns array that contains credential and config parameters
*/
$service = new AdaptivePaymentsService(Configuration::getAcctAndConfig());
try {
    /* wrap API method calls on the service object with a try catch */
    $response = $service->PaymentDetails($paymentDetailsReq);
} catch (Exception $ex) {
    require_once 'Common/Error.php';
    exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>PayPal Adaptive Payments - Payment Details</title>
<link href="Common/sdk.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="Common/sdk_functions.js"></script>
</head>
Ejemplo n.º 22
0
<?php

$path = '../lib';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);
require_once 'services/AdaptivePayments/AdaptivePaymentsService.php';
require_once 'PPLoggingManager.php';
$logger = new PPLoggingManager('GetUserLimits');
// create request
$requestEnvelope = new RequestEnvelope("en_US");
$getUserLimitsReq = new GetUserLimitsRequest($requestEnvelope, $_POST['preapprovalKey']);
$logger->log("Created GetUserLimitsRequest Object");
$service = new AdaptivePaymentsService();
try {
    $response = $service->GetUserLimits($getUserLimitsReq);
    $logger->error("Received GetUserLimitsResponse:");
    $ack = strtoupper($response->responseEnvelope->ack);
} catch (Exception $ex) {
    throw new Exception('Error occurred in GetUserLimits method');
}
if ($ack != "SUCCESS") {
    echo "<b>Error </b>";
    echo "<pre>";
    print_r($response);
    echo "</pre>";
    require_once 'Common/Response.php';
    exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
Ejemplo n.º 23
0
 public function refundTheAmt()
 {
     $logger = new PPLoggingManager('Refund');
     // ##RefundRequest
     // The code for the language in which errors are returned, which must be
     // en_US.
     $requestEnvelope = new RequestEnvelope("en_US");
     // `RefundRequest` which takes,
     // `Request Envelope` - Information common to each API operation, such
     // as the language in which an error message is returned.
     $refundRequest = new RefundRequest($requestEnvelope);
     // You must specify either,
     //
     // * `Pay Key` - The pay key that identifies the payment for which you
     // want to retrieve details. This is the pay key returned in the
     // PayResponse message.
     // * `Transaction ID` - The PayPal transaction ID associated with the
     // payment. The IPN message associated with the payment contains the
     // transaction ID.
     // `$refundRequest->transactionId`
     // * `Tracking ID` - The tracking ID that was specified for this payment
     // in the PayRequest message.
     // `$refundRequest->trackingId`
     $refundRequest->payKey = "AP-6KL026467X0532357";
     // ## Creating service wrapper object
     // Creating service wrapper object to make API call and loading
     // configuration file for your credentials and endpoint
     $service = new AdaptivePaymentsService();
     try {
         // ## Making API call
         // Invoke the appropriate method corresponding to API in service
         // wrapper object
         $response = $service->Refund($refundRequest);
     } catch (Exception $ex) {
         $logger->error("Error Message : " . $ex->getMessage());
     }
     // ## Accessing response parameters
     // You can access the response parameters using getter methods in
     // response object as shown below
     // ### Success values
     if ($response->responseEnvelope->ack == "Success") {
         // List of refunds associated with the payment.
         $refundList = $response->refundInfoList->refundInfo;
         // Represents the refund attempt made to a receiver of a
         // PayRequest.
         foreach ($refundList as $refundInfo) {
             // Status of the refund. It is one of the following values:
             //
             // * REFUNDED - Refund successfully completed
             // * REFUNDED_PENDING - Refund awaiting transfer of funds; for
             // example, a refund paid by eCheck.
             // * NOT_PAID - Payment was never made; therefore, it cannot
             // be refunded.
             // * ALREADY_REVERSED_OR_REFUNDED - Request rejected because
             // the refund was already made, or the payment was reversed
             // prior to this request.
             // * NO_API_ACCESS_TO_RECEIVER - Request cannot be completed
             // because you do not have third-party access from the
             // receiver to make the refund.
             // * REFUND_NOT_ALLOWED - Refund is not allowed.
             // * INSUFFICIENT_BALANCE - Request rejected because the
             // receiver from which the refund is to be paid does not
             // have sufficient funds or the funding source cannot be
             // used to make a refund.
             // * AMOUNT_EXCEEDS_REFUNDABLE - Request rejected because you
             // attempted to refund more than the remaining amount of the
             // payment; call the PaymentDetails API operation to
             // determine the amount already refunded.
             // * PREVIOUS_REFUND_PENDING - Request rejected because a
             // refund is currently pending for this part of the payment
             // * NOT_PROCESSED - Request rejected because it cannot be
             // processed at this time
             // * REFUND_ERROR - Request rejected because of an internal
             // error
             // * PREVIOUS_REFUND_ERROR - Request rejected because another
             // part of this refund caused an internal error.
             $logger->log("Refund Status : " . $refundInfo->refundStatus);
         }
     } else {
         $logger->error("API Error Message : " . $response->error[0]->message);
     }
     return $response;
 }
/*
 *  (Required) The payment paykey that identifies the account holder for whom you want to obtain the selected shipping address.
Note:

Shipping information can only be retrieved through the payment payKey; not through the preapprovalKey.
*/
/*
 * (Required) Information common to each API operation, such as the language in which an error message is returned.
 */
$getShippingAddressesReq = new GetShippingAddressesRequest(new RequestEnvelope("en_US"), $_POST['key']);
/*
* 	 ## Creating service wrapper object
Creating service wrapper object to make API call and loading
Configuration::getAcctAndConfig() returns array that contains credential and config parameters
*/
$service = new AdaptivePaymentsService(Configuration::getAcctAndConfig());
try {
    /* wrap API method calls on the service object with a try catch */
    $response = $service->GetShippingAddresses($getShippingAddressesReq);
} catch (Exception $ex) {
    require_once 'Comon/Error.php';
    exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>PayPal Adaptive Payments - Get Shipping Addresses</title>
<link href="Common/sdk.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="Common/sdk_functions.js"></script>
</head>
/*
 * The code for the currency in which the payment is made; you can specify only one currency, regardless of the number of receivers 
 */
/*
 * URL to redirect the sender's browser to after canceling the approval for a payment; it is always required but only used for payments that require approval (explicit payments) 
 */
/*
 * 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 
 */
$payRequest = new PayRequest(new RequestEnvelope("en_US"), $_POST['actionType'], $_POST['cancelUrl'], $_POST['currencyCode'], $receiverList, $_POST['returnUrl']);
/*
* 	 ## Creating service wrapper object
Creating service wrapper object to make API call and loading
Configuration::getAcctAndConfig() returns array that contains credential and config parameters
*/
$service = new AdaptivePaymentsService(Configuration::getAcctAndConfig());
try {
    /* wrap API method calls on the service object with a try catch */
    $response = $service->Pay($payRequest);
} catch (Exception $ex) {
    require_once '../Common/Error.php';
    exit;
}
/* Make the call to PayPal to get the Pay token
 If the API call succeded, then redirect the buyer to PayPal
to begin to authorize payment.  If an error occured, show the
resulting errors */
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html>
Ejemplo n.º 26
0
<?php

$path = '../lib';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);
require_once 'services/AdaptivePayments/AdaptivePaymentsService.php';
require_once 'PPLoggingManager.php';
$logger = new PPLoggingManager('CancelPreapproval');
// create request
$requestEnvelope = new RequestEnvelope("en_US");
$cancelPreapprovalReq = new CancelPreapprovalRequest($requestEnvelope, $_POST['preapprovalKey']);
$logger->log("Created CancelPreapprovalRequest Object");
$service = new AdaptivePaymentsService();
try {
    $response = $service->CancelPreapproval($cancelPreapprovalReq);
    $logger->error("Received CancelPreapprovalResponse:");
    $ack = strtoupper($response->responseEnvelope->ack);
} catch (Exception $ex) {
    throw new Exception('Error occurred in CancelPreapproval method');
}
if ($ack != "SUCCESS") {
    echo "<b>Error </b>";
    echo "<pre>";
    print_r($response);
    echo "</pre>";
    require_once 'Common/Response.php';
    exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    $preapprovalRequest->feesPayer = $_POST['feesPayer'];
}
/*
 * (Optional) Whether to display the maximum total amount of this preapproval. It is one of the following values:
   TRUE – Display the amount
    FALSE – Do not display the amount (default)
*/
if ($_POST['displayMaxTotalAmount'] != null) {
    $preapprovalRequest->displayMaxTotalAmount = $_POST['displayMaxTotalAmount'];
}
/*
* 	 ## Creating service wrapper object
Creating service wrapper object to make API call and loading
Configuration::getAcctAndConfig() returns array that contains credential and config parameters
*/
$service = new AdaptivePaymentsService(Configuration::getAcctAndConfig());
try {
    /* wrap API method calls on the service object with a try catch */
    $response = $service->Preapproval($preapprovalRequest);
} catch (Exception $ex) {
    require_once 'Common/Error.php';
    exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>PayPal Adaptive Payments - Preapproval</title>
<link href="Common/sdk.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="Common/sdk_functions.js"></script>
</head>
require_once 'PPBootStrap.php';
/*
 * Use the GetFundingPlans API operation to determine the funding sources that are available for a specified payment, identified by its key, which takes into account the preferences and country of the receiver as well as the payment amount. You must be both the sender of the payment and the caller of this API operation 
 */
/*
 * The key used to create the payment whose funding sources you want to determine. 
 * The code for the language in which errors are returned, which must be en_US.
 */
$getFundingPlansReq = new GetFundingPlansRequest(new RequestEnvelope("en_US"), $_POST['payKey']);
/*
* 	 ## Creating service wrapper object
Creating service wrapper object to make API call and loading
Configuration::getAcctAndConfig() returns array that contains credential and config parameters
*/
$service = new AdaptivePaymentsService(Configuration::getAcctAndConfig());
try {
    /* wrap API method calls on the service object with a try catch */
    $response = $service->GetFundingPlans($getFundingPlansReq);
} catch (Exception $ex) {
    require_once 'Common/Error.php';
    exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>PayPal Adaptive Payments - Get Funding Plans</title>
<link href="Common/sdk.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="Common/sdk_functions.js"></script>
</head>
 *  You use the GetPaymentOptions API operation to retrieve the payment options passed with the SetPaymentOptionsRequest. 
 */
/*
 * (Required) Information common to each API operation, such as the language in which an error message is returned.
 */
$requestEnvelope = new RequestEnvelope("en_US");
/*
 * (Required) The pay key that identifies the payment for which you want to get payment options. This is the pay key you used to set the payment options.
 */
$getPaymentOptionsReq = new GetPaymentOptionsRequest($requestEnvelope, $_POST['payKey']);
/*
* 	 ## Creating service wrapper object
Creating service wrapper object to make API call and loading
Configuration::getAcctAndConfig() returns array that contains credential and config parameters
*/
$service = new AdaptivePaymentsService(Configuration::getAcctAndConfig());
try {
    /* wrap API method calls on the service object with a try catch */
    $response = $service->GetPaymentOptions($getPaymentOptionsReq);
} catch (Exception $ex) {
    require_once 'Common/Error.php';
    exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>PayPal Adaptive Payments - Get Payment Options</title>
<link href="Common/sdk.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="Common/sdk_functions.js"></script>
</head>
 /**
  * Process the payment and return the result
  *
  * @access public
  * @param int     $order_id
  * @return array
  */
 function process_payment($order_id)
 {
     $receiver = array();
     $payRequest = new PayRequest();
     $order = new WC_Order($order_id);
     $sub_orders = get_children(array('post_parent' => $order_id, 'post_type' => 'shop_order'));
     if ($sub_orders) {
         $sum = 0;
         foreach ($sub_orders as $key => $order_post) {
             $seller_id = dokan_get_seller_id_by_order($order_post->ID);
             $seller_balance = $this->get_seller_net_balance($order_post->ID, $seller_id);
             $seller_pay_email = dokan_get_seller_withdraw_mail($seller_id);
             if (false === $seller_pay_email) {
                 $seller_pay_email = get_user_by('id', $seller_id)->user_email;
             }
             $receiver[$key] = new Receiver();
             $receiver[$key]->amount = $seller_balance;
             $receiver[$key]->email = $seller_pay_email;
             $sum += (double) $seller_balance;
         }
         if ($this->payment_process == 'chained') {
             $admin_amount = (string) $order->get_total();
         } else {
             $admin_amount = (string) ((double) $order->get_total() - $sum);
         }
     } else {
         $seller_id = dokan_get_seller_id_by_order($order_id);
         $seller_balance = $this->get_seller_net_balance($order_id, $seller_id);
         $seller_pay_email = dokan_get_seller_withdraw_mail($seller_id);
         if (false === $seller_pay_email) {
             $seller_pay_email = get_user_by('id', $seller_id)->user_email;
         }
         $receiver[0] = new Receiver();
         $receiver[0]->amount = $seller_balance;
         $receiver[0]->email = $seller_pay_email;
         if ($this->payment_process == 'chained') {
             if ($this->single_mode == 'yes') {
                 $admin_amount = (string) ((double) $order->get_total() - (double) $seller_balance);
                 $receiver[0]->amount = (string) $order->get_total();
             } else {
                 $admin_amount = (string) $order->get_total();
             }
         } else {
             $admin_amount = (string) ((double) $order->get_total() - (double) $seller_balance);
         }
     }
     $count = count($receiver);
     if ($admin_amount > 0) {
         $receiver[$count] = new Receiver();
         $receiver[$count]->amount = $admin_amount;
         $receiver[$count]->email = $this->pa_admin_email;
     }
     if ($this->payment_process == 'chained') {
         if ($this->single_mode == 'yes') {
             $receiver[0]->primary = "true";
         } else {
             $receiver[$count]->primary = "true";
         }
     }
     $this->add_log('Payment Process: ' . $this->payment_process . ' ------ Reciever list' . print_r($receiver, true) . '...');
     $receiverList = new ReceiverList($receiver);
     $payRequest->receiverList = $receiverList;
     $requestEnvelope = new RequestEnvelope("en_US");
     $payRequest->requestEnvelope = $requestEnvelope;
     $payRequest->actionType = "PAY";
     $payRequest->cancelUrl = esc_url($order->get_cancel_order_url());
     $payRequest->returnUrl = esc_url($this->get_return_url($order));
     $payRequest->currencyCode = get_woocommerce_currency();
     $payRequest->ipnNotificationUrl = $this->notify_url;
     if ('yes' == $this->testmode) {
         $sdkConfig = array("mode" => "sandbox", "acct1.UserName" => $this->test_appuser, "acct1.Password" => $this->test_apppass, "acct1.Signature" => $this->test_appsig, "acct1.AppId" => "APP-80W284485P519543T");
     } else {
         $sdkConfig = array("mode" => "live", "acct1.UserName" => $this->appuser, "acct1.Password" => $this->apppass, "acct1.Signature" => $this->appsig, "acct1.AppId" => $this->appid);
     }
     $adaptivePaymentsService = new AdaptivePaymentsService($sdkConfig);
     $payResponse = $adaptivePaymentsService->Pay($payRequest);
     if ($payResponse->payKey) {
         $shippingAddressInfo = new ShippingAddressInfo();
         $shippingAddressInfo->addresseeName = $order->billing_first_name . ' ' . $order->billing_last_name;
         $shippingAddressInfo->street1 = $order->billing_address_1;
         $shippingAddressInfo->street2 = $order->billing_address_2;
         $shippingAddressInfo->city = $order->billing_city;
         $shippingAddressInfo->zip = $order->billing_postcode;
         $shippingAddressInfo->state = $this->get_paypal_state($order->billing_country, $order->billing_state);
         $shippingAddressInfo->country = $order->billing_country;
         if ('yes' == $this->send_shipping) {
             $shippingAddressInfo->addresseeName = $order->shipping_first_name . ' ' . $order->shipping_last_name;
             $shippingAddressInfo->street1 = $order->shipping_address_1;
             $shippingAddressInfo->street2 = $order->shipping_address_2;
             $shippingAddressInfo->city = $order->shipping_city;
             $shippingAddressInfo->zip = $order->shipping_postcode;
             $shippingAddressInfo->state = $this->get_paypal_state($order->shipping_country, $order->shipping_state);
             $shippingAddressInfo->country = $order->shipping_country;
         }
         $so = new SenderOptions();
         $so->shippingAddress = $shippingAddressInfo;
         $re = new RequestEnvelope('en_US');
         $setPaymentOptionsRequest = new SetPaymentOptionsRequest($re, $payResponse->payKey);
         $setPaymentOptionsRequest->senderOptions = $so;
         $paymentOptionRequest = $adaptivePaymentsService->SetPaymentOptions($setPaymentOptionsRequest);
     }
     $this->add_log('Payment Response: ' . print_r($payResponse, true));
     // update paykey reference to find out
     update_post_meta($order->id, '_dokan_pap_key', $payResponse->payKey);
     if ('yes' == $this->testmode) {
         $paypal_url = "https://www.sandbox.paypal.com/webscr?cmd=_ap-payment&paykey=" . $payResponse->payKey;
     } else {
         $paypal_url = "https://www.paypal.com/webscr?cmd=_ap-payment&paykey=" . $payResponse->payKey;
     }
     // Return thankyou redirect
     return array('result' => 'success', 'redirect' => $paypal_url);
 }