5

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?

Abel Callejo
  • 13,779
  • 10
  • 69
  • 84
  • 1
    quick look at the provided documentation, seems good, https://dev.bitly.com/v4_documentation.html what are you stuck on? –  Apr 15 '19 at 03:11

2 Answers2

25

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
zedfoxus
  • 35,121
  • 5
  • 64
  • 63
  • Hi, how you can print only the bitly url? – FilipeOS Feb 20 '20 at 16:51
  • That api URL doesn't look correct, shouldn't it be: https://api-ssl.bitly.com/v4/shorten https://dev.bitly.com/v4/#operation/createBitlink - also, this requires the group_guid – gvanto Feb 25 '20 at 13:09
  • All worked well when I wrote the answer. Specs could have changed. You’re welcome to write an answer with latest code that works @gvanto – zedfoxus Feb 25 '20 at 22:54
  • I too would like to know how to get the shortened URL only from this. Also, do we not need to json_decode at the end? – dijon Feb 26 '20 at 18:54
  • Okay, @dijon, I think I can write another answer or update my answer to get only the shortened URL and use V4 changes that gvanto has mentioned. – zedfoxus Feb 26 '20 at 22:02
  • @gvanto I ran this example today and it worked just fine. – zedfoxus Feb 26 '20 at 22:30
  • 1
    @dijon I have edited my answer showing how you can output only the short link and nothing else (as long as link is a property of the decoded JSON) – zedfoxus Feb 26 '20 at 22:31
  • 1
    @zedfoxus works great, thanks for adding the last bit. – dijon Feb 26 '20 at 22:57
  • what if I need to add a custom second-half, please? – Tormy Van Cool Oct 06 '22 at 19:18
1

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.

Rakesh Roy
  • 930
  • 2
  • 12
  • 22