首页 > 解决方案 > snapchat login kit web:无效授权,无效代码验证器

问题描述

我在我的 PHP 项目中使用 Snapchat 登录工具包网络。我成功连接了用户授权页面。授予授权后,我在我的 redirect_uri 页面中获取代码和状态 GET 变量。我需要一个访问令牌,但是当我继续下一步时,我收到一个错误响应,

1.invalid_grant 2.invalid code_verifier

这是我的登录页面和重定向页面代码:

--登录页面---

<?php

if(isset($_POST['login']))
{

$url="https://accounts.snapchat.com/accounts/oauth2/auth";
$clientId="my_client_id_get_from_snapchat_app_setting";
$client_secret="my_client_secrect_get_from_snapchat_app_setting";
$redirectUri="https://Snapreport.org/Redirect.php";

$method= "GET";

$str = 'arifusingsnapchat'; 
  
$state= base64_encode($str);

 $code_verifier = "arifusingsnapchat225678909fghh8df777634567890";
 $code_verifier_hash = hash("sha256",$code_verifier);

 $code_challenge = base64_encode($code_verifier_hash);



$scopeList= array("https://auth.snapchat.com/oauth2/api/user.display_name",
                   "https://auth.snapchat.com/oauth2/api/user.bitmoji.avatar",
                   "https://auth.snapchat.com/oauth2/api/user.external_id"
);

$scope = implode($scopeList," ");

$stringArr = array(
    "client_id" => $clientId,
    "client_secret" => $client_secret,
    "redirect_uri" => $redirectUri,
    "code_challenge" => $code_challenge,
    "code_challenge_method"=> "S256",
    "response_type" => "code",
    "scope" => $scope,
    "state" => $state );

$query= http_build_query($stringArr, '', '&'); 

$request = $url."?".$query;

header("Location:".$request);

}
 ?>

--redirect_uri 页面--

<?php

if(isset($_GET['code']) && isset($_GET['state']))
{ 
  $code= $_GET['code'];
  $state=$_GET['state'];

  
  $url="https://accounts.snapchat.com/accounts/oauth2/token";
  $clientId="my_client_id_get_from_snapchat_app_setting";
  $client_secret="my_client_secrect_get_from_snapchat_app_setting";
  $redirect_uri="https://Snapreport.org/Redirect.php";

  $header = base64_encode($clientId.":".$client_secret);
 
  $code_verifier = "arifusingsnapchat225678909fghh8df777634567890";
  
  $payloaded_url=$url."?client_id=".$clientId."&client_secret=".$client_secret."&grant_type=authorization_code&redirect_uri=".$redirect_uri."&code=".$code."&code_verifier=".$code_verifier; 

  $ch = curl_init($payloaded_url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_POST, 1);

  curl_setopt($ch, CURLOPT_HTTPHEADER, array(
      'Content-Type' => 'application/json',
       'Authorization'=> 'Basic '.$header
  ));
  // execute!
  $response = curl_exec($ch);

  // close the connection, release resources used
  curl_close($ch);
  
 $res= json_decode($response);
  // do anything you want with your response
 echo "<pre>";
  var_dump($res);

  echo "</pre>";
} 

Snapchat 登录工具包 Web 文档 Snapchat 登录工具包 Web 文档https://kit.snapchat.com/docs/login-kit-web

标签: phpapiauthenticationsnapchat

解决方案


在您的登录页面上:

$code_verifier_hash = urlencode(pack('H*', hash('sha256', $code_verifier)))

您可能还应该使用像这里这样的 B64 安全 url 编码器:

https://github.com/F21/jwt/blob/master/JWT/JWT.php#L120


推荐阅读