Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Bitly Api Laravel Package

hpatoio/bitly-api

Unmaintained PHP Bitly API client built on Guzzle. Provides a Bitly\Client for calling endpoints (e.g., Highvalue), supports custom cURL options like timeouts, and allows attaching Guzzle plugins (e.g., logging). Symfony2 integration mentioned.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:
    composer require hpatoio/bitly-api
    
  2. Basic Usage:
    use Hpatoio\BitlyApi\BitlyApi;
    
    $bitly = new BitlyApi('YOUR_ACCESS_TOKEN');
    $shortUrl = $bitly->shorten('https://example.com');
    echo $shortUrl->getShortUrl();
    
  3. First Use Case:
    • Shorten a long URL and retrieve the Bitly link.
    • Fetch click analytics for a shortened URL.
    • Deprecation Note: This package is deprecated and may not support Bitly's latest API (v4+). Consider alternatives like spatie/bitly or direct API integration for production use.

Key Files to Explore

  • src/BitlyApi.php – Core class with API methods (may contain outdated endpoints).
  • src/Exceptions/ – Custom exceptions for error handling.
  • src/Models/ – Response models (e.g., ShortUrl, Click).
  • New: Check README.md or CHANGELOG.md for deprecation warnings and migration paths.

Implementation Patterns

Common Workflows

  1. URL Shortening (Legacy API):

    $bitly = new BitlyApi($accessToken);
    $result = $bitly->shorten('https://laravel.com/docs', [
        'title' => 'Laravel Docs',
        'tags' => ['laravel', 'docs']
    ]);
    
    • Warning: This may fail for Bitly API v4+ endpoints. Verify compatibility.
  2. Fetching Analytics (Legacy):

    $clicks = $bitly->getClicks('bit.ly/3Example');
    foreach ($clicks as $click) {
        echo $click->getTimestamp() . ': ' . $click->getCountry();
    }
    
    • Tip: Use try-catch for BitlyException to handle deprecated endpoint errors gracefully.
  3. Batch Operations (Legacy):

    $urls = ['https://example1.com', 'https://example2.com'];
    $shortUrls = $bitly->shortenBatch($urls);
    
    • Note: Batch operations may not work with newer API versions.

Integration Tips

  • Laravel Service Provider (Legacy): Bind the client to the container:

    $this->app->singleton(BitlyApi::class, function ($app) {
        return new BitlyApi(config('services.bitly.token'));
    });
    
    • Recommendation: Replace with a modern alternative (e.g., spatie/bitly) in production.
  • Configuration: Store the access token in .env:

    BITLY_ACCESS_TOKEN=your_token_here
    
    • Security Note: Avoid hardcoding tokens. Use Laravel’s env() or a secrets manager.
  • Error Handling: Wrap API calls to handle deprecation warnings:

    try {
        $result = $bitly->shorten('https://example.com');
    } catch (\Hpatoio\BitlyApi\Exceptions\BitlyException $e) {
        Log::warning('Deprecated Bitly API call: ' . $e->getMessage());
        // Fallback to direct API call or alternative package
    }
    

Gotchas and Tips

Pitfalls

  1. Deprecated API (Critical):

    • This package no longer supports Bitly’s latest API (v4+). The 2.0.6 release explicitly warns about deprecation.
    • Action Required:
      • For new projects, use spatie/bitly or direct API integration.
      • For legacy projects, extend the client to support v4 endpoints or migrate incrementally.
  2. Rate Limiting:

    • Bitly’s free tier enforces 500 requests/hour. Cache responses aggressively:
      $cacheKey = 'bitly:shortened:' . md5($url);
      if (Cache::has($cacheKey)) {
          return Cache::get($cacheKey);
      }
      $shortUrl = $bitly->shorten($url);
      Cache::put($cacheKey, $shortUrl, now()->addHours(1));
      
  3. Token Management:

    • Hardcoding tokens violates security best practices. Use Laravel’s .env or a secrets manager.
  4. Response Parsing:

    • The package’s ShortUrl and Click models may not align with Bitly’s v4 response structure.
    • Workaround: Extend the client or parse raw responses manually:
      $response = $bitly->client->get('/v4/shorten', ['query' => ['long_url' => $url]]);
      $data = json_decode($response->getBody(), true);
      

Debugging

  • Enable Guzzle Debugging: Log requests/responses to identify deprecated endpoints:

    $bitly = new BitlyApi($token, [
        'debug' => true,
        'handler' => HandlerStack::create([
            new \GuzzleHttp\Middleware::tap(function ($request) {
                Log::debug('Deprecated Bitly Request:', [
                    'url' => (string) $request->getUri(),
                    'method' => $request->getMethod()
                ]);
            }),
        ]),
    ]);
    
  • Common Errors:

    • 401 Unauthorized: Invalid token or deprecated endpoint.
    • 404 Not Found: Endpoint no longer exists in v4.
    • 429 Too Many Requests: Hit rate limits.
    • New: Add 410 Gone to catch explicitly deprecated endpoints.

Extension Points

  1. Migrate to Bitly API v4: Override the base URL and endpoints:

    class BitlyV4Api extends BitlyApi {
        protected $baseUri = 'https://api-ssl.bitly.com/v4';
    
        public function shorten($longUrl, array $options = []) {
            return $this->client->post('/shorten', [
                'json' => array_merge(['long_url' => $longUrl], $options)
            ]);
        }
    }
    
  2. Webhooks (Legacy): Bitly’s webhook system has changed in v4. Update validation logic if using this feature.

  3. Testing: Mock the client to test deprecated behavior:

    $mockHandler = HandlerStack::create();
    $mockHandler->push(Middleware::mock(function ($request) {
        if (str_contains($request->getUri(), 'v3')) {
            return new Response(410, [], json_encode(['error' => 'Deprecated']));
        }
        return new Response(200, [], json_encode(['id' => 'bit.ly/test']));
    }));
    $bitly = new BitlyApi($token, ['handler' => $mockHandler]);
    
  4. Fallback Logic: Implement a fallback to direct API calls when the package fails:

    public function safeShorten($url) {
        try {
            return $this->shorten($url);
        } catch (\Exception $e) {
            return $this->directApiCall($url); // Custom v4 implementation
        }
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky