PHP CURL Authorization: Basic 获取token

PHP CURL Authorization: Basic 获取token_第1张图片

需要填写账号密码,在CURL中可以用base64_encode() 拼接起来放在header里面

$url 接口地址  $port 端口 $name 账号 $pwd 密码

public function get_token($url,$port=9999,$name='xxxx',$pwd='xxxx'){
        $curl = curl_init();
        $header = array(
            "Authorization: Basic ".base64_encode("$name:$pwd"),  //添加头,在name和pwd处填写对应账号密码
        );
        $data = array('grant_type' => 'client_credentials');

        curl_setopt($curl, CURLOPT_PORT, $port);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);

        $response = curl_exec($curl);
        $err = curl_error($curl);

        curl_close($curl);
        unset($curl);

        if ($err) {
          return "cURL Error #:" . $err;
        } else {
            $token = json_decode($response,true);
          return $token['access_token'];
        }

    }

自己Mark一下...

你可能感兴趣的:(CRUL)