Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to shorten URL using PHP Bitly v4?

Tags:

php

bit.ly

I have this code for Bitly v3 and it is working well.

<?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
?>

However, how can this be done in the newer version? The above example uses API keys but it has been deprecated in favor of OAuth requests.

How to shorten URL using Bitly v4?

like image 581
Abel Callejo Avatar asked Nov 28 '22 21:11

Abel Callejo


2 Answers

Get generic access token

Go to your Bitly, click on the hamburger menu on the top-right side > Settings > Advanced Settings > API Support > click on the link Generic Access Tokens. Type in your password and generate a generic token. That's what you'll use for authentication.

See https://dev.bitly.com/v4_documentation.html and look for Application using a single account section.

Authentication has changed a bit according to https://dev.bitly.com/v4/#section/Application-using-a-single-account.

How you authenticate to the Bitly API has changed with V4. Previously your authentication token would be provided as the access_token query parameter on each request. V4 instead requires that the token be provided as part of the Authorization header on each request.

Code

See this doc https://dev.bitly.com/v4/#operation/createFullBitlink for information about what Bitly expects.

In v4, you could use generic token as a bearer in your headers with each request like so:

<?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);

Request

JSON that you send will look like this:

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

Response

{
   "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"
   }
}

EDIT

There is a request in comments to see just the short link output. In order to do that, just adapt the code like so:

<?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';
}

Result (assuming the above file was test.php)

php test.php

bit.ly/2ZbYD4Z
like image 102
zedfoxus Avatar answered Dec 10 '22 07:12

zedfoxus


Here is a PHP package you can use https://packagist.org/packages/codehaveli/bitly-php

Step to use the package:

Step 1:

composer require codehaveli/bitly-php:dev-master --prefer-source to install the package via composer [Get it from here if not installed https://getcomposer.org/]

Step 2:

Add Access Token and Group GUID from Bitly [Guide here: https://www.codehaveli.com/how-to-generate-bitly-oauth-access-token/]

<?php

require 'vendor/autoload.php';

use Codehaveli\Bitly;
use Codehaveli\Exceptions\BitlyErrorException;

// First setup your credentials provided by Bitly

$accessToken  = "ACCESS_TOKEN_FROM_BITLY";
$guid         = "GUID_FROM_BITLY";

Bitly::init($accessToken, $guid);

Step 3:

After initializing with an access token and guide just call the method getUrl from the resource like with an URL will give you the short link.

<?php

use Codehaveli\Bitly;
use Codehaveli\Exceptions\BitlyErrorException;

$accessToken  = "ACCESS_TOKEN_FROM_BITLY";
$guid         = "GUID_FROM_BITLY";

Bitly::init($accessToken, $guid);

$link = Bitly::link();

try {

    $shortLink = $link->getUrl("https://stackoverflow.com/"); // Generated link

} catch (BitlyErrorException $e) {

    $code    = $e->getCode();
    $message = $e->getMessage();
}

Note: This package is in active development.

like image 20
Rakesh Roy Avatar answered Dec 10 '22 09:12

Rakesh Roy