Using the API here: https://dev.mention.com/resources/alert_mentions/#put-accounts-id-alerts-alert-id-mentions-mention-id
From what I understand, if I want to mark a specific "mention" as read, I do something like this:
$browser = new \Buzz\Browser(new \Buzz\Client\Curl);
$params = ['read' => true]; //tried this
$url = "https://api.mention.net/api/accounts/" . $this->getAccountId() . "/alerts/{$alert_id}/mentions/{$mention_id}";
if(!empty($params))
{
$url .= '?' . http_build_query($params); //i think this isnt needed because i pass $params below to the $browser->put but it was worth a try.
}
$response = $browser->put($url, array(
"Authorization: Bearer {$this->getAccessToken()}",
"Accept: application/json",
), $params);
if (200 != $response->getStatusCode()) {
return false;
}
However, when I run the code, it doesn't produce any errors and infact returns a valid response, but the "read" flag is still set to false.
Also tried:
$params = ['read' => 'true']; //tried this
$params = ['read' => 1]; //tried this
The Mention API accepts JSON in request bodies: https://dev.mention.com/#request-format
You can mark a mention as read like this:
$params = ['read' => true];
// params are json encoded
$params = json_encode($params);
$response = $browser->put($url, array(
"Authorization: Bearer $token",
"Accept: application/json",
// the Content-Type header is set to application/json
"Content-Type: application/json",
), $params);
Related
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);
I wanted to pass the whole incoming data (that is, $request) to the curl not wanted to post to a particular field in the endpoint as subjectId=>1 as am running this curl request for different endPoint everytime. The below curl request will work if CURLOPT_URL => $url . $subjectId, was given. As my input changes for every end point, i've to pass everything that comes in the input to the curl , i can't pass it as an arary $subjectId. Is there any way to do this?
Currently, dd($Response); returns null
Am giving a postman input like this:
{
"subjectId":"1"
}
Curl
public function getContentqApiPost(Request $request)
{
$token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.ey";
$headers = [
"Accept: application/json",
"Authorization: Bearer " . $token
];
$url="http://127.0.0.1:9000/api/courses/course-per-subject";
$subjectId = "?subjectId=$request->subjectId";
$ch = curl_init();
$curlConfig = array(
// CURLOPT_URL => $url . $subjectId,
CURLOPT_URL => $url . $request,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => $headers,
);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt_array($ch, $curlConfig);
$result = trim(curl_exec($ch));
$Response = json_decode($result, true);
if (curl_errno($ch)) {
$error_msg = curl_error($ch);
echo $error_msg;
}
curl_close($ch);
return $Response;
}
If you would like to pass all params of $request to curl:
$queryParams = '';
$delimeter = '?';
foreach($request->all() as $k => $v){
$queryParams .= "$delimeter$k=$v";
$delimeter = '&';
}
Also You can only pass the params you want:
foreach($request->only(['subjectId']) as $k => $v){
// code here
}
Finally you have:
CURLOPT_URL => $url . $queryParams,
Answer
Assuming you want to pass the entire GET query string as-is:
$query_string = str_replace($request->url(), "", $request->fullUrl());
$url = "http://localhost:9000/api/courses/course-per-subject" . $query_string;
This works because $request->url() returns the URL without the query string parameters, while $request->fullUrl() returns the URL with all the query string parameters, so we can use str_replace with an empty replacement to remove the non-query part. Note that $query_string will already start with a ? so there is no need to add that yourself.
Other suggestions
Unless your Laravel API is a 1:1 copy of the backend API, I strongly suggest writing a class that interfaces with the backend API, then provide it to your Laravel controllers using dependency injection. E.g.
class CourseCatalogApi {
public function getSubjectsInCourse(String $course){
... // your curl code here
}
}
Finally, since you are already using Laravel, there is no need to write such low level code using curl to make HTTP requests. Consider using guzzlehttp, which is already a dependency of Laravel.
I found a sample github that is able to properly generate a signature for the API in question, their code is as follows:
so i found their github which has a sample in object oriented like this:
if ($api === 'private') {
$this->check_required_credentials();
$timestamp = $this->seconds();
$xPhemexRequestExpiry = $this->safe_integer($this->options, 'x-phemex-request-expiry', 60);
$expiry = $this->sum($timestamp, $xPhemexRequestExpiry);
$expiryString = (string) $expiry;
$headers = array(
'x-phemex-access-token' => $this->apiKey,
'x-phemex-request-expiry' => $expiryString,
);
$payload = '';
if ($method === 'POST') {
$payload = $this->json($params);
$body = $payload;
$headers['Content-Type'] = 'application/json';
}
$auth = $requestPath . $queryString . $expiryString . $payload;
$headers['x-phemex-request-signature'] = $this->hmac($this->encode($auth), $this->encode($this->secret));
}
$url = $this->urls['api'][$api] . $url;
return array( 'url' => $url, 'method' => $method, 'body' => $body, 'headers' => $headers );
}
my code is core and looks like this, and I can not seem to get the proper result of a valid signature, any guidance possible?
$epoch=strtotime(date('r', time()).'+2 days');
$data = '{"clOrdId":"123456","ordType":"LIMIT","symbol":"BTC-USD","side":"BUY","orderQty":"0.1","price":"100"}';
$content=("/orders".$epoch.$data);
//SECRET KEY
$str = 'cn87t3Z8wLw-OR626cuAZFIUhHT2z3XSfEt6X8OBSyFjU3Ny05ZWYyLTQ3ZjItODkwNy1mODlhNWMxM2UzMWY';
$decode= base64_decode($str);
$signature = hash_hmac('SHA256',$content,'$decode');
In short I need to send the signature inside the headers like so:
"x-phemex-request-signature: $signature)",
UPDATED CODE:
$epoch=strtotime(date('r', time()).'+5 minutes');
$data = '{"clOrdId":"123456","ordType":"LIMIT","symbol":"BTC-USD","side":"BUY","orderQty":"0.1","price":"100"}';
$content="/orders".$epoch.$data;
//SECRET KEY
$str = 'cn87t3Z8wLw-OR626cuAZFIUhHT2z3XSfEt6X8OBSyFkMjE0NjU3Ny05ZWYyLTQ3ZjItODkwNy1mODlhNWMxM2UzMWY';
$signature = hash_hmac('SHA256',$auth,'cn87t3Z8wLw-OR626cuAZFIUhHT2z3XSfEt6X8OBSy***5ZWYyLTQ3ZjItODkwNy1mODlhNWMxM2UzMWY');
$headers = array(
"accept: application/json",
//API KEY
"x-phemex-access-token:e92028ca-4704-4317-8149-c1c7a7f85226",
"Content-Type: application/json",
"x-phemex-request-expiry: $epoch",
//this right here is what we need to have working proper
"x-phemex-request-signature: $signature)",
);
The format of a proper signature looks like:
API REST Request URL: https://api.phemex.com/orders
Request Path: /orders
Request Query:
Request Body: {"symbol":"BTCUSD","clOrdID":"uuid-1573058952273","side":"Sell","priceEp":93185000,"orderQty":7,"ordType":"Limit","reduceOnly":false,"timeInForce":"GoodTillCancel","takeProfitEp":0,"stopLossEp":0}
Request Expiry: 1575735514
Signature: HMacSha256( /orders + 1575735514 + {"symbol":"BTCUSD","clOrdID":"uuid-1573058952273","side":"Sell","priceEp":93185000,"orderQty":7,"ordType":"Limit","reduceOnly":false,"timeInForce":"GoodTillCancel","takeProfitEp":0,"stopLossEp":0})
signed string is /orders1575735514{"symbol":"BTCUSD","clOrdID":"uuid-1573058952273","side":"Sell","priceEp":93185000,"orderQty":7,"ordType":"Limit","reduceOnly":false,"timeInForce":"GoodTillCancel","takeProfitEp":0,"stopLossEp":0}
I’m having a rough time getting a simple Oauth 1 api call to work. I’ve figured out how to access the data I want via Postman and have made successful calls for lists, starred items, etc. If I copy an already-run call from postman and rerun it locally, as long as the timestamp is the timeout time (3 minutes) the api will accept it and I’ll be able to receive and parse the json data.
I've tested and run all of the elements of the code in isolation and everything seems to work fine... What seems to not work is generating a proper signature.
Full code is below... Any help is appreciated!
<?php
// Include Manually Entered Credentials
include 'credentials.php';
####################################
// GENERATE TIMESTAMP:
$oathtimestamp = time();
// GENERATE NONCE:
function generateNonce() {
$length = 15;
$chars='1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM';
$ll = strlen($chars)-1;
$o = '';
while (strlen($o) < $length) {
$o .= $chars[ rand(0, $ll) ];
}
return $o;
}
$oathnonce = generateNonce();
####################################
// API Determinants
$APIurl = "https://www.example.com/api/";
####################################
// GENERATE Oath1 Signature:
$signatureMethod = "HMAC-SHA1";
$oathVersion = "1.0";
$base = "POST&".$APIurl."&"."folder_id=starred"."&limit=25"."&oauth_consumer_key=".$oauth_consumer_key."&oauth_nonce=".$oathnonce."&oauth_signature_method=".$signatureMethod."&oauth_timestamp=".$oathtimestamp."&oauth_token=".$oauth_token."&oauth_version=".$oathVersion."&x_auth_mode=client_auth"."&x_auth_password=".$x_auth_password."&x_auth_username=".$x_auth_username;
//echo $base;
$key = $oauth_consumer_key."&".$oath_tokenSecret;
//echo $key;
$signature = base64_encode(hash_hmac('sha1', $oauth_consumer_key, $key));
//echo $signature;
$oath_getstringlength =
"folder_id=starred".
"&limit=25".
"&oauth_consumer_key=".$oauth_consumer_key.
"&oauth_nonce=".$oathnonce.
"&oauth_signature=".$signature.
"&oauth_signature_method=".$signatureMethod.
"&oauth_timestamp=".$oathtimestamp.
"&oauth_token=".$oauth_token.
"&oauth_version=".$oathVersion.
"&x_auth_mode=client_auth".
"&x_auth_password=".$x_auth_password.
"&x_auth_username=".$x_auth_username;
$oath_stringlength = strlen($oath_getstringlength);
//echo $oath_stringlength;
####################################
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://www.example.com/api/",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS =>
"folder_id=starred".
"&limit=25".
"&oauth_consumer_key=".$oauth_consumer_key.
"&oauth_nonce=".$oathnonce.
"&oauth_signature=".$signature.
"&oauth_signature_method=".$signatureMethod.
"&oauth_timestamp=".$oathtimestamp.
"&oauth_token=".$oauth_token.
"&oauth_version=".$oathVersion.
"&x_auth_mode=client_auth".
"&x_auth_password=".$x_auth_password.
"&x_auth_username=".$x_auth_username,
CURLOPT_HTTPHEADER => array(
"Accept: */*",
"Accept-Encoding: gzip, deflate",
"Cache-Control: no-cache",
"Connection: keep-alive",
"Content-Length: $oath_stringlength",
"Content-Type: application/x-www-form-urlencoded",
"Host: www.example.com",
"User-Agent: curlAPICall",
"cache-control: no-cache"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "... cURL Error #:" . $err;
} else {
echo $response;
$jsonresponse = json_decode($response, true);
print_r($jsonresponse);
}
?>
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.