API接口文档: 身份验证和授权 (mercadolibre.com.mx) https://developers.mercadolibre.com.mx/es_ar/autenticacion-y-autorizacion/
/** * 生成授权链接 * @param string $redirect_uri * @return string */ public function getAuthUrl($redirect_uri,$app_id) { $this->redirect_uri = $redirect_uri; $randomn = $this->generateRandomString(48); $appmodel = new MercadolibreAPP(); $appmodel->updateAll(['code_verifier'=>$randomn],"id=".$app_id);//产生的随机数记录到数据库 $encoded = base64_encode(hash('sha256', $randomn, true));//code_verifier经过sha256 $code_challenge = strtr(rtrim($encoded, '='), '+/', '-_');//整理 得到 code_challenge $params = array("client_id" => $this->client_id, "response_type" => "code", "redirect_uri" => $redirect_uri,'code_challenge'=>$code_challenge,'code_challenge_method'=>'S256'); if(in_array($this->client_id,[8274783443247575,8149149353703108,2401922632679187,6739263324786978,878999950093151,2621145909128904,4224821929868485,4367955135326677])){ //本土账号测试 return 'https://auth.mercadolibre.com.mx/authorization?'.http_build_query($params); } return 'https://global-selling.mercadolibre.com/authorization?'.http_build_query($params); // return $this->request_url."/merchant/authorization?".http_build_query($params); } //生成随机数 public function generateRandomString($length = 48) { $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $randomString = ''; for ($i = 0; $i < $length; $i++) { $randomString .= $characters[rand(0, strlen($characters) - 1)]; } return $randomString;//随机字符串 }
上述会得到授权的链接 例如:
https://auth.mercadolibre.com.mx/authorization?client_id=4367955135326677&response_type=code&redirect_uri=https%3A%2F%2Fpublish.delaman168.com%2Findex.php%2Fservices%2Fmercadolibre%2Fmercadolibreauthorize%2Faccept%2Fstate%2F61&code_challenge=Xgemq5fLBSsZAe3dl2KteKYPg_AJja_0rrcGxNbbH_g&code_challenge_method=S256
里面多了两个参数 code_challenge:随机数(code_verifier)进过 sha256 加密的参数
根据返回的code得到token:
public function authorize($code, $redirect_uri,$account_id) { if($redirect_uri) $this->redirect_uri = $redirect_uri; $body = array( "grant_type" => "authorization_code", "client_id" => $this->client_id, "client_secret" => $this->client_secret, "code" => $code, "redirect_uri" => $this->redirect_uri.'/state/'.$account_id, 'code_verifier' =>$this->code_verifier //这里是生成授权链接的时候产生的随机数 ); $opts = array( CURLOPT_POST => true, CURLOPT_POSTFIELDS => $body ); $request = $this->execute(self::$OAUTH_URL, $opts); if($request["httpCode"] == 200) { $this->access_token = $request["body"]->access_token; if($request["body"]->refresh_token) $this->refresh_token = $request["body"]->refresh_token; return $request; } else { return $request; } }
标签:redirect,code,challenge,mercadolibre,request,uri,PKCE,美卡多,id From: https://www.cnblogs.com/xiangshihua/p/17129953.html