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

Freshdesk Php Sdk Laravel Package

hasfoug/freshdesk-php-sdk

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require hasfoug/freshdesk-php-sdk
    

    Add the package to your composer.json and run composer update.

  2. Basic Configuration Create a config file (e.g., config/freshdesk.php) with your API domain and API key:

    return [
        'domain' => env('FRESHDESK_DOMAIN', 'yourdomain.freshdesk.com'),
        'api_key' => env('FRESHDESK_API_KEY', 'your_api_key_here'),
    ];
    

    Publish the config file:

    php artisan vendor:publish --provider="Hasfoug\Freshdesk\FreshdeskServiceProvider"
    
  3. First API Call Use the SDK in a controller or service:

    use Hasfoug\Freshdesk\Client;
    
    $client = new Client(config('freshdesk.domain'), config('freshdesk.api_key'));
    
    // Example: Fetch tickets
    $tickets = $client->tickets()->get();
    dd($tickets);
    
  4. Environment Variables Add to your .env:

    FRESHDESK_DOMAIN=yourdomain.freshdesk.com
    FRESHDESK_API_KEY=your_api_key_here
    

Implementation Patterns

Common Workflows

Ticket Management

  • Create a Ticket

    $ticket = $client->tickets()->create([
        'subject' => 'New Issue',
        'description' => 'Details here...',
        'priority' => 2,
    ]);
    
  • Update a Ticket

    $client->tickets()->update($ticketId, [
        'status' => 3, // 'open' => 1, 'pending' => 2, 'hold' => 3, etc.
        'priority' => 1,
    ]);
    
  • Fetch a Ticket

    $ticket = $client->tickets()->get($ticketId);
    
  • List Tickets with Filters

    $tickets = $client->tickets()->get(['page' => 1, 'per_page' => 20, 'query' => 'status:open']);
    

Contact Management

  • Create a Contact

    $contact = $client->contacts()->create([
        'name' => 'John Doe',
        'email' => 'john@example.com',
    ]);
    
  • Update a Contact

    $client->contacts()->update($contactId, ['phone' => '+1234567890']);
    

Integration with Laravel Jobs

Use Laravel's queue system to offload API calls:

use Hasfoug\Freshdesk\Jobs\CreateFreshdeskTicket;

CreateFreshdeskTicket::dispatch($ticketData)->onQueue('freshdesk');

Middleware for API Calls

Create middleware to handle API rate limits or retries:

public function handle($request, Closure $next)
{
    $response = $next($request);

    if ($response->status() === 429) {
        sleep(1); // Retry after delay
        return $this->handle($request, $next);
    }

    return $response;
}

Gotchas and Tips

Common Pitfalls

  1. API Rate Limits

    • Freshdesk enforces rate limits (e.g., 60 requests per minute). Cache responses aggressively:
      $tickets = Cache::remember("freshdesk_tickets_{$query}", now()->addMinutes(5), function () use ($client, $query) {
          return $client->tickets()->get(['query' => $query]);
      });
      
  2. API Key Exposure

    • Never hardcode API keys in your code. Use Laravel's .env and env() helper.
    • Restrict API key permissions in Freshdesk to only necessary endpoints.
  3. Pagination Handling

    • The SDK does not auto-paginate. Manually handle pagination:
      $allTickets = [];
      $page = 1;
      do {
          $tickets = $client->tickets()->get(['page' => $page, 'per_page' => 100]);
          $allTickets = array_merge($allTickets, $tickets['tickets']);
          $page++;
      } while (!empty($tickets['tickets']));
      
  4. Error Handling

    • Wrap API calls in try-catch blocks:
      try {
          $ticket = $client->tickets()->create($data);
      } catch (\Hasfoug\Freshdesk\Exception\ApiException $e) {
          Log::error("Freshdesk API Error: " . $e->getMessage());
          return back()->with('error', 'Failed to create ticket.');
      }
      
  5. Time Zone Issues

    • Freshdesk uses UTC. Convert dates if your app uses a different timezone:
      $createdAt = Carbon::parse($ticket['created_time'])->timezone('America/New_York');
      

Extension Points

  1. Custom Requests Use the low-level request() method for unsupported endpoints:

    $response = $client->request('GET', '/api/v2/tickets/custom_field', ['custom_field_id' => 123]);
    
  2. Webhooks Implement webhook listeners in Laravel:

    // routes/web.php
    Route::post('/freshdesk/webhook', [FreshdeskWebhookController::class, 'handle']);
    
    // FreshdeskWebhookController.php
    public function handle(Request $request)
    {
        $payload = $request->json()->all();
        // Process webhook (e.g., update local DB)
    }
    
  3. Testing Use Laravel's HTTP tests to mock API responses:

    public function test_create_ticket()
    {
        $this->mockFreshdeskApi()
            ->shouldReceive('create')
            ->once()
            ->andReturn(['ticket' => ['id' => 123]]);
    
        $response = $this->post('/tickets', ['subject' => 'Test']);
        $response->assertCreated();
    }
    

Debugging Tips

  • Enable Debug Mode Set debug to true in config/freshdesk.php to log raw API requests/responses:

    'debug' => env('FRESHDESK_DEBUG', false),
    
  • Check API Status Verify your API key and domain are correct by visiting:

    https://{domain}.freshdesk.com/api/v2/tickets.json
    

    (Replace {domain} and authenticate with your API key.)

  • Use Postman Test endpoints manually in Postman before integrating into Laravel to isolate issues.

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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
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
spatie/mailcoach-vapor