Paypal Refund Option Programmatically - php

I have integrated paypal payment in my project .
I would like to include automatic refund option.
require_once('includes/paypal.class.php');
require_once('includes/paypal.adaptive.class.php');
include('includes/config.php');
// Create PayPal object.
$PayPalConfig = array(
'Sandbox' => $sandbox,
'DeveloperAccountEmail' => $developer_account_email,
'ApplicationID' => $application_id,
'DeviceID' => $device_id,
'IPAddress' => $_SERVER['REMOTE_ADDR'],
'APIUsername' => $api_username,
'APIPassword' => $api_password,
'APISignature' => $api_signature,
'APISubject' => $api_subject
);
$PayPal = new PayPal_Adaptive($PayPalConfig);
// Prepare request arrays
$RefundFields = array(
'CurrencyCode' => USD',
// Required. Must specify code used for original payment. You do not need to specify if you use a payKey to refund a completed transaction.
'PayKey' => '',
// Required. The key used to create the payment that you want to refund.
'TransactionID' => '7C0359353Y165821P',
// Required. The PayPal transaction ID associated with the payment that you want to refund.
'TrackingID' => ''
// Required. The tracking ID associated with the payment that you want to refund.
);
$Receivers = array();
$Receiver = array(
'Email' => 'jilu#newagesmb.com',
// A receiver's email address.
'Amount' => '100.00',
// Amount to be debited to the receiver's account.
'Primary' => '',
// Set to true to indicate a chained payment. Only one receiver can be a primary receiver. Omit this field, or set to false for simple and parallel payments.
'InvoiceID' => '',
'PaymentType' => 'GOODS'
// The transaction subtype for the payment. Allowable values are: GOODS, SERVICE
);
array_push($Receivers, $Receiver);
$PayPalRequestData = array(
'RefundFields' => $RefundFields,
'Receivers' => $Receivers
);
//print_r($PayPalRequestData);exit;
$PayPalResult = $PayPal->Refund($PayPalRequestData);
echo '<pre />';
print_r($PayPalResult);
My Output is:
2014-04-28T02:54:20.805-07:00Failure55b35d9b576e810680030560022PLATFORMApplicationErrorApplicationThe X-PAYPAL-APPLICATION-ID header contains an invalid valueX-PAYPAL-APPLICATION-ID

Did your application fully approved via PayPal?
You can check it from below link:
https://www.paypal-apps.com/user/my-account/applications
You can use application ID if it has been fully approved via PayPal. You can try this after confirmation from above URL.

Related

Does the creditCard function exist in Omnipay PayPal Express? Or only in PayPal Pro?

