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

mpclarkson/freshdesk-php-sdk

PHP 5.5+ SDK for Freshdesk API v2. Simple, resource-based client: $api->tickets->all/create/update/view/delete, plus contacts, agents, companies, groups and more. Returns plain arrays. Composer install and easy Symfony/Laravel integration.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require mpclarkson/freshdesk-php-sdk
    

    For Laravel/Lumen, use the Laravel Service Provider for dependency injection.

  2. First API Call:

    use Freshdesk\Api;
    
    $api = new Api(config('freshdesk.api_key'), config('freshdesk.domain'));
    $tickets = $api->tickets->all(['page' => 1, 'per_page' => 10]);
    
  3. Laravel Configuration (if using the service provider): Add to config/services.php:

    'freshdesk' => [
        'api_key' => env('FRESHDESK_API_KEY'),
        'domain'  => env('FRESHDESK_DOMAIN'),
    ],
    

    Then bind in AppServiceProvider:

    $this->app->singleton('freshdesk', function ($app) {
        return new Api(config('freshdesk.api_key'), config('freshdesk.domain'));
    });
    

First Use Case: Fetching and Creating Tickets

// Fetch tickets for a specific company
$tickets = $api->tickets->all(['company_id' => 123]);

// Create a new ticket
$newTicket = $api->tickets->create([
    'subject' => 'API Test Ticket',
    'description' => 'Created via PHP SDK',
    'priority' => 2,
    'requester_id' => 456,
]);

Implementation Patterns

Common Workflows

1. Ticket Management

  • Fetching Tickets:
    $tickets = $api->tickets->all(['status' => 2, 'page' => 1, 'per_page' => 20]);
    
  • Creating/Updating Tickets:
    $ticketData = ['subject' => 'Update', 'description' => 'Updated via API'];
    $updated = $api->tickets->update(123, $ticketData);
    
  • Adding Notes:
    $api->conversations->note(123, ['body' => 'Follow-up note']);
    

2. Contact and Company Management

  • Fetching Contacts:
    $contacts = $api->contacts->all(['email' => 'user@example.com']);
    
  • Creating a Company:
    $company = $api->companies->create([
        'name' => 'Acme Corp',
        'domain_names' => ['acme.com'],
    ]);
    

3. Agent Workflows

  • Fetch Current Agent:
    $currentAgent = $api->agents->current();
    
  • Convert Contact to Agent:
    $api->contacts->makeAgent(789, ['role_id' => 1]);
    

4. Forum and Topic Monitoring

  • Monitor a Topic:
    $api->topics->monitor(456, $agentId);
    
  • Fetch Monitored Topics:
    $monitored = $api->topics->all(['monitored_by' => $agentId]);
    

Integration Tips

Laravel Eloquent Integration

Map Freshdesk resources to Eloquent models for seamless ORM usage:

// Example: Ticket Model
class Ticket extends Model
{
    protected $fillable = ['subject', 'description', 'priority'];

    public static function fetchFromFreshdesk($api, $id)
    {
        $data = $api->tickets->view($id);
        return new static($data);
    }
}

API Response Handling

Use Laravel's Http facade to standardize responses:

use Illuminate\Support\Facades\Http;

try {
    $response = $api->tickets->all();
    return Http::response($response, 200);
} catch (\Freshdesk\Exceptions\ApiException $e) {
    return Http::response(['error' => $e->getMessage()], 500);
}

Batch Processing

Process large datasets efficiently with pagination:

$page = 1;
$perPage = 100;
$allTickets = [];

do {
    $tickets = $api->tickets->all(['page' => $page, 'per_page' => $perPage]);
    $allTickets = array_merge($allTickets, $tickets);
    $page++;
} while (!empty($tickets));

Webhook Integration

Trigger Laravel events on Freshdesk API responses:

event(new TicketCreated($newTicket));

Gotchas and Tips

Pitfalls

  1. API Credits:

    • Each include in a view() call consumes additional credits. Example:
      // Avoid if not needed
      $ticket = $api->tickets->view(123, ['include' => 'requester,company']);
      
    • Fix: Only include necessary fields.
  2. Rate Limiting:

    • Freshdesk enforces rate limits (e.g., 60 requests/minute for API keys).
    • Fix: Implement exponential backoff or queue delayed jobs:
      use Illuminate\Support\Facades\Queue;
      
      Queue::later(now()->addSeconds(5), function () use ($api) {
          $api->tickets->all();
      });
      
  3. Unsupported Content Types:

    • The SDK throws UnsupportedContentTypeException if Freshdesk returns XML.
    • Fix: Ensure your Freshdesk account is configured to return JSON.
  4. Missing Resources:

    • Solutions and Surveys are not implemented in this SDK.
    • Fix: Use raw HTTP requests or wait for updates:
      $client = $api->getClient();
      $response = $client->get("/api/v2/solutions");
      
  5. ID Types:

    • Some methods expect scalar IDs (e.g., delete()), while others use objects.
    • Fix: Cast IDs explicitly:
      $api->companies->delete((int) $companyId);
      

Debugging Tips

  1. Enable Guzzle Middleware: Add a logging middleware to inspect requests/responses:

    $api = new Api($key, $domain);
    $api->getClient()->getEmitter()->attach(
        new \GuzzleHttp\Middleware::tap(function ($request, $options) {
            \Log::debug('Request:', [$request->getUri(), $options]);
        })
    );
    
  2. Handle Exceptions: Catch specific exceptions for granular error handling:

    try {
        $api->tickets->view(999);
    } catch (\Freshdesk\Exceptions\NotFoundException $e) {
        \Log::warning("Ticket not found: {$e->getMessage()}");
    }
    
  3. Validate Input Data: Use Laravel's Validator to ensure data matches Freshdesk's API schema:

    $validator = Validator::make($data, [
        'subject' => 'required|string|max:255',
        'description' => 'required|string',
    ]);
    

Extension Points

  1. Custom Resources: Extend AbstractResource to add unsupported endpoints:

    namespace App\Freshdesk;
    
    use Freshdesk\Resources\AbstractResource;
    
    class Solution extends AbstractResource
    {
        protected $resource = 'solutions';
    
        public function all(array $query = null)
        {
            return $this->get($query);
        }
    }
    
  2. Mocking for Testing: Use Laravel's MockHttp to test API interactions:

    $this->mock(Http::class, function ($mock) {
        $mock->shouldReceive('get')
             ->withArgs(['/api/v2/tickets/123'], ['headers' => ['Authorization' => 'Bearer ...']])
             ->andReturn(['id' => 123, 'subject' => 'Test']);
    });
    
  3. Caching Responses: Cache frequent API calls using Laravel's cache:

    $cacheKey = "freshdesk_tickets_{$companyId}";
    $tickets = Cache::remember($cacheKey, now()->addHours(1), function () use ($api, $companyId) {
        return $api->tickets->all(['company_id' => $companyId]);
    });
    
  4. Webhook Verification: Verify Freshdesk webhook signatures:

    use Illuminate\Http\Request;
    
    public function handleWebhook(Request $request)
    {
        $signature = $request->header('X-Freshdesk-Signature');
        $payload = $request->getContent();
    
        if (!hash_equals($signature, hash_hmac('sha256', $payload, config('freshdesk.webhook_secret')))) {
            abort(401
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui