Omnipay Autentication error inside laravel - paypal

I'm using Omnipay Paypal Rest api for Laravel and getting this:
"Authentication failed due to invalid authentication credentials or a missing Authorization header."
here is my code :
public function PayWithPaypal(Request $request)
{
// Initialize the Omnipay PayPal_Rest gateway
$gateway = Omnipay::create('PayPal_Rest');
$gateway->setClientId(env('PAYPAL_SANDBOX_CLIENT_ID'));
$gateway->setSecret(env('PAYPAL_SANDBOX_CLIENT_SECRET'));
$gateway->setTestMode(true);
// Prepare the payment request
$request = $gateway->purchase([
'amount' => 1,
'returnUrl' => route('payment.success'),
'cancelUrl' => route('payment.cancel'),
]);
// Send the payment request
$response = $request->send();
// Process the payment response
if ($response->isRedirect()) {
// Redirect the customer to the payment gateway
$response->redirect();
} else {
// Payment failed, display an error message to the customer
Log::alert($response->getMessage());
return redirect()->route('payment.error')->with('error', $response->getMessage());
}
}
Any way to solve this error ?

Related

Paypal sandbox post error 401 (Unauthorized)

enter image description hereI have been following a tutorial for a paypal sandbox using react-paypal-express-checkout and have followed it exactly, but when I try to open the paypal window it closes instantly and throws this error.
Photo:Photo Here
Text:
http.js:147 POST https://www.sandbox.paypal.com/v1/payment-experience/web-profiles 401 (Unauthorized)
types.js:121 Uncaught Error: Request to post https://www.sandbox.paypal.com/v1/payment-experience/web-profiles failed with 401 error. Correlation id: bfca9a9c3fdfc
{
"name": "AUTHENTICATION_FAILURE",
"debug_id": "bfca9a9c3fdfc",
"message": "Authentication failed due to invalid authentication credentials or a missing Authorization header",
"information_link": "https://developer.paypal.com/docs/api/payment-experience/#errors",
"details": []
}
at XMLHttpRequest.xhrLoad (http.js:114)
at Object._RECEIVE_MESSAGE_TYPE.<computed> [as postrobot_message_response] (types.js:121)
at receiveMessage (index.js:114)
at messageListener (index.js:140)
at Object._RECEIVE_MESSAGE_TYPE.<computed> [as postrobot_message_response] (types.js:121)
at receiveMessage (index.js:114)
at messageListener (index.js:140)
_RECEIVE_MESSAGE_TYPE.<computed> # types.js:121
receiveMessage # index.js:114
messageListener # index.js:140
setTimeout (async)
dispatchPossiblyUnhandledError # exceptions.js:16
(anonymous) # promise.js:122
setTimeout (async)
reject # promise.js:120
dispatch # promise.js:179
reject # promise.js:127
dispatch # promise.js:179
reject # promise.js:127
dispatch # promise.js:186
reject # promise.js:127
(anonymous) # promise.js:157
dispatch # promise.js:184
reject # promise.js:127
(anonymous) # promise.js:51
respond # client.js:147
_RECEIVE_MESSAGE_TYPE.<computed> # types.js:126
receiveMessage # index.js:114
messageListener # index.js:140
serialize.js:175 Uncaught Error: Error: Request to post https://www.sandbox.paypal.com/v1/payment-experience/web-profiles failed with 401 error. Correlation id: bfca9a9c3fdfc
{
"name": "AUTHENTICATION_FAILURE",
"debug_id": "bfca9a9c3fdfc",
"message": "Authentication failed due to invalid authentication credentials or a missing Authorization header",
"information_link": "https://developer.paypal.com/docs/api/payment-experience/#errors",
"details": []
}
at XMLHttpRequest.xhrLoad (http.js:114)
at Object._RECEIVE_MESSAGE_TYPE.<computed> [as postrobot_message_response] (types.js:121)
at receiveMessage (index.js:114)
at messageListener (index.js:140)
at Object._RECEIVE_MESSAGE_TYPE.<computed> [as postrobot_message_response] (types.js:121)
at receiveMessage (index.js:114)
at messageListener (index.js:140)
at deserializeError (serialize.js:175)
at serialize.js:212
at util.js:140
at eachArray (util.js:102)
at each (util.js:116)
at replaceObject (util.js:138)
at util.js:147
at eachObject (util.js:109)
at each (util.js:118)
at replaceObject (util.js:138)
Heres the page for my button and all the tutorial guy changes is the sandbox id which I did:
import React from 'react';
import PaypalExpressBtn from 'react-paypal-express-checkout';
export default class MyApp extends React.Component {
render() {
const onSuccess = (payment) => {
// Congratulation, it came here means everything's fine!
console.log("The payment was succeeded!", payment);
// You can bind the "payment" object's value to your state or props or whatever here, please see below for sample returned data
}
const onCancel = (data) => {
// User pressed "cancel" or close Paypal's popup!
console.log('The payment was cancelled!', data);
// You can bind the "data" object's value to your state or props or whatever here, please see below for sample returned data
}
const onError = (err) => {
// The main Paypal's script cannot be loaded or somethings block the loading of that script!
console.log("Error!", err);
// Because the Paypal's main script is loaded asynchronously from "https://www.paypalobjects.com/api/checkout.js"
// => sometimes it may take about 0.5 second for everything to get set, or for the button to appear
}
let env = 'sandbox'; // you can set here to 'production' for production
let currency = 'USD'; // or you can set this value from your props or state
let total = 1; // same as above, this is the total amount (based on currency) to be paid by using Paypal express checkout
// Document on Paypal's currency code: https://developer.paypal.com/docs/classic/api/currency_codes/
const client = {
sandbox: 'ASloDPNYZO9LtigzQd58tcYQHuORCH3TlvPS-LWMdwzIWiEiefonUQE7KmWCE-WkaEaiiJb54RSNcrLE',
production: 'YOUR-PRODUCTION-APP-ID',
}
// In order to get production's app-ID, you will have to send your app to Paypal for approval first
// For sandbox app-ID (after logging into your developer account, please locate the "REST API apps" section, click "Create App"):
// => https://developer.paypal.com/docs/classic/lifecycle/sb_credentials/
// For production app-ID:
// => https://developer.paypal.com/docs/classic/lifecycle/goingLive/
// NB. You can also have many Paypal express checkout buttons on page, just pass in the correct amount and they will work!
return (
<PaypalExpressBtn env={env} client={client} currency={currency} total={total} onError={onError} onSuccess={onSuccess} onCancel={onCancel} />
);
}
}
The react-paypal-express-checkout repository does not reference v1/payment-experience/web-profiles , so I am not sure where your error is actually coming from
The v1/payment-experience/web-profiles API requires a valid ClientId and a Secret for authentication.

