Laravel paypal checkout перестает работать если входить в систему через Socialite

mstdmstd

Новичок
Всем привет!
Сделал paypal checkout и он нормально работает если в систему входить через login форму(стандартный auth)

Но если входить в систему через Socialite (тестирую с аккаунтами Facebook, Google ) то получаю ошибку :

Credential not found for default user. Please make sure your configuration/APIContext has credential information

PHP:
public function redirectToProvider($provider_name)
{
if ( $provider_name == 'facebook' ) {
return Socialite::driver('facebook')->scopes([
"publish_actions, manage_pages", "publish_pages"])->redirect();
}
return Socialite::driver($provider_name)->redirect();
}

public function handleSocialiteProviderCallback($provider_name)
{
$settingsArray = Settings::getSettingsList(['site_name']);
$site_name = !empty($settingsArray['site_name']) ? $settingsArray['site_name'] : '';
$site_home_url = \URL::to('/');

$provider_name= (string)$provider_name;
$is_debug= true;
try {

$socialiteUser = Socialite::driver($provider_name)->user();

$loggedUser = User::where('provider_id', $socialiteUser->id)->first();

if ($loggedUser !== null ) { // There is already user is system - just login under it's credentials
Auth::login($loggedUser, true);
\Event::dispatch(new backendSuccessOnLoginEvent($loggedUser));
return redirect()->route('home');
} // if ($loggedUser) { // There is already user is system - just login under it's credentials
...
И в модуле оплаты app/Paypal/ExecutePayment.php :

PHP:
<?php
namespace App\Paypal;
use Auth;
use App\Http\Traits\funcsTrait;
use PayPal\Api\Payment;
use PayPal\Api\PaymentExecution;

class ExecutePayment extends PaypalConnection
{
use funcsTrait;
private $payment;
public function create() {

$is_debug= false;
if ($is_debug) {
echo '<pre>paymentId::' . print_r(request('paymentId'), true) . '</pre>';
}

$loggedUser= Auth::user();
$this->debToFile(print_r( ( !empty($loggedUser->id) ? $loggedUser->id : '') , true), ' GetThePayment -0SA $loggedUser->id::');

$this->payment = $this->GetThePayment();
$this->debToFile - это вывод в отладочный файл и он отображает что $loggedUser->id == null

И файл выше наследуется от app/Paypal/PaypalConnection.php :
PHP:
<?php


namespace App\Paypal;

use App\Http\Traits\funcsTrait;
use Auth;


class PaypalConnection
{
use funcsTrait;

protected $apiContext;
private $loggedUser;

public function __construct($loggedUser)
{

if ( !Auth::check() ) {
return redirect()->route('home-msg', [])->with([
'text' => 'You need to login into the system !',
'type' => 'danger',
'action' => 'show-login'
]);
}
$this->loggedUser= $loggedUser;
$this->debToFile(print_r($this->loggedUser->id, true), ' PaypalConnection -0A $this->loggedUser->id::');// ЭТА СТРОКА ВЫВОДИТ ТЕКУЩИЙ $this->loggedUser->id


$this->debToFile(print_r(config('services.paypal'), true), " PaypalConnection -0A config('services.paypal.id')::"); // ВЫВОДИТ ПРАВИЛЬНЫЕ ПАРАМЕТРЫ PAYPAL-конфигурации

$this->apiContext = new \PayPal\Rest\ApiContext(
new \PayPal\Auth\OAuthTokenCredential(
config('services.paypal.id'),
config('services.paypal.secret')
)
);

// ПОХОЖЕ СТРОКА ВЫШЕ КАКИМ-ТО ОБРАЗОМ ВЫПОЛНЯЕТ ЛОГ ОУТ ТЕКУЩЕГО ЮЗЕРА - после ручного возврата в программу и вижу что был выполнен логаут

}
}

ExecutePayment - вызывается из контролла app/Http/Controllers/PaymentController.php :


PHP:
<?php

namespace App\Http\Controllers;

use Auth;
use DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;

use App\Settings;
use App\User;
use App\Http\Traits\funcsTrait;
use Spipu\Html2Pdf\Html2Pdf;
use App\library\CheckValueType;
use App\Paypal\CreatePayment;
use App\Paypal\ExecutePayment;
use App\Paypal\SubscriptionPlan;
use App\Payment;
use App\PaymentItem;

use Spatie\Browsershot\Browsershot;


class PaymentController extends MyAppController
{
use funcsTrait;


private $loggedUser;
public function __construct()
{
}

public function paypal_payment()
{
$request = request();
$requestData = $request->all();

$this->loggedUser = Auth::user();

if ( empty($this->loggedUser->first_name) or
empty($this->loggedUser->last_name or
empty($this->loggedUser->address_line1) or
empty($this->loggedUser->address_city) or
empty($this->loggedUser->address_state) or
empty($this->loggedUser->address_postal_code) or
empty($this->loggedUser->address_country_code) or
empty($this->loggedUser->shipping_address_line1) or
empty($this->loggedUser->shipping_address_city) or
empty($this->loggedUser->shipping_address_state) or
empty($this->loggedUser->shipping_address_postal_code) or
empty($this->loggedUser->shipping_address_country_code)
) ) {

return redirect()->route('home-msg', [])->with([
'text' => 'To make payment fill your profile, including First name, Last name, Address, Shipping address !',
'type' => 'danger',
'action' => 'show-profile'
]);
}
$this->loggedUser = Auth::user();

$payment= new CreatePayment($this->loggedUser);
return $payment->Create($requestData);

}

public function paypal_payment_execute()
{
echo '<pre>paypal_payment_execute::' . print_r(-1, true) . '</pre>';
$this->loggedUser = Auth::user();

$this->debToFile(print_r( ( !empty($this->loggedUser->id) ? $this->loggedUser->id : '' ), true) , ' paypal_payment_execute -000 $this->loggedUser->id::');

$newPayment= new ExecutePayment($this->loggedUser);
try {
$newPaymentResult= $newPayment->create();
} catch (PayPal\Exception\PPConnectionException $pce) {
echo '<pre>Error Block # 1</pre>';
var_dump("-1:" . json_decode($pce->getData()));
exit(1);
} catch (PayPal\Exception\PayPalConnectionException $pce) {
echo '<pre>Error Block # 2</pre>';
var_dump("-2:" . json_decode($pce->getData()));
exit(1);
} catch (Exception $pce) {
echo '<pre>Error Block # 3</pre>';
var_dump("-3:" . json_decode($pce->getData()));
exit(1);

}

if ( $newPaymentResult->state != 'approved' ) { // payment was successful
return redirect()->route('home-msg', [])->with([
'text' => 'Your payment was successfully completed !',
'type' => 'danger',
'action' => ''
]);
}

$newAppayment= new \App\Payment();
$newAppayment->user_id= $this->loggedUser->id;
$newAppayment->status= 'C';
$newAppayment->payment_type= 'P';
$newAppayment->payment_status= $newPaymentResult->state;
$newAppayment->payment_description= $newPaymentResult->transactions[0]->description;
$newAppayment->invoice_number= $newPaymentResult->transactions[0]->invoice_number;

$newAppayment->payer_id= $newPaymentResult->payer->payer_info->payer_id;
$newAppayment->payer_recipient_name= $newPaymentResult->payer->payer_info->recipient_name;

$newAppayment->payer_email= $newPaymentResult->payer->payer_info->email;
$newAppayment->payer_first_name= $newPaymentResult->payer->payer_info->first_name;
$newAppayment->payer_last_name= $newPaymentResult->payer->payer_info->last_name;
$newAppayment->payer_middle_name= $newPaymentResult->payer->payer_info->middle_name;

$newAppayment->currency= $newPaymentResult->transactions[0]->amount->currency;
$newAppayment->total= $newPaymentResult->transactions[0]->amount->total;
$newAppayment->subtotal= $newPaymentResult->transactions[0]->amount->details->subtotal;
$newAppayment->tax= $newPaymentResult->transactions[0]->amount->details->tax;
$newAppayment->shipping= $newPaymentResult->transactions[0]->amount->details->shipping;


$newAppayment->payer_shipping_address= $newPaymentResult->payer->payer_info->shipping_address->line1;
$newAppayment->payer_recipient_name= $newPaymentResult->payer->payer_info->shipping_address->recipient_name;
$newAppayment->payer_city= $newPaymentResult->payer->payer_info->shipping_address->city;
$newAppayment->payer_state= $newPaymentResult->payer->payer_info->shipping_address->state;
$newAppayment->payer_postal_code= $newPaymentResult->payer->payer_info->shipping_address->postal_code;
$newAppayment->payer_country_code= $newPaymentResult->payer->payer_info->shipping_address->country_code;
$newAppayment->payer_business_name= $newPaymentResult->payer->payer_info->business_name;

$itemsList= $newPaymentResult->transactions[0]->item_list;

DB::beginTransaction();
try {
$newAppayment->save();

foreach( $itemsList->items as $next_key=>$nextItem ) {
$newPaymentItem= new PaymentItem();
$newPaymentItem->payment_id= $newAppayment->id;
$newPaymentItem->item_type= 'D';
$newPaymentItem->quantity= $nextItem->quantity;
$newPaymentItem->item_id= $nextItem->sku;
$newPaymentItem->price= $nextItem->price;
$newPaymentItem->save();
}

DB::commit();
} catch (\Exception $e) {
DB::rollback();
$this->setFlashMessage($e->getMessage(), 'danger');

echo '<pre>$e->getMessage()::'.print_r($e->getMessage(),true).'</pre>';
die("-1 EOOR");
return Redirect
::back()
->withErrors([$e->getMessage()])
;
}
return redirect()->route('home-msg', [])->with([
'text' => 'Your payment was successfully completed !',
'type' => 'success',
'action' => ''
]);

}

public function paypal_payment_cancel()
{
echo '<pre>paypal_payment_cancel::' . print_r(-1, true) . '</pre>';
die("-1 XXZ paypal_payment_cancel app/Http/Controllers/PaymentController.php");
}


}
Как я писал в начале если войти в систему через login форму(стандартный auth) - ошибки нет.

Почему ошибка и как ее исправить ?

при логине в handleSocialiteProviderCallback я использовал
PHP:
// Login and "remember" the given user...
Auth::login($user, true);
Или вызова этой функции недостаточно ?

Спасибо !
 

mstdmstd

Новичок
Следующая мысль это проверить 2х юзеров по полям : https://prnt.sc/p10ry9
Для юзера созданного в facebook(id=42) поле password было пустым - я его скопировал из id=6 -
залогинился из facebook-а заново - но та же ошибка.
остальные поля : https://prnt.sc/p10tc9, https://prnt.sc/p10tok, https://prnt.sc/p10tsh
Я заполнил address, shipping_address поля при логине юзера из facebook-а. Если эти поля пустые - то выводит paypal ошибку.
я там сделал проверку.
То есть вроде все поля заполнены одинаково - и каким образом и почему теряется логин - непонятно...
 

mstdmstd

Новичок
Кажется нашел причину в том что у меня в приложении были переходы
Код:
https://mysite.com
https://www.mysite.com
и в .htaccess я писал :
Код:
RewriteCond %{HTTPS} !=on
RewriteRule ^.*$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
в .env :
Код:
APP_URL=https://mysite.com
И при текущем урле с “www.” на урл без него текущий юзер терялся ... такое возможно?
И вообще нужны ли “www.” в урле сайта ?
 
Сверху