首页 > 解决方案 > 如何使用 PHP Bitly v4 缩短 URL?

问题描述

我有这个 Bitly v3的代码,它运行良好。

<?php
$login = 'login-code-here';
$api_key = 'api-key-here';
$long_url = 'https://stackoverflow.com/questions/ask';

$ch = curl_init('http://api.bitly.com/v3/shorten?login='.$login.'&apiKey='.$api_key.'&longUrl='.$long_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
$res = json_decode($result, true);
echo $res['data']['url']; // bit.ly/2PcG3Fg
?>

但是,如何在较新的版本中做到这一点?上面的示例使用 API 密钥,但它已被弃用以支持 OAuth 请求。

如何使用 Bitly v4缩短 URL ?

标签: phpbit.ly

解决方案


获取通用访问令牌

转到您的 Bitly,单击右上角的汉堡菜单 > 设置 > 高级设置 > API 支持 > 单击链接通用访问令牌。输入您的密码并生成通用令牌。这就是您将用于身份验证的内容。

请参阅https://dev.bitly.com/v4_documentation.html并查找使用单个帐户部分的应用程序。

身份验证根据https://dev.bitly.com/v4/#section/Application-using-a-single-account有所改变。

您对 Bitly API 进行身份验证的方式在 V4 中发生了变化。以前,您的身份验证令牌将作为每个请求的 access_token 查询参数提供。相反,V4 要求将令牌作为每个请求的 Authorization 标头的一部分提供。

代码

有关Bitly 期望的信息,请参阅此文档https://dev.bitly.com/v4/#operation/createFullBitlink 。

在 v4 中,您可以在每个请求的标头中使用通用令牌作为承载,如下所示:

<?php

$long_url = 'https://stackoverflow.com/questions/ask';
$apiv4 = 'https://api-ssl.bitly.com/v4/bitlinks';
$genericAccessToken = 'your-token';

$data = array(
    'long_url' => $long_url
);
$payload = json_encode($data);

$header = array(
    'Authorization: Bearer ' . $genericAccessToken,
    'Content-Type: application/json',
    'Content-Length: ' . strlen($payload)
);

$ch = curl_init($apiv4);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
$result = curl_exec($ch);

print_r($result);

要求

您发送的 JSON 将如下所示:

{"long_url":"https:\/\/stackoverflow.com\/questions\/ask"}

回复

{
   "created_at":"1970-01-01T00:00:00+0000",
   "id":"shortcode-link-id-here",
   "link":"shortcode-link-here",
   "custom_bitlinks":[

   ],
   "long_url":"https://stackoverflow.com/questions/ask",
   "archived":false,
   "tags":[

   ],
   "deeplinks":[

   ],
   "references":{
      "group":"group-link-here"
   }
}

编辑

评论中有要求只查看短链接输出。为此,只需像这样调整代码:

<?php
$long_url = 'https://stackoverflow.com/questions/ask';
$apiv4 = 'https://api-ssl.bitly.com/v4/bitlinks';
$genericAccessToken = 'your-token';

$data = array(
    'long_url' => $long_url
);
$payload = json_encode($data);

$header = array(
    'Authorization: Bearer ' . $genericAccessToken,
    'Content-Type: application/json',
    'Content-Length: ' . strlen($payload)
);

$ch = curl_init($apiv4);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
$result = curl_exec($ch);
$resultToJson = json_decode($result);

if (isset($resultToJson->link)) {
    echo $resultToJson->link;
}
else {
    echo 'Not found';
}

结果(假设上面的文件是test.php)

php test.php

bit.ly/2ZbYD4Z

推荐阅读