PayPal异常PayPalInvalidCredentialException:找不到默认用户的凭据

I have implemented PayPal (PHP, Laravel) and there is some issue coming while payment. I am getting the following exception in the live.

PayPal\Exception\PayPalInvalidCredentialException: Credential not found for default user. Please make sure your configuration/APIContext has credential information in /var/www/project/project-files/vendor/paypal/rest-api-sdk-php/lib/PayPal/Core/PayPalCredentialManager.php

I have checked this and other similar problems with the same issue but those didn't helped, i am still missing something. A little help or guidance will be helpful.

The scenario is: Once a user request for Payment, the admin approves it, the payment will be processed.

For this purpose a Laravel Job is created and code for the following Job is:

namespace Test\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use PayPal;
use Test\Models\Transaction;

class ProcessPayout implements ShouldQueue
{

use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

/**
 * @var Transaction
 */
protected $transaction;

/**
 * Create a new job instance.
 *
 * @param Transaction $transaction
 */
public function __construct(Transaction $transaction) {
    $this->transaction = $transaction;
}

/**
 * Execute the job.
 *
 * @return void
 */
public function handle() {
    try {
        \Log::info($this->transaction); // I am getting all the data in this to be processed from Transaction Model

        $response = PayPal::makePayoutEnvironment()
            ->setPayoutEmailSubject($this->transaction->sender_batch_id)
            ->setPayoutItem($this->transaction->receiver, $this->transaction->amount, $this->transaction->sender_item_id)
            ->makePayout();

        if(empty($response)){
            throw new \Exception();
        }

    }catch(\Exception $e){
        \Log::info($e); 
    }
}

}

The PayPal.php is as follows:

namespace Test\PayPal;

use PayPal\Api\Currency;
use PayPal\Api\Payout;
use PayPal\Api\PayoutItem;
use PayPal\Api\PayoutSenderBatchHeader;
use PayPal\Rest\ApiContext;
use ResultPrinter;

class PayPal
{

/**
 * @var ApiContext
 */
protected $context;

/**
 * @var Payout
 */
protected $payout;

/**
 * @var PayoutSenderBatchHeader
 */
protected $senderHeader;

/**
 * PayPal constructor.
 */
public function __construct()
{
    $this->context = app('PayPalContext');
}

/**
 * Create payout environment.
 */
public function makePayoutEnvironment()
{
    $this->payout = new Payout();
    $this->senderHeader = new PayoutSenderBatchHeader();
    return $this;
}

/**
 * Set payout sender email subject.
 *
 * @param      $senderId
 * @param null $subject
 *
 * @return $this
 */
public function setPayoutEmailSubject($senderId, $subject = null)
{
    $this->senderHeader->setSenderBatchId($senderId)
        ->setEmailSubject($subject ?: config('mail.subject_prefix') . 'Payout accepted.');
    $this->payout->setSenderBatchHeader($this->senderHeader);

    return $this;
}

/**
 * Set the payout item with receiver and amount of.
 *
 * @param $receiverEmail
 * @param $amount
 *
 * @param $itemId
 *
 * @return $this
 */
public function setPayoutItem($receiverEmail, $amount, $itemId)
{
    $item = (new PayoutItem())->setRecipientType('Email')
        ->setNote($this->senderHeader->getEmailSubject())
        ->setReceiver($receiverEmail)
        ->setSenderItemId($itemId)
        ->setAmount(new Currency(sprintf('{
                    "value":"%s",
                    "currency":"%s"
                }', $amount, config('currency.fallback'))));

    $this->payout->addItem($item);

    return $this;
}

/**
 * Make payout for recipient.
 *
 * @return bool|\PayPal\Api\PayoutBatch
 */
public function makePayout()
{
    try {
        $output = $this->payout->create(['sync_mode' => false], $this->context);
    } catch (\Exception $ex) {
        \Log::info($ex);
        return false;
    }

    return $output;
}

}

And code for the PayPalServiceProvider is as follows:

namespace Test\Providers;
use Illuminate\Support\ServiceProvider;
use PayPal\Auth\OAuthTokenCredential;
use PayPal\Rest\ApiContext;
use Test\PayPal\PayPal;
class PayPalServiceProvider extends ServiceProvider
{
    public function boot() {

    }
    public function register()
    {
        $this->app->singleton('PayPalContext', function ($app) {

        $config = array('mode' => 'live');

        $apiContext = new ApiContext(
            new OAuthTokenCredential(
                config('services.paypal.client_id'),// ClientID
                config('services.paypal.client_secret')// ClientSecret
            )
        );

        $apiContext->setConfig($config);

        return $apiContext;
    });

    $this->app->singleton('PayPal', function ($app) {
        return new PayPal();
    });
}

/**
 * Get the services provided by the provider.
 *
 * @return array
 */
    public function provides(){
        return [ 'PayPal' ];
    }
}

After some debugging, the PaypalServiceProvider was not returning anything in the constructor of the PayPal.php in live, don't know why. So when i set the credentials and the configuration in the $this->context of Paypal.php, the Credential error isn't coming but now i can see a new error.

Got Http response code 403 when accessing https://api.paypal.com/v1/payments/payouts

name : AUTHORIZATION_ERROR, debug_id : 6dd18f794dd9, message : Authorization erroroccurred

I followed this and its issue with the verification of account and i checked if my account is verified and it is. Any other suggestions to solve this please.

Will you please try with this?

PayPals PHP REST-API-SDK comes with some great samples. Take a look at the bootstrap.php in /vendor/paypal/rest-api-sdk-php/sample/ in line 84. There are some configurations happening, after getting the api context.

$apiContext = new ApiContext(
    new OAuthTokenCredential(
        $clientId,
        $clientSecret
    )
);

// Comment this line out and uncomment the PP_CONFIG_PATH
// 'define' block if you want to use static file
// based configuration

$apiContext->setConfig(
    array(
        'mode' => 'sandbox',
        'log.LogEnabled' => true,
        'log.FileName' => '../PayPal.log',
        'log.LogLevel' => 'DEBUG', // PLEASE USE `INFO` LEVEL FOR LOGGING IN LIVE ENVIRONMENTS
        'cache.enabled' => true,
      implementing \PayPal\Log\PayPalLogFactory
    )
);

同样出现了这个问题 何解啊