Skip to content

Instantly share code, notes, and snippets.

@uptimizt
Last active January 28, 2018 18:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uptimizt/547a1687f4e1ef082b141b56720fa26f to your computer and use it in GitHub Desktop.
Save uptimizt/547a1687f4e1ef082b141b56720fa26f to your computer and use it in GitHub Desktop.
ex-amocrm-api-wrapper-wp
<?php
/**
* Request wrapper for API AmoCRM
*/
function wooac_request($ep = '', $method = 'GET', $data = array())
{
try {
$cookies = get_transient('wooac_cookies');
if(empty($cookies) and $ep != '/private/api/auth.php'){
wooac_request('/private/api/auth.php', 'POST');
$cookies = get_transient('wooac_cookies');
}
$url = 'https://' . get_option('wac_subdomain') . '.amocrm.ru' . $ep;
$url = add_query_arg('type', 'json', $url);
$login_data = array(
'USER_LOGIN' => get_option('wac_login'),
'USER_HASH' => get_option('wac_key')
);
$args = array(
'method' => $method,
'timeout' => '30',
);
if( empty($cookies)){
$args['body'] = $login_data;
} else {
$args['body'] = $login_data;
$args['cookies'] = $cookies;
}
do_action('logger_u7', $args);
$response = wp_remote_request( $url, $args );
if(wp_remote_retrieve_response_code($response) != 200){
throw new Exception('Ошибка ответа от сервера. Код: ' . wp_remote_retrieve_response_code($response));
}
if(isset($response["cookies"]) and $ep == '/private/api/auth.php'){
set_transient('wooac_cookies', $response["cookies"], MINUTE_IN_SECONDS * 14);
// do_action('logger_u7', ['set_transient-wooac_cookies'], $response["cookies"]);
return true;
}
$data = wp_remote_retrieve_body($response);
$data = json_decode($data, true);
return $data;
} catch (Exception $e) {
return new WP_Error( 'api_request_error', $e->getMessage() );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment