php实现抖音开放平台账号授权获取码code、获取access_token

该代码段展示了如何通过PHP实现从抖音开放平台获取OAuth授权的访问令牌。当`code`为空时,程序重定向到授权链接,用户授权后回调到指定域名并获取`code`。然后,程序使用`code`、client_key和client_secret通过CURL请求获取access_token。返回的access_token信息可以用于进一步的API调用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

直接上代码

public function index(){
	$code = $_GET['code'];
	$dyClientKey = xxx;
	$dyClientSecret = xxx;
	if(empty($code)){
		$redirect_uri = "http://www.xxx.com";//授权回调域名(要和在抖音平台申请的网站应用回调域名要一致) 用来接收抖音平台返回的code
		$redirect_uri = urlencode($redirect_uri);
		$url = "https://open.douyin.com/platform/oauth/connect/?client_key={$dyClientKey}&response_type=code&scope=user_info,video.create&redirect_uri={$redirect_uri}";
		header("Location:" . $url);
	}else{
		$get_access_token_url = "https://open.douyin.com/oauth/access_token?client_key={$dyClientKey}&client_secret={$dyClientSecret}&grant_type=authorization_code&code={$code}";
		$access_token_info = $this->getJson($get_access_token_url);
        echo '<pre>';
        var_dump($access_token_info);
	}
}
//curl请求
public function getJson($url){
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
	curl_setopt($ch, CURLOPT_HEADER, FALSE);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);//为true,则会跟踪爬取重定向页面,否则,不会跟踪重定向页面
	$output = curl_exec($ch);
	curl_close($ch);
	return json_decode($output, true);
}

返回access_token信息截图

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

木子李0531

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值