UserVoice PHP SDK

UserVoice SDK is now packaged in a PHP library (library & the source). This document illustrates its usage with installation instructions and a few examples just to get you quickly started.

Install OAuth, mcrypt and the library from Packagist

The library uses Composer as a package manager and requires two extensions to be installed and then loaded in php.ini:

After installing OAuth and mcrypt, make sure the extensions are loaded from your php.ini:

1
2
extension=oauth.so
extension=mcrypt.so

Composer requires you to create a dependency file composer.json, where you include uservoice/uservoice as a dependency:

1
2
3
4
5
{
  "require": {
    "uservoice/uservoice": ">=0.0.6"
  }
}

Now execute the dependency manager (installation) in your project root:

1
php composer.phar install

The command will create a directory “vendor” under the current working directory. The vendor contains the dependencies of uservoice/uservoice including the file autoload.php. It also makes sure the PHP5 extensions are available. The output should be something similar to this:

1
2
3
4
5
6
Loading composer repositories with package information
Installing dependencies from lock file
  - Installing uservoice/uservoice (v0.0.6)
    Downloading: 100%

Generating autoload files

Ready to go! Let’s see what we can do with this.

Creating a new API client

For creating a new API client you need to do a few things. First, get your API KEY and API SECRET from UserVoice Admin Console and pass them as parameters to the client like this:

1
2
3
4
5
6
7
8
9
10
11
12
<?php
// If you haven't already, require autoload.php from the vendor directory
include_once('vendor/autoload.php');

$SUBDOMAIN_NAME = 'uservoice';
$API_KEY = 'oQt2BaunWNuainc8BvZpAm';
$API_SECRET = '3yQMSoXBpAwuK3nYHR0wpY6opE341inL9a2HynGF2';
$SSO_KEY = '982c88f2df72572859e8e23423eg87ed';
$URL = 'http://localhost:4567/';

$client = new \UserVoice\Client($SUBDOMAIN_NAME, $API_KEY, $API_SECRET, array('callback' => $URL));
?>

Now we have an API client that we can use to connect Helpdesk API.

Post a new ticket

Making requests using the client follow the format $client->method(path, params). In the first example we post a new ticket, which is possible if you have the helpdesk service.

1
2
3
4
5
6
7
8
9
10
11
12
13
<?php
# Post a new ticket to your helpdesk from sidson@example.com
$result = $client->post("/api/v1/tickets.json", array(
    'email' => 'sidson@example.com',
    'ticket' => array(
        'state' => 'open',
        'subject' => 'PHP SDK',
        'message' => "I'm wondering if you would have any OAuth example for PHP?\n\n".
                     "Thanks,\n\nSidson"
    )
));
$question = $result['ticket'];
?>

Post a suggestion using an access token

Acting on behalf of the user lets you leave out the email parameter from the previous example as well as access to user-requiring API calls. In the following example we post a new suggestion in your first forum. You need feedback service for this example.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php
// Login as man.with.only.answers@example.com and retrieve an access token
$access_token = $client->login_as('man.with.only.answers@example.com');

$forums = $access_token->get_collection('/api/v1/forums?sort=newest', array('limit' => 1));
// Get the first forum id for the example which access_token has access to
$forum_id = $forums[0]['id'];

// Make the request using the access token
$result = $access_token->post("/api/v1/forums/${forum_id}/suggestions", array(
    'suggestion' => array(
        'title' => 'Color the left navbar to green'
    )
));
$suggestion = $result['suggestion'];

$result = $access_token->get("/api/v1/users/current");
$user = $result['user'];

print("${user['name']} created suggestion: ${suggestion['url']}\n");
// Prints: Anonymous created suggestion: http://..... 
?>

Get the access token of the account owner and post responses

To respond to the ticket, you need to log in as an admin (or owner).

1
2
3
4
5
6
7
8
9
10
11
12
13
<?php
// This logs in as the first owner of the account
$owner = $client->login_as_owner();

$posted_response = $owner->post("/api/v1/tickets/${question['id']}/ticket_messages", array(
    'ticket_message' => array(
        'text' => "Hi " . ucfirst($question['contact']['name']) . "!\n\n" .
                  "We sure do! See the installation instructions and a few example API calls " .
                  "here: http://developer.uservoice.com/docs/api/php-sdk\n\n" .
                  "Best regards,\n\nRaimo Tuisku\nDeveloper"
    )
));
?>

