Hyves Developer Summit
API Tips & Tricks

Robert Slootjes
March 2, 2012

Hi!

My first steps

The OAuth 'dance' - eh... wut?

Now what?



Choosing one of the PHP libraries

Boxing with code

$call = new HA_CALL('users.get',
    new HA_T('token', 'secret'), // HA_T? token...every time?
    new HA_R('profilepicture'), // HA_R? responsefields...
    new HA_P(array('userid ' => 'foo')) // HA_P? params...
);
if($call->execute() === true) { // just do this automaticly
    $response = $call->getResponseAsObject(); // why?
    if($response->hasErrors() === false) { // please use exceptions
        $users = $response->users_as_objects(); // why?
        $user = $users[0]; // php failing me here
        echo $user->firstname(); // finally
    }
}

Problem?

Building our own library

(that's what we like to do as PHP developers...)

MediaMonks_Service_Hyves or “HyvesPHP”

Show me the code - Startup

// your consumer key and consumer secret
$hyves = new MediaMonks_Service_Hyves('key', 'secret');

// optional: the user's access token
$hyves->setToken('token', 'token secret');

Or set it with some options:

// your consumer key and consumer secret
$hyves = new MediaMonks_Service_Hyves('key', 'secret', array(
    'version' => 'beta_2', // default = 2.1
    'fancylayout' => true,
    'https' => true
));

Show me the code - Authentication

You don't have to understand OAuth!

$hyvesAuth = new MediaMonks_Service_Hyves_Authorization($hyves);
$hyvesAuth->requestUserAuthorization(
    array('users.getLoggedin', 'search.find', 'users.get')
);

$response = $hyves->call('users.getLoggedin');
echo $response->firstname; // php's “magic methods”
Execute

Return fields, filter your response

/user/firstname,/user/lastname // only returns specified nodes
/user/birthday/* // returns all nodes in /user/birthday
//src // only return all 'src' nodes

Show me the code - Response- & Returnfields

$res = $hyves->call('users.getLoggedin', array(
    'responsefields' => array('profilepicture'),
    'returnfields' => array(
        '/user/birthday/*',
        '/user/profilepicture/square_large/src'
    )
));
echo implode('-', array($res->day, $res->month, $res->year));
echo $res->src;
Execute with returnfields
Execute without returnfields

Show me the code - Pagination

$response = $hyves->call('users.getFriendsByLoggedinSorted', array(
    'params' => array('sorttype' => 'alphabetically'),
    'pagination' => array(
        'page' => 1,
        'perpage' => 5
    )
));

$response->getTotalResults();
$response->getTotalPages();

for($i = 0; $i < $response->countResults('user'); $i++) {
    echo $response->user($i, 'firstname');
}
Execute

Batch processing

Show me the code - Batch processing to search friends

$hyves->startBatch()
    ->call('users.getLoggedin')
    ->call('search.find', array(
        'params' => array(
            'searchterms' => $term,
            'nrresults' => 5,
            'categories' => 'friends',
            'userid' => '0(userid)'
        )
    ))
    ->call('users.get', array(
        'params' => array('userid' => '1(userid)')
));
$responseBatch = $hyves->flushBatch();
for($i = 0; $i < $responseBatch[2]->countResults('user'); $i++) {
    echo $responseBatch[2]->user($i, 'firstname');
}
Execute

Show me the code - Uploading media

$uploadToken = $hyves->uploadFile('/location/to/file', array(
    'title' => 'Your actual funny picture',
    'description' => 'The usual lame description'
));

while(true) { // poll upload status every 2 seconds
    sleep(2);
    $status = $hyves->getUploadStatus(
        $uploadToken['ip'], $uploadToken['token']);
        
    if($status->isDone($uploadToken['token'])) {
        $mediaId = $status->getMediaId($uploadToken['token']);
        break;
    }
}
Execute

Show me the code - Handling errors

try { 
    $response = $hyves->call('users.getLoggedIn');
    echo $response->firstname;
}
catch(MediaMonks_Service_Hyves_Request_Exception $e) {
    // error requesting the page, curl error nr & message
}
catch(MediaMonks_Service_Hyves_Response_Exception $e) {
    // error in response, hyves error code & message
}

Using it in production

Problem?

The story of the two logintokens

High server loads for larger campaigns

The big trick

Can we move our load to the client...?



The big trick - Tryvertising campaigns

Use 2 different consumers:


The big trick - Regular campaigns

Everything client side

Negotiating with Hyves

Building another library

Show me the code - Startup

<script type="text/javascript" src="hyves.js"></script>
<script type="text/javascript">
// your consumer key and consumer secret
var hyves = new Hyves('key', 'secret');

// set Europe/Amsterdam timestamp, same as Hyves
hyves.setRealTime(<?php echo time(); ?>);

// the user's access token
hyves.setToken('token', 'token secret');
</script>
                

Show me the code - Authentication using a popup

// close self if we act as the popup
var oauthToken = hyves.getQueryParamValue('oauth_token');
if(oauthToken !== null) {
    window.opener.hyves.hyvesAuth.complete();
}
hyves.requestAuthorization(
    ['users.getLoggedin', 'search.find', 'users.get'], // methods
    function() { // accept callback
        hyves.call('users.getLoggedin', function(response) {
            response.get('firstname'); // semi magic
        });
    },
    function(e) { // cancel callback
    },
    {'expiration': 'infinite'} // options
);
Execute

Show me the code - Batch processing

hyves.startBatch();
hyves.call('users.getLoggedin');
hyves.call('search.find', {'userid': '0(userid)', 'searchterms': 'van', 'nrresults': 3, 'categories': 'friends'});
hyves.call('users.get', {'userid': '1(userid)'});
hyves.flushBatch(function(batchResponse) {
    var friends = batchResponse.getResponse(2);
    for(i = 0, l = friends.countResults('user'); i < l; i++) {
    	friends.get('user', i, 'firstname');
    }
});
Execute

Common pitfalls

Results

‘Mobile is Ready’

Problem?

To sum up

Download

That's it, thanks


Download code and examples from:


More about MediaMonks?