I'm trying to develop a Telegram Bot in PHP, but I failed to make my bot answer the user when he press an inline button.
Can someone help me sending a message (sendMessage method) after calling the answerCallback method?
Here's my last trial code:
if ($call_back_query != null) {
$response = $call_back_query;
$botUrl = "https://api.telegram.org/bot" . BOT_TOKEN . "/answerCallbackQuery";
$postFields = array('callback_query_id' => $call_back_id, 'text' => $response);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:multipart/form-data"));
curl_setopt($ch, CURLOPT_URL, $botUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
$output = curl_exec($ch);
//send Text
$response = "help me if you can, i'm feeling down";
header("Content-Type: application/json");
$parameters = array('chat_id' => $chatId, "text" => $response);
$parameters["method"] = "sendMessage";
echo json_encode($parameters);
}
Ok, I've understood the problem:
In sendText I have to use $call_back_from instead of $chatId, because he's answering to the callback query and not a simple message (I think so...)
While
$chatId = isset($message['chat']['id']) ? $message['chat']['id'] : "";
$call_back_from = isset ($update['callback_query']['from']['id']) ? $update['callback_query']['from']['id'] : "";
The code will be
if ($call_back_query != null) {
$response = $call_back_query;
$botUrl = "https://api.telegram.org/bot" . BOT_TOKEN . "/answerCallbackQuery";
$postFields = array('callback_query_id' => $call_back_id, 'text' => $response);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:multipart/form-data"));
curl_setopt($ch, CURLOPT_URL, $botUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
$output = curl_exec($ch);
//send Text
$response = "help me if you can, i'm feeling down";
header("Content-Type: application/json");
$parameters = array('chat_id' => $call_back_from, "text" => $response);
$parameters["method"] = "sendMessage";
echo json_encode($parameters);
}
Hope this could be helpful!
Have a nice try!
Related
I'm trying to validate api data with POST request using cURL but getting no response.
API documentation
<?php
$url = "https://widget.packeta.com/v6/api/pps/api/widget/validate";
$data = array(
"Parameters" => array(
"apiKey" => "XXXXXX",
"id" => "9346",
)
);
$encoded = json_encode($data);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $encoded);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$resp = curl_exec($ch);
$decoded = json_decode($resp);
print_r($decoded);
curl_close($ch);
?>
Does anyone know what is wrong?
SOLUTION:
Turns out i was missing CURL_HTTPHEADER.
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type: application/json",
"Accept: application/json"
));
Try to write:
$ch = curl_init();
instead of :
$ch = curl_init($url);
Eventualy you can use a try ... catch to get the error:
<?php
// Define variables
define('API_KEY', 'XXXXXX');
$url = "https://widget.packeta.com/v6/api/pps/api/widget/validate";
$id = "9346";
// Prepare data
$data = array(
"Parameters" => array(
"apiKey" => API_KEY,
"id" => $id,
)
);
$encoded = json_encode($data);
try {
// Initialize cURL
$ch = curl_init();
// Set cURL options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $encoded);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute cURL request
$resp = curl_exec($ch);
if($resp === false) {
throw new Exception(curl_error($ch));
}
// Decode response and print it
$decoded = json_decode($resp);
print_r($decoded);
// Close cURL session
curl_close($ch);
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage();
}
?>
I'm getting error : Missing or incorrectly formatted payload
I'm generating device token from Apple DeviceCheck API in swift language with real device and also passing Transaction ID to this php api.
jwt token generating successfully with this code but further code not working with apple query bit api.
This is my server side code in php :
<?php
require_once "vendor/autoload.php";
use Zenstruck\JWT\Token;
use Zenstruck\JWT\Signer\OpenSSL\ECDSA\ES256;
use \Ramsey\Uuid\Uuid;
$deviceToken = (isset($_POST["deviceToken"]) ? $_POST["deviceToken"] : null);
$transId = (isset($_POST["transId"]) ? $_POST["transId"] : null);
function generateJWT($teamId, $keyId, $privateKeyFilePath) {
$payload = [
"iss" => $teamId,
"iat" => time()
];
$header = [
"kid" => $keyId
];
$token = new Token($payload, $header);
return (string)$token->sign(new ES256(), $privateKeyFilePath);
}
$teamId = "#####";// I'm passing My team id
$keyId = "#####"; // I'm passing my key id
$privateKeyFilePath = "AuthKey_4AU5LJV3.p8";
$jwt = generateJWT($teamId, $keyId, $privateKeyFilePath);
function postReq($url, $jwt, $bodyArray) {
$header = [
"Authorization: Bearer ". $jwt
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $bodyArray); //Post Fields
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
// curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
// curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$server_output = curl_exec($ch);
//$info = curl_getinfo($ch);
// print_r($info);
//echo 'http code: ' . $info['http_code'] . '<br />';
//echo curl_error($ch);
curl_close($ch);
return $server_output;
}
$body = [
"device_token" => $deviceToken,
"transaction_id" => $transId,
"timestamp" => ceil(microtime(true)*1000)
];
$myjsonis = postReq("https://api.development.devicecheck.apple.com/v1/query_two_bits", $jwt, $body);
echo $myjsonis;
?>
Where is problem in this code? Or any other solution in php code.
Is there anything that I'm missing.
I just checked the Docs. They don't want POST fields like a form, they want a JSON body instead. Here's a snippet of code that you should be able to tweak to do what you require:
$data = array("name" => "delboy1978uk", "age" => "41");
$data_string = json_encode($data);
$ch = curl_init('http://api.local/rest/users');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);
Actually, looking again at your code, it could be as simple as running json_encode() on your array.
I am trying to delete a deal using through the API. The code I have written is below , but its not working. I am not able to figure out where to add the Method "DELETE" while making the call.I am not getting any error message in output. Please suggest.
<?php
$api_token = "myapitoken";
$url = "https://api.pipedrive.com/v1/deal?api_token=" . $api_token;
$deal = array(
'id' => 375,
'method' => 'DELETE'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $deal);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
$result = json_decode($output);
?>
Deleting deal on pivedrive can be done using following code
$id= "deal_id";
$url = "https://api.pipedrive.com/v1/deals/". $id ."?api_token=" . $api_token;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
Your api token is a postfield too.
Maybe this way:
$url = "https://api.pipedrive.com/v1/deal";
$deal = array(
'api_token'=> $api_token,
'id' => 375,
'method' => 'DELETE'
);
Please tell me what I am missing here? I keep getting error 404, file not found
$apiKey = "MY-KEY-IS-HERE";
$apiUri = "https://www.googleapis.com/language/translate/v2";
$text = "Hello world";
$source = "EN";
$target = "NL";
if (!$target || !$text) {
echo "Noting to translate";
} else {
$fields = array(
"key" => $apiKey,
"source" => $source,
"target" => $target,
"q" => $text
);
$fieldsString = "";
foreach($fields as $key=>$value) {
$fieldsString .= $key . '=' . $value . '&';
}
rtrim($fieldsString, '&');
echo $fieldsString;
$handle = curl_init($apiUri);
curl_setopt($handle, CURLOPT_URL, $apiUri);
curl_setopt($handle, CURLOPT_POST, true);
curl_setopt($handle, CURLOPT_POSTFIELDS, $fieldsString);
curl_setopt($handle, CURLOPT_HTTPHEADER, array('Content-Length: ' . strlen($fieldsString)));
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($handle);
$responseCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
if($responseCode != 200) {
echo 'Fetching translation failed! Server response code: ' . $responseCode . '<br>';
echo $response;
}
else {
echo $response;
}
curl_close($handle);
When I put at CURL_POSTFIELDS the $string array, nothing changes. Also tried adding a ? mark in the URI or added a trailing slash. Keep getting the same errors. For testing I also removed the lines:
curl_setopt($handle, CURLOPT_POSTFIELDS, $fieldsString);
curl_setopt($handle, CURLOPT_HTTPHEADER, array('Content-Length: ' . strlen($fieldsString)));
And then got an error saying that length is missing in the headers. Which would say it reaches the api correctly..???
GOT IT TO WORK LIKE THIS:
$apiKey = "MY-KEY-IS-HERE";
$apiUri = "https://www.googleapis.com/language/translate/v2";
$text = "Hello world";
$source = "EN";
$target = "NL";
if (!$target || !$text) {
echo "Noting to translate";
exit;
} else {
$fields = array(
"key" => $apiKey,
"source" => $source,
"target" => $target,
"q" => $text
);
$handle = curl_init();
curl_setopt($handle, CURLOPT_URL, $apiUri);
curl_setopt($handle, CURLOPT_POST, true);
curl_setopt($handle, CURLOPT_POSTFIELDS, $fields);
curl_setopt($handle, CURLOPT_HTTPHEADER, array("X-HTTP-Method-Override: GET"));
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($handle);
$responseDecoded = json_decode($response, true);
$responseCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
if($responseCode != 200) {
echo 'Fetching translation failed! Server response code: ' . $responseCode . '<br>';
echo $response;
}
else {
echo $responseDecoded['data']['translations'][0]['translatedText'];
}
curl_close($handle);
You waste a lot of time doing stuff that CURL can do for you automatically, and far more reliably:
$handle = curl_init($apiUri);
curl_setopt($handle, CURLOPT_URL, $apiUri); // redundant
You've already set the URI via curl_init(), there's NO point in setting it yet again.
Then you also build your own post body, set content-length, blah blah blah. Skip all of that. All you need is
$fields = array(
"key" => $apiKey,
"source" => $source,
"target" => $target,
"q" => $text // note LACK of urlencode here
);
curl_setopt($handle, CURLOPT_POSTFIELDS, $fields);
CURL will happily take your array and transform it as necessary, and set whatever appropriate headers as well.
I have looked over the code many times but whenever I send request to API it returns "message":"invalid signature"
I am thinking it has to do with hashing the body, possibly. I'm new to PHP and its my first project. :)
Anyone see an error? Thanks.
<?php
$arr = array('size' => ".01", 'price' => '240', 'side' => 'sell',
'product_id' => 'BTC-USD');
$output = json_encode($arr);
echo json_encode($arr)."<br/>";
$key = "f23612b06cb4d020cda7e04b1ae6ef9a";
$secret = "RENqodtuTCn4v7g7Pn/FFdQAIKReVXGayNPrNN/Zb7AjATI0hP4R0MCDD5RqnDu60qTZ5Qry329fFu7kcObGBw==";
$passphrase = "tradebot";
$time = time();
$url = "https://api.gdax.com/orders";
$data = $time."POST"."/orders";
echo $data . "<br/>";
$hashinput = "$output"."$data";
$sign = base64_encode(hash_hmac("sha256", $hashinput, base64_decode($secret), true));
echo $sign . "<br/>";
$headers = array(
'CB-ACCESS-KEY: '.$key,
'CB-ACCESS-SIGN: '.$sign,
'CB-ACCESS-TIMESTAMP: '.$time,
'CB-ACCESS-PASSPHRASE: '.$passphrase,
'Content-Type: application/json'
);
var_dump($headers);
echo $url;
static $ch = null;
if (is_null($ch)) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'local server');
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, $output);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$res = curl_exec($ch);
echo $res;
}
replace
$hashinput = "$output"."$data";
with
$hashinput = "$data"."$output";
and replace
curl_setopt($ch, CURLOPT_POST, $output);
with
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $output);
(from Coinbase Community forum)