Client Authentication failed in Paypal sandbox mode

I'm trying to add Paypal's smart buttons to my website.
I followed the tutorial here:
https://developer.paypal.com/docs/checkout/integrate/
Anyway, this is the code in my payment.html file:
<!-- End of Body content -->
</body>
<script src="https://www.paypal.com/sdk/js?client-id=sb&currency=ILS&locale=he_IL&vault=true"></script>
<script>
paypal.Buttons({
createOrder: function(data, actions) {
return actions.order.create({
purchase_units: [{
amount: {
value: '49.99'
}
}]
});
},
onApprove: function(data, actions) {
return actions.order.capture().then(function(details) {
alert('Transaction completed by ' + details.payer.name.given_name);
// Call your server to save the transaction
return fetch('../paypal.php', {
method: 'post',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({
orderID: data.orderID
})
});
});
}
}).render('#pay');
</script>
This is my paypal.php file:
<?php
namespace Sample;
require __DIR__ . '/vendor/autoload.php';
//1. Import the PayPal SDK client that was created in `Set up Server-Side SDK`.
use Sample\PayPalClient;
use PayPalCheckoutSdk\Orders\OrdersGetRequest;
class GetOrder
{
// 2. Set up your server to receive a call from the client
/**
*You can use this function to retrieve an order by passing order ID as an argument.
*/
public static function getOrder($orderId)
{
// 3. Call PayPal to get the transaction details
$client = PayPalClient::client();
$response = $client->execute(new OrdersGetRequest($orderId));
/**
*Enable the following line to print complete response as JSON.
*/
// echo json_encode($response->result);
print "Status Code: {$response->statusCode}\n";
print "Status: {$response->result->status}\n";
print "Order ID: {$response->result->id}\n";
print "Intent: {$response->result->intent}\n";
print "Links:\n";
foreach($response->result->links as $link)
{
print "\t{$link->rel}: {$link->href}\tCall Type: {$link->method}\n";
}
// 4. Save the transaction in your database. Implement logic to save transaction to your database for future reference.
print "Gross Amount: {$response->result->purchase_units[0]->amount->currency_code} {$response->result->purchase_units[0]->amount->value}\n";
// To print the whole response body, uncomment the following line
// echo json_encode($response->result, JSON_PRETTY_PRINT);
}
}
if (!count(debug_backtrace()))
{
$request_body = file_get_contents('php://input');
$json = json_decode($request_body,true);
$id=$json["orderID"];
GetOrder::getOrder($id, true);
}
and this is my paypal_loader.php file:
<?php
namespace Sample;
use PayPalCheckoutSdk\Core\PayPalHttpClient;
use PayPalCheckoutSdk\Core\SandboxEnvironment;
ini_set('error_reporting', E_ALL); // or error_reporting(E_ALL);
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
class PayPalClient
{
/**
* Returns PayPal HTTP client instance with environment that has access
* credentials context. Use this instance to invoke PayPal APIs, provided the
* credentials have access.
*/
public static function client()
{
return new PayPalHttpClient(self::environment());
}
/**
* Set up and return PayPal PHP SDK environment with PayPal access credentials.
* This sample uses SandboxEnvironment. In production, use LiveEnvironment.
*/
public static function environment()
{
$clientId = getenv("CLIENT_ID") ?: "myclientidhere";
$clientSecret = getenv("CLIENT_SECRET") ?: "mysecrethere";
return new SandboxEnvironment($clientId, $clientSecret);
}
}
I get the javascript alert ("transaction completed by....") on the payment.html after using the sandbox account to pay and the payment is actually being completed the problem is when I try to verify it on the server side the response I'm getting from the paypal.php is:
<br />
<b>Fatal error</b>: Uncaught BraintreeHttp\HttpException: {"error":"invalid_client","error_description":"Client Authentication failed"} in C:\xampp\htdocs\firstGear\schoolcontrol\vendor\braintree\braintreehttp\lib\BraintreeHttp\HttpClient.php:185
Stack trace:
#0 C:\xampp\htdocs\firstGear\schoolcontrol\vendor\braintree\braintreehttp\lib\BraintreeHttp\HttpClient.php(97): BraintreeHttp\HttpClient->parseResponse(Object(BraintreeHttp\Curl))
#1 C:\xampp\htdocs\firstGear\schoolcontrol\vendor\paypal\paypal-checkout-sdk\lib\PayPalCheckoutSdk\Core\AuthorizationInjector.php(37): BraintreeHttp\HttpClient->execute(Object(PayPalCheckoutSdk\Core\AccessTokenRequest))
#2 C:\xampp\htdocs\firstGear\schoolcontrol\vendor\paypal\paypal-checkout-sdk\lib\PayPalCheckoutSdk\Core\AuthorizationInjector.php(29): PayPalCheckoutSdk\Core\AuthorizationInjector->fetchAccessToken()
#3 C:\xampp\htdocs\firstGear\schoolcontrol\vendor\braintree\braintreehttp\lib\BraintreeHttp\HttpClient.php(64): PayPalCheckoutSdk\Core\AuthorizationInjector->inject(Object(PayPalChecko in <b>C:\xampp\htdocs\firstGear\schoolcontrol\vendor\braintree\braintreehttp\lib\BraintreeHttp\HttpClient.php</b> on line <b>185</b><br />
I tripled check my client_id and client_secret, and can't figure out for hours now where's the problem in the code as it's pretty much copy pasted from paypal's website.
Would appreciate your help, thanks in advance.

Cannot login through Facebook in Laravel 5.1

I am trying to login with facebook using Laravel 5.1.
I am following each steps mention in laravel documentation.
http://laravel.com/docs/5.1/authentication#social-authentication.
But, When i login through facebook then it will redirect to my normal login page.
In sort Session is store in facebook login.
This is a Code that is written by me.
Router.php
Route::get('auth/facebook','Auth\AuthController#redirectToProvider');
Route::get('auth/facebook/callback','Auth\AuthController#handleProviderCallback');
AuthController.php
public function redirectToProvider()
{
return Socialite::driver('facebook')
->scopes(['email', 'public_profile'])
->redirect();
}
public function handleProviderCallback()
{
$user = Socialite::driver('github')->user();
$user = Socialite::driver('github')->user();
// OAuth Two Providers
$token = $user->token;
// OAuth One Providers
$token = $user->token;
$tokenSecret = $user->tokenSecret;
// All Providers
$user->getId();
$user->getNickname();
$user->getName();
$user->getEmail();
$user->getAvatar();
}
Services.php
'facebook' => [
'client_id' => '1625567400000000',
'client_secret' => 'secret',
'redirect' => 'http://localhost:8000/',
],
When i type localhost/8000/auth/facebook it will redirect me to facebook and ask permission for public_profile, email etc.
And it will redirect back to localhost/auth/login.
And when i type localhost:8000/auth/facebook/callback in URL, it will through error like this;
ClientException in Middleware.php line 69:
Client error: 404
For your case, I guest you are using middleware to check if the user is already logged in. And this might the problem that you get redirect to localhost/auth/login
I hope following code could be useful to you
public function handleProviderCallback()
{
//retrieve user's information from facebook
$socUser = Socialite::driver('facebook')->user();
//check user already exists in db
$user = \App\User::where('email', $socUser->getEmail())->first();
if($user) {
// if exist, log user into your application
// and redirect to any path you want
\Auth::login($user);
return redirect()->route('user.index');
}
//if not exist, create new user,
// log user into your application
// and resirect to any path you want
$user = new \App\User ;
$user->email = $socUser->getEmail();
// ...
// ...
// ...
$user->save();
\Auth::login($user); // login user
return redirect()->route('user.index'); // redirect
}
note: I did not test my code but you should get some idea
for more information: http://laravel.com/docs/5.1/authentication
and as #mimo mention,
Your redirect url in the Services.php file has to be
localhost:8000/auth/facebook/callback
Your redirect url in the Services.php file has to be
localhost:8000/auth/facebook/callback

