Paypal Rest Api devuelve 401 No autorizado cuando intento obtener el token OAuth2 usando php file_get_contents() en localhost con sandbox
$client_id = env('PAYBAL_CLIENT'); $client_secret = env('PAYPAL_SECRET'); $opts = array('http' => array( 'method' => 'POST', "headers" => [ "Content-Type" => "application/x-www-form-urlencoded", "Authorization" => "Basic " . base64_encode("$client_id:$client_secret") ], 'body' => "{'grant_type' : 'client_credentials'}" ) ); $context = stream_context_create($opts); $url = "https://api-m.sandbox.paypal.com/v1/oauth2/token"; $result = file_get_contents($url, false, $context);la misma solicitud funcionó bien conmigo en ajax
$.ajax( { url: "https://api-m.sandbox.paypal.com/v1/oauth2/token", type:"post", headers:{ "Authorization": "Basic 'XXXbase64_encodedXXX'" "Content-Type": "application/x-www-form-urlencoded" }, data:{ "grant_type":"client_credentials" }, success:function (data){ console.log(data); }, complete:function (data,status){ console.log(status); } });
La función ajax está convirtiendo los datos al formato codificado de URL para usted aquí:
"Content-Type": "application/x-www-form-urlencoded" }, data:{ "grant_type":"client_credentials" },El curl de PHP no hace eso (o especialmente cuando le das una cadena en lugar de una matriz/objeto, no hay forma de que pueda adivinar que necesita ser convertido; asumirá que cualquier cadena que pases es la cadena que pretendes publicar)
'body' => "{'grant_type' : 'client_credentials'}" Debe proporcionar una cadena de cuerpo de formulario con codificación URL como lo requiere la llamada a la API: "grant_type=client_credentials"
En lugar de file_get_contents, uso GuzzleHttp y funcionó conmigo, aquí está el código
$client_id = env('PAYBAL_CLIENT'); $client_secret = env('PAYPAL_SECRET'); $client = new \GuzzleHttp\Client(); $response = $client->request('POST', 'https://api-m.sandbox.paypal.com/v1/oauth2/token', [ 'headers' => [ 'Content-type' => 'application/x-www-form-urlencoded', 'Authorization' => "Basic " . base64_encode("$client_id:$client_secret") ], 'body' => 'grant_type=client_credentials' ]);