Getting a list of suggestions

You maybe noticed the use of get_collection when getting the first forum ID. Whenever you need to fetch paginated results (like all suggestions), you can use our lazy-loading collection.

1
2
3
4
5
6
7
8
9
10
11
12
<?php
    # Creates a lazy-loading collection object but makes no requests to the API yet.
    $suggestions = $client->get_collection("/api/v1/suggestions?sort=newest");

    # Loads the first page (at most 100 records) of suggestions and reads the count.
    print("Total suggestions: ". count($suggestions) . "\n");

    # Loops through all the suggestions and loads new pages as necessary.
    foreach ($suggestions as $suggestion) {
        print("${suggestion['title']}: ${suggestion['url']}\n");
    }
?>

Log your users into your Widget using SSO

If your site has both authenticated users and the UserVoice Widget installed, you should definitely pass the email of your logged-in user to the UserVoice Widget so that users don’t have to type it again in your site.

Generating an SSO token should be done on the server side, as you should never reveal your API SECRET to anyone. Here’s how you do it:

1
2
3
4
5
6
7
<?php
    function current_sso_token() {
        return \UserVoice\SSO::generate_token($SUBDOMAIN_NAME, $SSO_KEY, array(
            'email' => current_user().email
        ), 300); // Leaving this out sets the expiry time to 5 minutes = 300 seconds.
    }
?>

Now you can pass the SSO token to the UserVoice Widget JavaScript snippet. Make sure the aforementioned method current_sso_token() can be called from there.

1
2
3
4
5
6
7
8
9
10
11
<script type="text/javascript">
  var uvOptions = {
    params: { sso: '<?php echo current_sso_token(); ?>' }
  };
  (function() {
    var uv = document.createElement('script'); uv.type = 'text/javascript'; uv.async = true;
    uv.src = ('https:' == document.location.protocol ? 'https://' : 'http://') +
      'widget.uservoice.com/yourwidgetcodetobehere.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(uv, s);
  })();
</script>

That’s all! Now your users should be able to leave feedback and post tickets right away.

Associating your users with their UserVoice profiles

Connecting your users with their UserVoice profiles is possible by following a procedure called 3-Legged OAuth. The steps required to do this are explained below.

1. Provide a link or redirect user to /authorize from system X.

When you want to connect your current user to his or her UserVoice profile, redirect the browser to the authorization url like this:

1
2
3
4
<?php
// Redirects user to the UserVoice authorization dialog.
header('Location: ' . $client->authorize_url());
?>

Providing a direct link is another way to do the trick:

1
<a href="<?php echo $client->authorize_url(); ?>">Connect UserVoice</a>

2. User is asked to log in and give X permission to access information in UserVoice.

The authorization dialog will look like this:

3. UserVoice redirects user back to system X and passes an oauth verifier

UserVoice will pass a verification code back to your system, which you can use to request an access token for the user, so you know which profile in UserVoice is owned by your currently logged-in user.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?php
// Getting oauth verifier as a GET parameter
if (isset($_GET['oauth_verifier'])) {
    try {
        // Get access token for the user
        $access_token = $client->login_with_verifier($_GET['oauth_verifier']);


        // Persist the access token in the database for later use
        $user = current_user(); // current_user() returns e.g. a Doctrine object
        $user->uservoice_token = $access_token->token;
        $user->uservoice_secret = $access_token->secret;
        $user->refresh();
    } catch (\UserVoice\Unauthorized $ua) {
        # false/old verifier, present error
        $flash['error'] = "Access denied";
    }
    header('Location: /');
}
?>

4. System X makes API calls to UserVoice using the access token.

Now whenever you need to, you can make calls on behalf of the user whom you verified. Just use the access token you got in exchange for the verifier.

1
2
3
4
5
6
7
8
9
10
11
12
13
<?php
try {
    // Use the previously saved access token. Makes zero requests!
    $access_token = $client->login_with_access_token(current_user()->uservoice_token,
                                                     current_user()->uservoice_secret);
    // Get current user
    $user_attributes = $access_token->get_object("/api/v1/users/current.json");
    print $user_attributes['email'];
    // Prints: man.with.only.answers@example.com
} catch (\UserVoice\Unauthorized $ua) {
    // Tried to do something unauthorized
}
?>

Raimo Tuisku (twitter: @raimo_t)

Didn’t find what you’re looking for?

Check out the UserVoice Help Center for more documentation.

Explore the Help Center