Successful Adaptive Payments Pay Request via paypal

I have a pay request via paypal sandbox. When I execute the PHP, I get a success response. However, I can't follow the transaction in the sandbox portal anywhere.
I'm using my API credentials from the sandbox (Which are working). Here's the response I'm getting
object(stdClass)#6 (3) { ["responseEnvelope"]=> object(stdClass)#7 (4) { ["timestamp"]=> string(29) "2013-04-02T11:56:35.221-07:00" ["ack"]=> string(7) "Success" ["correlationId"]=> string(13) "30317d69b575d" ["build"]=> string(7) "5563463" } ["payKey"]=> string(20) "AP-8VN625716X0611726" ["paymentExecStatus"]=> string(7) "CREATED" }
Here's the request. I've changed the email but it is set to an email that I have a sandbox account setup for.
object(PayRequest)#4 (7) { ["requestEnvelope"]=> object(RequestEnvelope)#1 (2) { ["detailLevel"]=> NULL ["errorLanguage"]=> NULL } ["actionType"]=> string(3) "PAY" ["cancelUrl"]=> string(19) "http://www.ebay.com" ["currencyCode"]=> string(3) "USD" ["memo"]=> string(10) "simple pay" ["receiverList"]=> object(ReceiverList)#2 (1) { ["receiver"]=> object(Receiver)#3 (2) { ["amount"]=> string(3) "3.0" ["email"]=> string(17) "xxx#gmail.com" } } ["returnUrl"]=> string(19) "http://www.ebay.com" }
After getting a successful response with the PayKey, you would redirect the customer to:
https://www.sandbox.paypal.com/webscr?cmd=_ap-payment&paykey=VALUE
Where VALUE is the PayKey you received in the API response.
Have you gone to this URL and continued the checkout with a Personal sandbox account?

PayPal Payments Advanced + PayFlow Link

I keep getting the following error when trying to submit a sandbox payment through my PayFlow Gateway:
Error: There was a problem processing your request. Please press the
Back button of your browser and then refresh the page. If you continue
to have an issue, please contact us.
I'm using the following code to generate my PayFlow Gateway, but I just can't get it to work.
/* PayPal Payments Advanced */
$PF_USER = 'my_user';
$PF_VENDOR = 'my_vendor';
$PF_PARTNER = 'PayPal';
$PF_PWD = 'my_pass';
$PF_MODE = 'TEST';
$PF_HOST_ADDR = 'https://pilot-payflowpro.paypal.com'; // TEST mode
// $PF_HOST_ADDR = 'https://payflowpro.paypal.com' // LIVE mode
$secureTokenId = uniqid('',true);
$postData = "USER=".$PF_USER
."&VENDOR=".$PF_VENDOR
."&PARTNER=".$PF_PARTNER
."&PWD=".$PF_PWD
."&SECURETOKENID=".$secureTokenId
."&CREATESECURETOKEN=Y"
."&TRXTYPE=S"
."&AMT=1.00"
."&BILLTOFIRSTNAME=".$first_name
."&BILLTOLASTNAME=".$last_name
."&BILLTOSTREET=".$address
."&BILLTOCITY=".$city
."&BILLTOSTATE=".$state
."&BILLTOZIP=".$zip
."&BILLTOCOUNTRY=".$country
."&SHIPTOFIRSTNAME=".$first_name
."&SHIPTOLASTNAME=".$last_name
."&SHIPTOSTREET=".$address
."&SHIPTOCITY=".$city
."&SHIPTOSTATE=".$state
."&SHIPTOZIP=".$zip
."&SHIPTTOCOUNTRY=".$country
."&EMAIL=".$email
."&PHONENUM=".$phone;
/* Initialize and Setup Request */
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$PF_HOST_ADDR);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_POST,true);
/* Ready the postData to send */
curl_setopt($ch,CURLOPT_POSTFIELDS,$postData);
/* Send the data to PayPal and assign response */
$resp = curl_exec($ch);
/* Confirm response and handle */
if(!$resp){
$error = '<p>There was an error processing your order.</p>';
}
/* Parse and assign to array */
parse_str($resp,$arr);
if($arr['RESULT'] != 0) {
// handle error
die($arr['RESULT']);
$error = '<p>There was an error processing your order. '.$arr['RESULT'].'</p>';
}
echo '<iframe src="https://payflowlink.paypal.com?mode='.$PF_MODE.'&SECURETOKEN='.$arr['SECURETOKEN'].'&SECURETOKENID='.$secureTokenId.'" width="550" height="565" scrolling="no" frameborder="0" border="0" allowtransparency="true"></iframe>';
Your help is appreciated!
I had to explicitly set my Firefox privacy settings to "Allow" third-party cookies. Doing this made the error message go away. I didn't have this problem on Safari.