欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  php教程

调用新浪微博短址API代码

程序员文章站 2024-01-15 12:02:34
...
php代码
<?php
$backurl="";
if (isset($_GET['type'])){
	$type=$_GET['type'];
	switch (trim($type))
	{
	case 1:
		if (isset($_GET['url'])){
			$backurl=shorturl(urlencode($_GET['url']));  //注意必须经过urlencode
		}
		else{
			$backurl="error0";
		}
		break;
	case 2:
		if (isset($_GET['url'])){
			$backurl=expandurl($_GET['url']);
		}
		else{
			$backurl="error1";
		}
		break;
	default:
		$backurl="error2";
	}
}
echo $backurl;

function shortenSinaUrl($long_url){
	$apiKey='xxxxxxxxx';    //请替换成你的APPID
	$apiUrl='https://api.weibo.com/2/short_url/shorten.json?source='.$apiKey.'&url_long='.$long_url;
	$curlObj = curl_init();
	curl_setopt($curlObj, CURLOPT_URL, $apiUrl);
	curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, 0);
	curl_setopt($curlObj, CURLOPT_HEADER, 0);
	curl_setopt($curlObj, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
	$response = curl_exec($curlObj);
	curl_close($curlObj);
	$json = json_decode($response);
	return $json->urls[0]->url_short;
}

function expandSinaUrl($short_url){
	$apiKey='xxxxxxxxx';    //请替换成你的APPID
	$apiUrl='https://api.weibo.com/2/short_url/expand.json?source='.$apiKey.'&url_short='.$short_url;
	$curlObj = curl_init();
	curl_setopt($curlObj, CURLOPT_URL, $apiUrl);
	curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, 0);
	curl_setopt($curlObj, CURLOPT_HEADER, 0);
	curl_setopt($curlObj, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
	$response = curl_exec($curlObj);
	curl_close($curlObj);
	$json = json_decode($response);
	return $json->urls[0]->url_long;
}


function shorturl($long_url){
	$apiKey='xxxxxxxxx';    //请替换成你的APPID
	$apiUrl='https://api.weibo.com/2/short_url/shorten.json?source='.$apiKey.'&url_long='.$long_url;
	$response = file_get_contents($apiUrl);
	$json = json_decode($response);
	return $json->urls[0]->url_short;
}

function expandurl($short_url){
	$apiKey='xxxxxxxxx';    //请替换成你的APPID
	$apiUrl='https://api.weibo.com/2/short_url/expand.json?source='.$apiKey.'&url_short='.$short_url;
	$response = file_get_contents($apiUrl);
	$json = json_decode($response);
	return $json->urls[0]->url_long;
}
?>