This question is maybe similar to THIS and THIS but I'm not entirely sure.
I've made a shopping cart that sends the product details and quantity/total amount to Paypal on checking out. I'm using Laravel 4 and the Omnipay Paypal plugin (Paypal_Express). I can send product details fine using the 'setItems' function and am now looking to pre-populate the credit card field on the Paypal summary page with my User's details.
I have seen in other SO threads such as THIS that other people use the creditCard function to pass details to the Paypal summary credit card info page.
My question: 1) Do you need to be using Paypal_Pro for the creditCard function to worK?
I get this error when I try (call_user_func_array() expects parameter 1 to be a valid callback, class 'Omnipay\Common\GatewayFactory' does not have a method 'creditCard').
I don't want to enter all the credit card details - Just speed the process up by entering the User's Name, Adress etc...
Also I tried changing to Paypal_Pro and it didn't work. (same error as above) I changed config plus gateways in my payment controller.
2)How do you change PayPal_Express to PayPay_Pro?
My code:
public function postPayment() {
$cart = Session::get('cart');
$allProducts = [];
foreach($cart->aContents as $productID=>$quantity){
$product = Product::find($productID);
// get the product id
// load the product from the id
// store data in the allProduct array
$allProducts[] = array('name' => $product->name, 'quantity' => $quantity, 'price'=> $product->price);
}
$cardInput = array(
'first_name' => Input::get('first_name'),
'last_name' => Input::get('last_name'),
'address1' => Input::get('address1'),
'city' => Input::get('city'),
'zip' => Input::get('zip'),
'email' => Input::get('email')
);
$card = Omnipay::creditCard($cardInput);
$params = array(
'cancelUrl' => \URL::to('cancel_order'),
'returnUrl' => \URL::to('payment_success'),
'amount' => Input::get('price'),
'currency' => Input::get('currency'),
'card' => $card,
);
Session::put('params', $params);
Session::save();
$gateway = Omnipay::create('PayPal_Express');
$gateway->setUsername('tjmusicmanagement-facilitator_api1.gmail.com');
$gateway->setPassword('K2LWQVP2L8472BPY');
$gateway->setSignature('AwTOuAJWzCkdc5PldYeiz.l3iy5UAwOucYW6EFLLA9zUQqXaWyEGbebq');
$gateway->setTestMode(true);
$gateway->setLogoImageUrl(URL::to('images/logoSmall.png'));
$response = $gateway->purchase($params)->setItems($allProducts)->send();
if ($response->isSuccessful()) {
// payment was successful: update database
print_r($response);
} elseif ($response->isRedirect()) {
// redirect to offsite payment gateway
$response->redirect();
} else {
// payment failed: display message to customer
echo $response->getMessage();
}
}
And also the ignited\laravel-omnipay\config.php is unchanged (though I did try changing the driver)
return array(
// The default gateway to use
'default' => 'paypal',
// Add in each gateway here
'gateways' => array(
'paypal' => array(
'driver' => 'PayPal_Express',
'options' => array(
'solutionType' => '',
'landingPage' => '',
'headerImageUrl' => ''
)
)
)
);
Thanks for your tinme!!
EDIT: Here is my getSuccessPayment function where I can hopefully get the users paypal details (just name and address etc) from paypal. But how and where do I specify this?
public function getSuccessPayment()
{
$gateway = Omnipay::create('PayPal_Express');
$gateway->setUsername('lillyloverofwar-facilitator_api1.gmail.com');
$gateway->setPassword('U6LM3SG2MNCA3QE2');
$gateway->setSignature('AJVP9tUtdotIeVt82RpcG7n9ld-tAdCG1Ramb1u8yZECHhSpiXc0BO04');
$gateway->setTestMode(true);
$params = Session::get('params');
$response = $gateway->completePurchase($params)->send();
$paypalResponse = $response->getData(); // this is the raw response object
if(isset($paypalResponse['PAYMENTINFO_0_ACK']) && $paypalResponse['PAYMENTINFO_0_ACK'] === 'Success') {
// return View::make('successfulPayment')->with($params);
// Session::flush();
// Response
// print_r($paypalResponse);
} else {
//Failed transaction
}
// FLUSHING SESSION HERE GETS AN ERROR
// Session::flush();
return View::make('successfulPayment');
}
1) I get this error when I try (call_user_func_array() expects parameter 1 to be a valid callback, class 'Omnipay\Common\GatewayFactory' does not have a method 'creditCard').
You can't use credit cards on the PayPal Express gateway, only on Pro or REST. I recommend that you use the REST gateway not the Pro gateway (REST supersedes Pro and has more features).
I don't want to enter all the credit card details - Just speed the process up by entering the User's Name, Adress etc...
There is no need to do that if you are using PayPal Express anyway, because PayPal will provide you the necessary details after the user has gone through the PayPal login process and authorized the transaction.
Also I tried changing to Paypal_Pro and it didn't work. (same error as above) I changed config plus gateways in my payment controller.
2)How do you change PayPal_Express to PayPay_Pro?
I suggest you have a look at my fork of the omnipay-paypal gateway, https://github.com/delatbabel/omnipay-paypal -- on the accept-paypal-payments branch there are additional commits (sent as a PR to the main repository but not merged yet) with additional features such as using the REST gateway for either Credit Card or PayPal purchases, and additional API documentation including code examples on how to use the REST gateway.
Here is the code example for using the Rest gateway for a purchase transaction with a credit card:
// Create a gateway for the PayPal RestGateway
// (routes to GatewayFactory::create)
$gateway = Omnipay::create('RestGateway');
// Initialise the gateway
$gateway->initialize(array(
'clientId' => 'MyPayPalClientId',
'secret' => 'MyPayPalSecret',
'testMode' => true, // Or false when you are ready for live transactions
));
// Create a credit card object
// DO NOT USE THESE CARD VALUES -- substitute your own
// see the documentation in the class header.
$card = new CreditCard(array(
'firstName' => 'Example',
'lastName' => 'User',
'number' => '4111111111111111',
'expiryMonth' => '01',
'expiryYear' => '2020',
'cvv' => '123',
'billingAddress1' => '1 Scrubby Creek Road',
'billingCountry' => 'AU',
'billingCity' => 'Scrubby Creek',
'billingPostcode' => '4999',
'billingState' => 'QLD',
));
// Do a purchase transaction on the gateway
$transaction = $gateway->purchase(array(
'amount' => '10.00',
'currency' => 'AUD',
'description' => 'This is a test purchase transaction.',
'card' => $card,
));
$response = $transaction->send();
if ($response->isSuccessful()) {
echo "Purchase transaction was successful!\n";
$sale_id = $response->getTransactionReference();
echo "Transaction reference = " . $sale_id . "\n";
}

