# value of POST variable in PHP CURL - php

I'm creating a function to untilize NameCheap's API for registering domain names. The registration process worked out smoothly, now I'm looking to set the proper DNS Hosts.
When I create a pure POST request with something like POSTMAN this works fine and returns the expected XML response. However when I try to pass the data through PHP's CURL functions it breaks. I've narrowed the problem the the '#' symbol that needs to be passed to the DNS Host. If i put anything else there the request goes through. I've tried to url_encode the symbol but the API does not accept that.
Any suggestions?
public function setDNSHost($name, $server){
list($domain,$tld) = explode('.',$name,2);
$request = $this->request_URL;
$curl = curl_init();
$args['ApiUser'] = $this->API_User;
$args['ApiKey'] = $this->API_Key;
$args['UserName'] = $this->API_User;
$args['Command'] = 'namecheap.domains.dns.setHosts';
$args['ClientIP'] = $this->Client_IP;
$args['SLD'] = $domain;
$args['TLD'] = $tld;
$args['HostName1'] = utf8_encode('#');
$args['RecordType1'] = 'A';
$args['Address1'] = $server;
$args['HostName2'] = 'www';
$args['RecordType2'] = 'CNAME';
$args['Address2'] = $name;
$args['HostName3'] = '*';
$args['RecordType3'] = 'CNAME';
$args['Address3'] = $name;
curl_setopt_array($curl, array(
CURLOPT_URL => $request,
CURLOPT_USERAGENT => 'API',
// CURLOPT_FAILONERROR => 1,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $args,
CURLOPT_TIMEOUT => 15
));
$response = curl_exec($curl);
curl_close($curl);
// $oXML = new SimpleXMLElement($response);
return $response;
}

Some caracters are not allowed to be in the string. To avoid such problems you could use http_build_query on your data before you use the curl function.

Related

Coinmarketcap API Call with PHP

I tried my first API call but something is still wrong. I added my API-Key, choose the symbol and tried to echo the price. But it is still not valid. But my echo is still 0. Maybe someone show me what i did wrong. Thank you!
<?php
$coinfeed_coingecko_json = file_get_contents('https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?symbol=ETH');
$parameters = [
'start' => '1',
'limit' => '2000',
'convert' => 'USD'
];
$headers = [
'Accepts: application/json',
'X-CMC_PRO_API_KEY: XXX'
];
$qs = http_build_query($parameters); // query string encode the parameters
$request = "{$url}?{$qs}"; // create the request URL
$curl = curl_init(); // Get cURL resource
// Set cURL options
curl_setopt_array($curl, array(
CURLOPT_URL => $request, // set the request URL
CURLOPT_HTTPHEADER => $headers, // set the headers
CURLOPT_RETURNTRANSFER => 1 // ask for raw response instead of bool
));
$response = curl_exec($curl); // Send the request, save the response
print_r(json_decode($response)); // print json decoded response
curl_close($curl); // Close request
$coinfeed_json = json_decode($coinfeed_coingecko_json, false);
$coinfeedprice_current_price = $coinfeed_json->data->{'1'}->quote->USD->price;
?>
<?php echo $coinfeedde = number_format($coinfeedprice_current_price, 2, '.', ''); ?>
API Doc: https://coinmarketcap.com/api/v1/#operation/getV1CryptocurrencyListingsLatest
There is a lot going on in your code.
First of all $url was not defined
Second of all you made two requests, one of which I have removed
Third; you can access the json object by $json->data[0]->quote->USD->price
Fourth; I removed the invalid request params
I have changed a few things to make it work:
$url = "https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest";
$headers = [
'Accepts: application/json',
'X-CMC_PRO_API_KEY: ___YOUR_API_KEY_HERE___'
];
$request = "{$url}"; // create the request URL
$curl = curl_init(); // Get cURL resource
// Set cURL options
curl_setopt_array($curl, array(
CURLOPT_URL => $request, // set the request URL
CURLOPT_HTTPHEADER => $headers, // set the headers
CURLOPT_RETURNTRANSFER => 1 // ask for raw response instead of bool
));
$response = curl_exec($curl); // Send the request, save the response
$json = json_decode($response);
curl_close($curl); // Close request
var_dump($json->data[0]->quote->USD->price);
var_dump($json->data[1]->quote->USD->price);

Using curl instead of http request 2 in PHP

I'm trying to use curl instead of the http request 2 pear module in PHP to query the plivo api. They have an existing library for easily making calls to their API but it uses a pear module called http request2. I don't really know how to install a pear module on a server so I thought of just rewriting some parts of their library to just use curl.
Here's the part of their code that I specifically want to modify:
function __construct($auth_id, $auth_token, $url="https://api.plivo.com", $version="v1") {
if ((!isset($auth_id)) || (!$auth_id)) {
throw new PlivoError("no auth_id");
}
if ((!isset($auth_token)) || (!$auth_token)) {
throw new PlivoError("no auth_token");
}
$this->version = $version;
$this->api = $url."/".$this->version."/Account/".$auth_id;
$this->auth_id = $auth_id;
$this->auth_token = $auth_token;
}
private function request($method, $path, $params=array()) {
$url = $this->api.rtrim($path, '/').'/';
if (!strcmp($method, "POST")) {
$req = new HTTP_Request2($url, HTTP_Request2::METHOD_POST);
$req->setHeader('Content-type: application/json');
if ($params) {
$req->setBody(json_encode($params));
}
} else if (!strcmp($method, "GET")) {
$req = new HTTP_Request2($url, HTTP_Request2::METHOD_GET);
$url = $req->getUrl();
$url->setQueryVariables($params);
} else if (!strcmp($method, "DELETE")) {
$req = new HTTP_Request2($url, HTTP_Request2::METHOD_DELETE);
$url = $req->getUrl();
$url->setQueryVariables($params);
}
$req->setAdapter('curl');
$req->setConfig(array(
'timeout' => 30,
'ssl_verify_peer' => FALSE,
));
$req->setAuth($this->auth_id, $this->auth_token, HTTP_Request2::AUTH_BASIC);
$req->setHeader(array(
'Connection' => 'close',
'User-Agent' => 'PHPPlivo',
));
$r = $req->send();
$status = $r->getStatus();
$body = $r->getbody();
$response = json_decode($body, true);
return array("status" => $status, "response" => $response);
}
public function get_account($params=array()) {
return $this->request('GET', '', $params);
}
And here's the code that I have so far:
<?php
$curl = curl_init();
$curl_options = array(
CURLOPT_URL => 'https://api.plivo.com/v1/Account/',
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_USERPWD => 'auth_id:auth_token',
CURLOPT_HTTPHEADER => array("Connection: close", "User-Agent: PHPPlivo"),
CURLOPT_TIMEOUT => 30
);
curl_setopt_array($curl, $curl_options);
$response = curl_exec($curl);
curl_close($curl);
?>
I don't really know what's going on behind the scenes but this specific code is telling me that its using basic authentication using the values for the auth id and auth token:
$req->setAuth($this->auth_id, $this->auth_token, HTTP_Request2::AUTH_BASIC);
So I also set it using curl:
CURLOPT_USERPWD => 'auth_id:auth_token',
I'm pretty much stuck. All I get as a respose is the following:
{
"error": "not found"
}
It doesn't really make much sense into what I have missed or done wrong. Please help. Thank you in advance!
Below are the things you need to handle to sync your new code with old one:
If you are using GET method
CURLOPT_URL => 'https://api.plivo.com/v1/Account/'.http_build_query($params),
CURLOPT_HTTPHEADER => array("User-Agent: PHPPlivo"),
If you are using POST method
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query($params),
CURLOPT_HTTPHEADER => array("Content-type: application/json", "User-Agent: PHPPlivo"),
Yea... The PEAR dependency is definitely overkill for Plivo's wrapper. So that was one of the first modifications I made to the code.
Check out:
https://github.com/ashbeats/Plivo-Curl-Based-Wrapper/
Only difference is the RestAPI::request() method.

change siteid in ebay API call

I need to connect with the eBay motors site using a function in openbay which is an opencart extension. The site id for eBay motors is 100, but for the life of me I cannot get it to change with the way this function is written, am I missing something here???
API function call
public function openbay_call($call, array $post = NULL, array $options = array(), $content_type = 'json', $statusOverride = false){
if(defined("HTTPS_CATALOG")){
$domain = HTTPS_CATALOG;
}else{
$domain = HTTPS_SERVER;
}
$data = array(
'token' => $this->token,
'language' => $this->config->get('openbay_language'),
'secret' => $this->secret,
'server' => $this->server,
'domain' => $domain,
'openbay_version' => (int)$this->config->get('openbay_version'),
'data' => $post,
'content_type' => $content_type
);
$defaults = array(
CURLOPT_POST => 1,
CURLOPT_HEADER => 0,
CURLOPT_URL => $this->url.$call,
CURLOPT_USERAGENT => "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1",
CURLOPT_FRESH_CONNECT => 1,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_FORBID_REUSE => 1,
CURLOPT_TIMEOUT => 0,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_POSTFIELDS => http_build_query($data, '', "&")
);
$ch = curl_init();
curl_setopt_array($ch, ($options + $defaults));
if( ! $result = curl_exec($ch)){
$this->log('openbay_call() - Curl Failed '.curl_error($ch).' '.curl_errno($ch));
}
curl_close($ch);
/* There may be some calls we just dont want to log */
if(!in_array($call, $this->noLog)){
$this->log('openbay_call() - Result of : "'.$result.'"');
}
/* JSON RESPONSE */
if($content_type == 'json'){
$encoding = mb_detect_encoding($result);
/* some json data may have BOM due to php not handling types correctly */
if($encoding == 'UTF-8') {
$result = preg_replace('/[^(\x20-\x7F)]*/','', $result);
}
$result = json_decode($result, 1);
$this->lasterror = $result['error'];
$this->lastmsg = $result['msg'];
if(!empty($result['data'])){
return $result['data'];
}else{
return false;
}
/* XML RESPONSE */
}elseif($content_type == 'xml'){
$result = simplexml_load_string($result);
$this->lasterror = $result->error;
$this->lastmsg = $result->msg;
if(!empty($result->data)){
return $result->data;
}else{
return false;
}
}
}else{
$this->log('openbay_call() - OpenBay not active');
$this->log('openbay_call() - Data: '.serialize($post));
}
}
predefined parameters within the class - probably don't help but included anyways.
public function __construct($registry) {
$this->registry = $registry;
$this->token = $this->config->get('openbaypro_token');
$this->secret = $this->config->get('openbaypro_secret');
$this->logging = $this->config->get('openbaypro_logging');
$this->tax = $this->config->get('tax');
$this->server = 1;
$this->lasterror = '';
$this->lastmsg = '';
}
the function call
$this->data['test_category_features'] = $this->ebay->openbay_call('listing/getCategoryFeatures/', array('id' => 35618));
Everything works but how would i get this to change siteid to 100, the only way I can figure it out is to re-write my own API call class, but the client is paying for the subscription to openbay and wants to use the API calls through them, so I have to use there function. Im trying to return eBay motors category features so he can list them the same way he has been for years "used parts". If you don't switch to the eBay motors site id "100" then it will not return the category variations needed or more less accept the categories when trying to add products to eBay through the opencart extension.
Any advice would be greatly appreciated, really stuck here!!! Thanks in advance :)
according to this page: http://developer.ebay.com/DevZone/merchandising/docs/Concepts/SiteIDToGlobalID.html you need to add "... X-EBAY-SOA-GLOBAL-ID HTTP header for each API call" so add that to the curl options.

Restful API for CakePHP 2

I am creating a Restful WebService with CakePHP 2 however, i am getting 500 Internal Server Error since i am not able to capture Post Data. The Rest Server is as below:
App::import ( 'Vendor', 'ExchangeFunctions', array ('file'=> 'exchange/exchangefunctions.php'));
class ExchangeController extends AppController
{
public $components = array('RequestHandler');
public
function index()
{
$exchange = new ExchangeFunctions();
$data = $this->request->data('json_decode');
$exchange->username = $_POST['username'];
$exchange->password = $_POST['password'];
$emailList = $exchange->listEmails();
$response = new stdClass();
$response->emailList = $emailList;
foreach($emailList->messages as $listid => $email)
{
$tempEmail = $exchange->getEmailContent(
$email->Id,
$email->ChangeKey,
TRUE,
$_POST['attachmentPath']
);
$response->emails[$tempEmail['attachmentCode']] = $tempEmail;
}
$this->set('response', $response);
$this->set('_serialize','response');
}
}
and the client goes as:
class ApitestController extends AppController
{
Public function index()
{
$this->layout = 'ajax';
$jRequestURLPrefix = 'http://localhost/EWSApi/';
$postUrl = $jRequestURLPrefix."exchange/index.json";
$postData = array(
'username' => 'username',
'password' => 'password',
'attachmentPath'=> $_SERVER['DOCUMENT_ROOT'] . $this->base . DIRECTORY_SEPARATOR . 'emailDownloads' . DIRECTORY_SEPARATOR . 'attachments'
);
$postData = json_encode($postData);
pr($postData);
$ch = curl_init( $postUrl );
$options = array(
CURLOPT_RETURNTRANSFER=> true,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'Content-Length: ' . strlen($postData)
),
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_POSTFIELDS => $postData,
);
curl_setopt_array( $ch, $options );
$jsonString = curl_exec($ch);
curl_close($ch);
$data = json_decode($jsonString, FALSE);
echo $jsonString;
}
}
Not sure where i am messing up! Please help!
Ok, after a second look there are some more suspicious things. As already mentioned, your CURL request uses GET instead of POST.
$options = array(
...
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => $postData,
);
Another thing is that you are encoding the POST data for your CURL call to JSON, but then you are trying to access it on the other side using $_POST, however there won't be anything, POST data would have to be key/value query string formatted in order to appear in $_POST. You have to read php://input instead, which may be what you were trying to do with
$data = $this->request->data('json_decode');
However you must use CakeRequest::input() for that purpose, and of course you must then use the $data variable instead of $_POST
$data = $this->request->input('json_decode');
$exchange->username = $data['username'];
$exchange->password = $data['password'];
....
$tempEmail = $exchange->getEmailContent(
$email->Id,
$email->ChangeKey,
TRUE,
$data['attachmentPath']
);
Also make double sure that your CURL request looks like expected:
$options = array(
...
CURLOPT_POSTFIELDS => $postData,
CURLINFO_HEADER_OUT => true // supported as of PHP 5.1.3
);
curl_setopt_array($ch, $options);
$result = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
echo '<pre>';
print_r($info);
echo '</pre>';

Box-api V2 upload file curl php returns false

I´m trying to upload a file from PHP via Box-API v2 and I only get a boolean false response.
I think this is caused by CURL, not Box-API but I was fighting the last five hours, and I can´t find the solution. Any idea??
The implicated code is that:
note: the file exists and is accessible from code and the token is ok (other calls to API work fine)
const CONTENT_ENDPOINT = 'https://api.box.com/2.0/';
$file = "unexeceles.xlsx";
private $defaultOptions = array(
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_VERBOSE => true,
CURLOPT_HEADER => true,
CURLINFO_HEADER_OUT => false,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => false,
);
public function putFile($file) {
$options = $this->defaultOptions;
$options[CURLOPT_HTTPHEADER] = array ("Authorization: Bearer ".$this->token);
$options[CURLOPT_POST] = true;
$postfields = array();
$postfields["filename"] = '#'.$file;
$postfields["parent_id"] = 0;
$options[CURLOPT_POSTFIELDS] = $postfields;
$handle = curl_init(BoxConfig::CONTENT_ENDPOINT."files/content");
curl_setopt_array($handle, $options);
$response = curl_exec($handle);
curl_close($handle);
if (is_string($response)) {
$response = $this->parse($response);
}
return $response;
}
Finally I've found the solution.
The problem was the relative path to the file, the file exists and it´s accessible form code, but CURL seems to need the entire path to the file.
Very helpful the function curl_errno($handle)
if(curl_errno($handle)) {
echo 'Curl error: ' . curl_error($handle);
}

Categories