Skip to content

Instantly share code, notes, and snippets.

@ryanmcgrath
Created January 20, 2012 11:21
Show Gist options
  • Save ryanmcgrath/1646798 to your computer and use it in GitHub Desktop.
Save ryanmcgrath/1646798 to your computer and use it in GitHub Desktop.
Hitting the myGengo API from within Drupal.
<?php
// ...
// Use like...
// $this->requestFromGengo('translate/service/languages', 'GET');
// $this->requestFromGengo('translate/job', 'GET', array(
// 'id' => 1
// ));
// ...
public $apiURL = 'http://api.mygengo.com/v1.1/';
public $sandboxURL = 'http://api.sandbox.mygengo.com/v1.1/';
public $useSandbox = TRUE;
public function requestFromGengo($endpoint, $method, $data = array()) {
$options = array(
'headers' => array(
'User-Agent' => 'Drupal myGengo Translation Interface v0.1',
'Accept' => 'application/json'
),
'method' => $method
);
$timestamp = gmdate('U');
$url = ($this->useSandbox ? $this->sandboxURL : $this->apiURL) . $endpoint;
/**
* If it's a GET or DELETE request, just sign it and send it appropriately. PUT/POST
* get a little more annoying...
*/
if($method == 'GET' || $method == 'DELETE') {
$query_data = drupal_http_build_query(array_merge(array(
'api_key' => 'your_api_key',
'api_sig' => hash_hmac('sha1', $timestamp, 'your_api_private_key'),
'ts' => $timestamp
), $data));
$response = drupal_http_request($url .'?'. $query_data, $options);
} else {
$options['headers']['Content-Type'] = 'application/x-www-form-urlencoded';
$options['data'] = drupal_http_build_query(array(
'api_key' => 'your_api_key',
'api_sig' => hash_hmac('sha1', $timestamp, 'your_api_private_key'),
'ts' => $timestamp,
'data' => json_encode($data)
));
$response = drupal_http_request($url, $options);
}
$results = json_decode($response->data);
if($results->opstat == 'ok' && isset($results->response)) {
return $results->response;
} else {
// TODO: Raise an actual error. >_>
return array();
}
}
// ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment