后端代码
/**
* 抖音授权 获取openid
* @param Request $request
* @return Json*/
public function code2Session(Request $request): Json
{$param = $request->param();$config = config('douyinconfig.douyin');$arr = ['appid' => $config['appid'], //抖音appid'secret' => $config['secret'], //抖音secret'code' => $param['code'], //前台获取的code'anonymous_code' => '',];$url = 'https://developer.toutiao.com/api/apps/v2/jscode2session'; //抖音接口地址//获取信息$rea = $this->getJson($url, $arr);$res = json_decode($rea, true);return api_success($res['data']);
}
/**
* 抖音接口$rea 返回值
/
{
“err_no”: 0,
“err_tips”: “success”,
“data”: {
“session_key”: "hZy6t19VPjFqm*******",
“openid”: “V3WvSshYq9******”,
“anonymous_openid”: “”,
“unionid”: “f7510d9ab***********”
}
}
前端可根据openid session_key 获取抖音方用户名、头像、性别等信息
//curl请求 调用抖音接口protected function getJson($url, $data, $ssl = true){//curl完成$curl = curl_init();$data = json_encode($data);//设置curl选项curl_setopt($curl, CURLOPT_URL, $url); //URL$user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '
Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0 FirePHP/0.7.4';curl_setopt($curl, CURLOPT_USERAGENT, $user_agent); //user_agent,请求代理信息curl_setopt($curl, CURLOPT_AUTOREFERER, true); //referer头,请求来源curl_setopt($curl, CURLOPT_TIMEOUT, 30); //设置超时时间//SSL相关if ($ssl) {curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); //禁用后cURL将终止从服务端进行验证curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); //检查服务器SSL证书中是否存在一个公用名(common name)。}// 处理post相关选项curl_setopt($curl, CURLOPT_POST, true); // 是否为POST请求curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // 处理请求数据// 处理响应结果curl_setopt($curl, CURLOPT_HEADER, false); //是否处理响应头curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); //curl_exec()是否返回响应结果// 发出请求$response = curl_exec($curl);if (false === $response) {echo '<br>', curl_error($curl), '<br>';return false;}curl_close($curl);return $response;}