Use Paypal Pro instead of Paypal Express - Omnipay for Laravel

I have a shopping cart that currently is redirecting users to paypal directly to make their payment. I am wanting to allow customers to input their credit card on the site and paypal to process it. I have Paypal Pro account but I am having trouble using it. I am not sure how I can use the Paypal Pro package via Omnipay. In my vendors folder I have a ExpressGateway.php and a Progateway.php but not sure how to call the Progateway.php page. The only way I can see to set it is by using Omnipay::getway('paypal') which I currently do for express. What is the process i need to use in order to use Paypal Pro?
$gateway = Omnipay::gateway('paypal');
if(Auth::user() != NULL && Auth::user()->super_user == 1) {
//sandbox
$gateway->setUsername('#######');
$gateway->setPassword('#######');
$gateway->setSignature('#######');
$gateway->setTestMode('true');
} else {
//production
$gateway->setUsername('#######');
$gateway->setPassword('#######');
$gateway->setSignature('######');
}
$cardInput = array(
'firstName' => $info['first_name_bill'],
'lastName' => $info['last_name_bill'],
'billingAddress1' => $info['street_address_1_bill'],
'billingAddress2' => $info['street_address_2_bill'],
'billingPhone' => $info['phone_bill'],
'billingCity' => $info['city_bill'],
'billingState' => $info['state_bill'],
'billingPostCode' => $info['zip_bill'],
'shippingAddress1' => $info['street_address_1_ship'],
'shippingAddress2' => $info['street_address_2_ship'],
'shippingPhone' => $info['phone_ship'],
'shippingCity' => $info['city_ship'],
'shippingState' => $info['state_ship'],
'shippingPostCode' => $info['zip_ship'],
);
$card = Omnipay::creditCard($cardInput);
$response = Omnipay::purchase(
array(
'cancelUrl' => URL::to('cart'),
'returnUrl' => URL::action('CartController#getSuccessPayment', array('id' =>$invoice->id)),
'amount' => Input::get('total'),
'currency' => 'USD',
'card' => $card,
'description' => '#####'
)
)->send();`
Set the gateway this way:
$gateway = Omnipay::gateway('Paypal_Pro');

Omnipay with Paypal Express

I have an ecommerce website that redirects to a Paypal express checkout using Omnipay. It will correctly redirect the user to Paypal and return with a successful message with payerID and everything. However, it does not actually take any payment and it does not show up on our paypal account as any payment taken. I am not sure if this is a paypal issue or a configuration problem with Omnipay. I would imagine that Paypal handles this part of it but since it's not working (on our old site it works fine but we do not use Omnipay.)
$gateway = Omnipay::gateway('paypal');
//production
$gateway->setUsername('11111111');
$gateway->setPassword('1111111111');
$gateway->setSignature('111111111');
$cardInput = array(
'firstName' => $info['first_name_bill'],
'lastName' => $info['last_name_bill'],
'billingAddress1' => $info['street_address_1_bill'],
'billingAddress2' => $info['street_address_2_bill'],
'billingPhone' => $info['phone_bill'],
'billingCity' => $info['city_bill'],
'billingState' => $info['state_bill'],
'billingPostCode' => $info['zip_bill'],
'shippingAddress1' => $info['street_address_1_ship'],
'shippingAddress2' => $info['street_address_2_ship'],
'shippingPhone' => $info['phone_ship'],
'shippingCity' => $info['city_ship'],
'shippingState' => $info['state_ship'],
'shippingPostCode' => $info['zip_ship'],
);
$card = Omnipay::creditCard($cardInput);
//live
$response = Omnipay::purchase(
array(
'cancelUrl' => 'http://store.site.com/cart/cancel-payment',
'returnUrl' => 'http://store.site.com/cart/successful-payment',
'amount' => Input::get('total'),
'currency' => 'USD',
'card' => $card,
'description' => 'Stuff'
)
)->send();
if ($response->isSuccessful()) {
return Redirect('cart/successful-payment');
} elseif ($response->isRedirect()) {
$response->redirect(); // this will automatically forward the customer
} else {
return Redirect::back()->with('error', 'There was a problem. Please try again.');
}
} else {
return Redirect::to('cart/successful-payment');
}
So basically what this will do is redirect them to Paypal to make a payment then redirect back to our store. That all works fine. They can input their card number and then come back to our store after submitting it. The issue is after it gets return nothing happens through paypal. No orders or payment are exchanged.
In your return function, the function that gets called when this URL is executed: http://store.site.com/cart/successful-payment you need to call completePurchase. Something like this:
$gateway = Omnipay::gateway('paypal');
//production
$gateway->setUsername('11111111');
$gateway->setPassword('1111111111');
$gateway->setSignature('111111111');
$purchaseId = $_GET['PayerID'];
$response = $gateway->completePurchase([
'transactionReference' => $purchaseId
])->send();
// .. check $response here.

Show billing and shipping information in Paypal Express using Omnipay

I am using Laravel with Omnipay for our ecommerce application. We direct the customers to Paypal to make their purchase. We require shipping and billing information prior to placing an order and we would like that information to continue to Paypal to make it easier for them. However, only the first name and last name are crossing over to Paypal correctly. We can also use email with no issues.
public function postPayment() {
//var_dump(Session::get('shipping_info')); die;
$info = Session::get('shipping_info');
$gateway = Omnipay::gateway('paypal');
//sandbox
$gateway->setUsername('xxxx');
$gateway->setPassword('xxxx');
$gateway->setSignature('xxx');
$gateway->setTestMode('true');
//production
// $gateway->setUsername('xxxx');
// $gateway->setPassword('xxxx');
// $gateway->setSignature('xxxx');
$cardInput = array(
'firstName' => $info['first_name_bill'],
'lastName' => $info['last_name_bill'],
'billingAddress1' => $info['street_address_1_bill'],
'billingAddress2' => $info['street_address_2_bill'],
'billingPhone' => $info['phone_bill'],
'billingCity' => $info['city_bill'],
'billingState' => $info['state_bill'],
'billingPostCode' => $info['zip_bill'],
'shippingAddress1' => $info['street_address_1_ship'],
'shippingAddress2' => $info['street_address_2_ship'],
'shippingPhone' => $info['phone_ship'],
'shippingCity' => $info['city_ship'],
'shippingState' => $info['state_ship'],
'shippingPostCode' => $info['zip_ship'],
);
$card = Omnipay::creditCard($cardInput);
// var_dump($card); die;
$response = Omnipay::purchase(
array(
'cancelUrl' => 'http://localhost/public/',
'returnUrl' => 'http://localhost/public/',
'amount' => Input::get('total'),
'currency' => 'USD',
'card' => $card,
'description' => 'Stuff'
)
)->send();
$response->redirect();
}
According to the docs https://github.com/omnipay/omnipay it should work with no issues. dumping the sessions reveals the correct billing and shipping parameters.
It was just needing a cache refresh.

How to use a variable as the amount for recurring payments (Paypal API)

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.

Categories