【发布时间】:2021-10-08 05:35:29
【问题描述】:
我正在尝试在我的项目中实施 Paypal Sandbox。我在app 文件夹中创建了一个trait:
use GuzzleHttp\Client;
trait ConsumesExternalServices
{
public function makeRequest(
$method,
$requestUrl,
$queryParams = [],
$formParams = [],
$headers = [],
$isJsonRequest=false
) {
$client = new Client([
'base_uri' => $this->baseUri,
]);
if (method_exists($this, 'resolveAuthorization')) {
$this->resolveAuthorization($queryParams, $formParams, $headers);
}
$response = $client->request($method, $requestUrl, [
$isJsonRequest ? 'json' : 'form_params' => $formParams,
'headers' => $headers,
'query' => $queryParams,
]);
$response = $response->getBody()->getContents();
if (method_exists($this, 'decodeResponse')) {
$response = $this->decodeResponse($response);
}
return $response;
}
}
我还创建了 Paypal 服务:
use App\Traits\ConsumesExternalServices;
class PaypalServices
{
use ConsumesExternalServices;
protected $baseUri;
protected $clientId;
protected $clientSecret;
public function __construct()
{
$this->baseUri = config('services.paypal.base_uri');
$this->clientId = config('services.paypal.client_id');
$this->clientSecret = config('services.paypal.client_secret');
}
public function resolveAuthorization(&$queryParams, &$formParams, &$headers)
{
$headers['Authorization']=$this->resolveAccessToken();
}
public function decodeResponse($response)
{
return json_decode($response);
}
public function resolveAccessToken()
{
$credentials = base64_encode("{$this->clientId} : {$this->clientSecret}");
return "Basic {$credentials}";
}
}
我正在尝试将我的沙盒帐户与我的项目集成,但每当我使用 tinker 并尝试发出请求时,我都会收到以下错误:
Psy Shell v0.10.8 (PHP 7.4.15 — cli) by Justin Hileman
>>> $paypal=new App\Services\PaypalServices;
=> App\Services\PaypalServices {#3473}
>>> $paypal->makeRequest('GET','v1/invoicing/invoices');
GuzzleHttp\Exception\ClientException with message 'Client error: `GET https://api-m.sandbox.paypal.com/v1/invoicing/invoices` resulted in a `401 Unauthorized` response:{"error":"invalid_client","error_description":"Client Authentication failed"}
我不知道是什么问题。 Laravel 版本是 8,我使用的是 Paypal Malaysia 帐户。
我在.env文件中提到过:
PAYPAL_BASE_URI=https://api-m.sandbox.paypal.com
PAYPAL_CLIENT_ID=
PAYPAL_CLIENT_SECRET=
在我的config/servies.php 文件中:
'paypal' => [
'base_uri' => env('PAYPAL_BASE_URI'),
'client_id' => env('PAYPAL_CLIENT_ID'),
'client_secret' => env('PAYPAL_CLIENT_SECRET')
],
【问题讨论】:
-
由于凭据错误或未正确发送而失败。你的配置文件是什么样的?
-
@Super_Simon 将编辑并显示我的 config/services.php 文件的样子
-
响应很清楚:"error":"invalid_client".. 和你的
base_uri、client_id和client_secret有关。 . -
@matiaslauriti 这是我想要弄清楚的。我做错了什么我在贝宝结帐时使用了相同的客户ID,它工作正常,但我不知道我在这里做错了什么:(