Skip to content

Instantly share code, notes, and snippets.

@gaishimo
Last active August 29, 2015 13:57
Show Gist options
  • Save gaishimo/9404059 to your computer and use it in GitHub Desktop.
Save gaishimo/9404059 to your computer and use it in GitHub Desktop.
Conyac API PHP Client
<?php
/**
* Conyac API Client for PHP
* @author gaishimo
*/
class Conyac{
private $apiDomain;
private $clientId;
private $clientSecret;
private $accessToken;
private static $AUTH_ENDPOINT = 'oauth/authorize';
private static $TOKEN_ENDPOINT = 'oauth/token';
public static $CURL_OPTS = array(
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_USERAGENT => 'conyac-php-1.0'
);
/**
* @param array $config
* clientId: Consumer Key(Application ID)
* clientSecret: Consumer Secret
* apiDomain: "https://biz.dev-conyac.com/" or "https://biz.conyac.cc/"
* redirectUri: URI after Authentication,
*/
public function __construct($config) {
$this->clientId = $config['clientId'];
$this->clientSecret = $config['clientSecret'];
$this->apiDomain = $config['apiDomain'];
$this->redirectUri = $config['redirectUri'];
}
/**
* Do a HTTP GET request
* @param string $endPoint API endpoint. ex: "/api/v1/my".
* @param array $params : Request parameters.
* @param array $config see makeRequest()
*/
public function get($endPoint, $params = null, $config = array()){
$config = array_merge( $config, array( "method" => "get" ) );
return $this->makeRequest($endPoint, $config);
}
/**
* Do a HTTP POST request
* @param string $endPoint API endpoint. ex: "/api/v1/my".
* @param array $params : Request parameters.
* @param array $config see makeRequest()
*/
public function post( $endPoint, $params = null, $config = array() ){
$config = array_merge( $config, array( "method" => "post" ) );
return $this->makeRequest($endPoint, $params, $config);
}
/**
* Do a HTTP request (GET, POST)
* @param string $endPoint API endpoint. ex: "/api/v1/my".
* @param array $params Request parameters.
* @param array $config
* method : HTTP method (GET, POST)
* headers : HTTP headers
*/
public function makeRequest($endPoint, $params, $config = array()){
$configDefault = array(
"method" => "get",
"headers" => array()
);
$config = array_merge($configDefault, $config);
$params['access_token'] = $this->accessToken;
$method = $config["method"];
$curlOpts = self::$CURL_OPTS;
$url = $this->apiDomain . $endPoint;
if( strcasecmp( $method, 'post' ) === 0 ){
$curlOpts[CURLOPT_POST] = true;
if ( self::includesFile($params) === false ){
$curlOpts[CURLOPT_POSTFIELDS] = json_encode($params);
$config["headers"][] = 'Content-Type: application/json';
}else{
$curlOpts[CURLOPT_POSTFIELDS] = $params;
}
}
if( strcasecmp( $method, 'get' ) === 0 ){
$query = http_build_query($params, null, '&');
$url .= "?" . $query;
}
$curlOpts[CURLOPT_VERBOSE] = true;
$curlOpts[CURLOPT_URL] = $url;
$curlOpts[CURLOPT_HTTPHEADER] = $config["headers"];
$ch = curl_init();
curl_setopt_array($ch, $curlOpts);
$result = curl_exec($ch);
$contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
if ( $curlError = curl_error($ch) ) {
throw new Exception($curlError, Exception::CURL_ERROR);
}
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ( $httpCode >= 400 ){
throw new Exception("status : $httpCode. " . $result);
}
$jsonDecodedResult = json_decode( $result, true );
return $jsonDecodedResult;
}
public function getAuthenticationUrl(){
$params = array(
'client_id' => $this->clientId,
'redirect_uri' => $this->redirectUri,
'response_type' => 'code'
);
$query = http_build_query($params, null, '&');
return $this->apiDomain . self::$AUTH_ENDPOINT . '?' . $query;
}
public function getAccessToken($code){
$url = $this->apiDomain . self::$TOKEN_ENDPOINT;
$params = array(
'client_id' => $this->clientId,
'client_secret' => $this->clientSecret,
'redirect_uri' => $this->redirectUri,
'grant_type' => 'authorization_code',
'code' => $code
);
$query = http_build_query($params, null, '&');
$curlOpts = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $query,
CURLOPT_URL => $url
);
$ch = curl_init();
curl_setopt_array($ch, $curlOpts);
$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
if ($curlError = curl_error($ch)) {
throw new Exception($curlError, Exception::CURL_ERROR);
} else {
$jsonDecodedResult = json_decode($result, true);
}
curl_close($ch);
$this->accessToken = $jsonDecodedResult["access_token"];
return $this->accessToken;
}
public static function includesFile($data){
foreach($data as $key => $value) {
if($value instanceof CurlFile){
return true;
}
}
return false;
}
}
?>
<?php
require('conyac.php');
const CLIENT_ID = 'xxxxxxx'; // Set your Consumer Key(Application ID)
const CLIENT_SECRET = 'xxxxxxx'; // Set your Consumer Secret
const REDIRECT_URI = 'http://conyac-client.localhost/sample.php'; //Set the redirect uri after the authentication
const API_DOMAIN = 'https://biz.dev-conyac.com/';
$conyac = new Conyac(
array(
"clientId" => CLIENT_ID,
"clientSecret" => CLIENT_SECRET,
"redirectUri" => REDIRECT_URI,
"apiDomain" => API_DOMAIN
)
);
if (!isset($_GET['code'])){
$auth_url = $conyac->getAuthenticationUrl();
header('Location: ' . $auth_url);
die('Redirect');
} else {
try{
$conyac->getAccessToken( $_GET['code']);
//API example: アカウント情報の取得
$account = $conyac->get('api/v1/my');
echo "<pre>"; var_dump($account); echo "</pre>";
/*
//API example: POST (新規翻訳依頼の作成)
$params = array(
"organization_id" => $account["default_organization_id"],
"language_id" => "ja",
"translated_language_id" => "en",
"questions" => array(
array(
"type" => "string",
"title" => "Hello Conyac!",
"body" => "Conyac APIは認証にOAuth 2.0をもちいたRESTfulなWebサービスとして実装されています。\n\n翻訳依頼に必要な各機能へのアクセスは直感的なURLやパラメータを用いています。",
"description" => "補足説明です。"
)
)
);
$res = $conyac->post('api/v1/projects', $params);
echo "<hr>";
echo "<pre>"; var_dump($res); echo "</pre>";
// exmple: POST (multipart)
$data = array( "file" => new CurlFile('/tmp/ja_utf8.txt', 'text/plain'));
$res = $conyac->post('api/v1/my/files', $data);
echo "<hr>";
echo "<pre>"; var_dump($res); echo "</pre>";
$organization = $conyac->get("api/v1/organizations/" . $account["default_organization_id"]);
echo "<pre>"; var_dump($organization); echo "</pre>";
*/
} catch(Exception $e){
echo $e->getMessage(), PHP_EOL;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment