Weave 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

Survey Monkey Api Client Bundle Laravel Package

davidwnek/survey_monkey_api_client_bundle

Symfony bundle integrating a SurveyMonkey API v3 client with OAuth setup. Configure client ID/secret and redirect URL via config/parameters, enable the bundle, and optionally use the built-in controller to handle the auth code callback.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to First Use

  1. Install the Bundle

    composer require davidwnek/survey-monkey-api-client-bundle dev-master
    

    Note: Use dev-master as the package is outdated (last release in 2018). Ensure your Laravel/Symfony project is compatible (Symfony 3.x+).

  2. Enable the Bundle Add to config/app.php (Laravel) or AppKernel.php (Symfony):

    davidwnek\SurveyMonkeyApiClientBundle\SurveyMonkeyApiClientBundle::class,
    
  3. Configure Credentials Add to .env (Laravel) or parameters.yml:

    SM_CLIENT_ID=your_client_id
    SM_CLIENT_SECRET=your_client_secret
    SM_REDIRECT_URL=http://your-app.com/survey_monkey/code
    

    Generate credentials via SurveyMonkey Developer Portal.

  4. Set Up Routing Add to routes/web.php (Laravel) or routing.yml (Symfony):

    // Laravel
    Route::get('/survey_monkey/code', [\davidwnek\SurveyMonkeyApiClientBundle\Controller\AuthenticationController::class, 'authenticate']);
    
  5. First API Call Inject the client into a service/controller:

    use davidwnek\SurveyMonkeyApiClientBundle\Service\SurveyMonkeyApiClient;
    
    public function __construct(SurveyMonkeyApiClient $client) {
        $this->client = $client;
    }
    
    // Example: Fetch surveys
    $surveys = $this->client->get('/surveys');
    

Implementation Patterns

Workflows

  1. OAuth Flow

    • Redirect users to SurveyMonkey for authentication:
      return redirect($this->client->getAuthUrl());
      
    • Handle the callback (e.g., /survey_monkey/code) to exchange the code for an access token. The bundle provides a built-in AuthenticationController for this.
  2. API Resource Management

    • Surveys: Create, fetch, or update surveys.
      $survey = $this->client->post('/surveys', ['title' => 'Customer Feedback']);
      $survey->questions = $this->client->get("/surveys/{$survey->id}/questions");
      
    • Pages/Questions: Use the Pages and PagesQuestions endpoints (added in v1.1.0).
      $page = $this->client->post("/surveys/{$survey->id}/pages", ['title' => 'Page 1']);
      $question = $this->client->post("/pages/{$page->id}/questions", ['title' => 'Question 1']);
      
  3. Error Handling Wrap API calls in a try-catch block to handle SurveyMonkey API errors (e.g., 401 Unauthorized, 404 Not Found):

    try {
        $response = $this->client->get('/surveys');
    } catch (\GuzzleHttp\Exception\RequestException $e) {
        $error = json_decode($e->getResponse()->getBody(), true);
        // Log or handle error (e.g., redirect to login if 401)
    }
    
  4. Token Refresh Store the access token and refresh token in the session or database. Refresh the token when it expires:

    $this->client->setAccessToken($refreshToken);
    $newAccessToken = $this->client->refreshAccessToken();
    

Integration Tips

  • Laravel-Specific:

    • Use Laravel’s Http facade or GuzzleHttp directly if you need more control over requests.
    • Store SurveyMonkey tokens in Laravel’s encrypter or sanctum for secure access.
    • Example service:
      namespace App\Services;
      
      use davidwnek\SurveyMonkeyApiClientBundle\Service\SurveyMonkeyApiClient;
      use Illuminate\Support\Facades\Cache;
      
      class SurveyMonkeyService {
          public function __construct(SurveyMonkeyApiClient $client) {
              $this->client = $client;
          }
      
          public function getSurvey($id) {
              return Cache::remember("survey_{$id}", now()->addHours(1), function() use ($id) {
                  return $this->client->get("/surveys/{$id}");
              });
          }
      }
      
  • Symfony-Specific:

    • Use Symfony’s dependency injection to inject the SurveyMonkeyApiClient into services.
    • Store tokens in Symfony’s security component or a custom ParameterBag.
  • Testing:

    • Mock the SurveyMonkeyApiClient in PHPUnit tests:
      $mockClient = $this->createMock(SurveyMonkeyApiClient::class);
      $mockClient->method('get')->willReturn(['survey' => 'data']);
      $this->app->instance(SurveyMonkeyApiClient::class, $mockClient);
      

Gotchas and Tips

Pitfalls

  1. Outdated Package:

    • The package is abandoned (last release in 2018). Expect compatibility issues with modern Laravel/Symfony versions or SurveyMonkey API changes.
    • Workaround: Fork the repository and update dependencies (e.g., guzzlehttp/guzzle, symfony/http-foundation).
  2. OAuth Flow Complexity:

    • The bundle provides a basic OAuth flow, but you may need to extend it for:
      • Custom redirect routes.
      • Handling state parameters for CSRF protection.
      • Storing tokens securely (e.g., in a database or encrypted cache).
    • Tip: Use Laravel’s Session or Symfony’s Session component to manage the OAuth state.
  3. Token Management:

    • The bundle does not persist tokens automatically. You must:
      • Store the access_token and refresh_token after the OAuth callback.
      • Implement logic to refresh the token when it expires (typically every 30 days for SurveyMonkey).
    • Tip: Use Laravel’s auth:sanctum or Symfony’s security component to manage tokens.
  4. Rate Limiting:

    • SurveyMonkey’s API has rate limits (e.g., 100 requests per 10 minutes). The bundle does not handle retries or rate limiting.
    • Tip: Implement exponential backoff using Guzzle middleware:
      $client = new SurveyMonkeyApiClient();
      $client->getClient()->getEmitter()->attach(
          new \GuzzleHttp\Middleware::retry(
              new \GuzzleHttp\RetryMiddleware(),
              $backoff = 100
          )
      );
      
  5. Environment-Specific Redirect URLs:

    • The redirect_url must match exactly what’s configured in SurveyMonkey’s developer portal. Use environment-specific values (e.g., localhost for dev, yourdomain.com for prod).
    • Tip: Use Laravel’s .env or Symfony’s parameters.yml to manage this:
      # .env
      SM_REDIRECT_URL=${APP_ENV_LOCAL}http://localhost:8000/survey_monkey/code:${APP_ENV_PROD}https://yourdomain.com/survey_monkey/code
      

Debugging

  1. Enable Guzzle Debugging: Add this to your SurveyMonkeyApiClient configuration to log requests/responses:

    $client = new SurveyMonkeyApiClient();
    $client->getClient()->getConfig()->setDebug(true);
    $client->getClient()->getEmitter()->attach(
        new \GuzzleHttp\HandlerStack()
    );
    
  2. SurveyMonkey API Errors: SurveyMonkey returns errors in the format:

    {
        "error": {
            "code": "invalid_request",
            "message": "Invalid parameter: title"
        }
    }
    

    Tip: Parse the error response to provide user-friendly feedback.

  3. CORS Issues: If you encounter CORS errors when calling the API from a frontend, ensure:

    • Your SurveyMonkey app is configured with the correct redirect_url.
    • You’re using the correct access token (e.g., not mixing up user and app tokens).

Extension Points

  1. Custom Authentication Flow: Extend the AuthenticationController to:

    • Add CSRF protection.
    • Customize the success/failure redirect routes.
    • Example:
      namespace App\Controller;
      
      use davidwnek\SurveyMonkeyApiClientBundle\Controller\AuthenticationController as BaseController;
      
      class CustomAuthenticationController extends BaseController {
          protected function getSuccessRedirectRoute() {
              return 'dashboard';
          }
      
          protected function getFailureRedirectRoute() {
              return 'login';
          }
      }
      
  2. Add Custom Endpoints: Extend the SurveyMonkeyApiClient to support additional SurveyMonkey API endpoints:

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.
pharaonic/laravel-notification-dependencies
beautinow/translug
dev-brainiac/bot-cloaked
octoberrain/html
octoberrain/extension
octoberrain/exception
octoberrain/contracts
frankyso/ipaymu
3mdikram/worldmoneywords
snowsoft/config
itmosoft/laravel-subscriptions
larva/laravel-ai-qwen
adachsoft/api-version-bundle
cgv/localized-resource
noith/settings
kda/laravel-package
kda/filament-dynamic-navigation
bypersoft/signbox
pairus/product-data
fayne/laravel-filament-cms-core