How to shorten URL using PHP Bitly v4?
Asked Answered
T

2

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?

Tyrant answered 15/4, 2019 at 2:21 Comment(1)
quick look at the provided documentation, seems good, dev.bitly.com/v4_documentation.html what are you stuck on?Triptych
C
26

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
Chatelaine answered 15/4, 2019 at 3:22 Comment(9)
Hi, how you can print only the bitly url?Gnash
That api URL doesn't look correct, shouldn't it be: api-ssl.bitly.com/v4/shorten dev.bitly.com/v4/#operation/createBitlink - also, this requires the group_guidInsipience
All worked well when I wrote the answer. Specs could have changed. You’re welcome to write an answer with latest code that works @InsipienceChatelaine
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?Endpaper
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.Chatelaine
@Insipience I ran this example today and it worked just fine.Chatelaine
@Endpaper 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)Chatelaine
@Chatelaine works great, thanks for adding the last bit.Endpaper
what if I need to add a custom second-half, please?Latakia
V
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.

Valarievalda answered 20/9, 2020 at 11:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.