PHP 调用 新浪API 生成短网址
2 min read
2019年9月更新:新浪短网址官方接口功能已下线。
最近在做一个短网址生成的小工具,需要调用新浪的API,于是就写了一个PHP脚本。
我们需要到 新浪开放平台 上注册一个应用,获取到 AppKey
新浪短网址生成接口文档:https://open.weibo.com/wiki/2/short_url/shorten
<?php
// title: 生成新浪短网址
// update: 2018-05-23
// author: iami233
header('Access-Control-Allow-Origin:*');
header('Content-type: application/json');
// 设置常量
define('SINA_APPKEY', '1335371408');
$url = $_GET['url'] ?? null;
if (!$url) {
sendResponse(201, 'URL参数错误');
exit;
}
$url = filterUrl($url);
if (!$url) {
sendResponse(201, '过滤后的URL无效');
exit;
}
$short = sinaShortenUrl($url);
if (!$short) {
sendResponse(201, '无法获取短网址');
exit;
}
$long = sinaExpandUrl($short);
sendResponse(200, '成功', ['short' => $short, 'long' => $long]);
function curlQuery($url, $headers = ["Content-type: application/json"]) {
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => $url,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => false,
CURLOPT_TIMEOUT => 15
]);
$result = curl_exec($curl);
curl_close($curl);
return $result;
}
function filterUrl($url) {
$url = trim(strtolower($url));
if (strpos($url, 'http://') !== 0 && strpos($url, 'https://') !== 0) {
$url = 'http://' . $url;
}
return urlencode($url);
}
function sinaShortenUrl($url) {
$requestUrl = 'http://api.t.sina.com.cn/short_url/shorten.json?source=' . SINA_APPKEY . '&url_long=' . $url;
$result = curlQuery($requestUrl);
$json = json_decode($result, true);
return $json[0]['url_short'] ?? false;
}
function sinaExpandUrl($url) {
$requestUrl = 'http://api.t.sina.com.cn/short_url/expand.json?source=' . SINA_APPKEY . '&url_short=' . $url;
$result = curlQuery($requestUrl);
$json = json_decode($result, true);
return $json[0]['url_long'] ?? false;
}
function sendResponse($code, $msg, $data = null) {
echo json_encode([
'code' => $code,
'msg' => $msg,
'data' => $data
], JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE);
exit;
}