telegram callback_data is null in update array - php

I'm trying to make responce to user press inline_button2, after inline_keyboard apper in chat and I click on inline_button2 I suppose object callback_data have data with "callback_data"=>'inline2' but callback_data is null
see screenshot
$access_token = '...';
$api = 'https://api.telegram.org/bot' . $access_token;
$content = file_get_contents("php://input");
$update = json_decode($content, TRUE);
$callback_query = $update['CallbackQuery'];
$callback_data = $callback_query['data'];
$message = $update["message"];
$text = $message["text"];
$chatId = $message["chat"]["id"];
if (!isset($chatId)) {exit;}
switch($callback_data){
case 'inline2':
sendMessage($chatId, "inline2 pressed",null);
break;
default:
sendMessage($chatId, var_export($callback_query,TRUE),null);
break;
}
switch($text) {
case 'inline':
$inline_button1 = array("text"=>"inline1","url"=>"http://google.com", "callback_data"=>'inline1');
$inline_button2 = array("text"=>"inline2","callback_data"=>'inline2');
$inline_keyboard = array(array($inline_button1,$inline_button2));
$keyboard=array("inline_keyboard"=>$inline_keyboard);
sendMessage($chatId, "назад",$keyboard);
break;
}
function sendMessage($chat_id, $message, $replyMarkup) {
$s='';
if (isset($replyMarkup)) {
$s=json_encode($replyMarkup);
}
file_get_contents($GLOBALS['api'] . '/sendMessage?parse_mode=HTML&chat_id=' . $chat_id . '&disable_web_page_preview=true&text=' . urlencode($message) .'&reply_markup='.$s);
}

You are accessing the callback_query wrongly and additionally you need to take the chatId from the callback_query object.
$callback_query = $update['callback_query'];
$callback_data = callback_query["data"];
$chatId = callback_query["message"]["chat"]["id"];

change this $callback_query = $update['CallbackQuery']; to $callback_query = $update['callbackquery'];
you also need to add the following for callbackquery
$message_id = ['callback_query']['message']['message_id']; //callbackquery message id
$chat_id = $callback_query['message']['chat']['id']; // callbackquery chat id
i hope this helps

Related

square payment form php check customer exists in directory and make payment

Am new to Square Payment Form using PHP and trying to do following steps
Check If customer Exists in Directory
If Customer Does not exist - create new customer and collect CUSTOMER_ID
MAKE PAYMENT & get Payment ID
Couple of time this script worked by started getting Maximum execution time of 30 seconds exceeded AND created multiple customer entries in directory and payment failed
PS : am using GOTO to loop and ENV file for credentials
Any help will be appreciated in advance
print_r($_POST);
$booknow = $_POST;
require 'vendor/autoload.php';
use Dotenv\Dotenv;
use Square\Models\Money;
use Square\Models\CreatePaymentRequest;
use Square\Exceptions\ApiException;
use Square\SquareClient;
use Square\Environment;
use SquareConnect\ApiClient;
use Square\Models\CreateCustomerRequest;
$idem = UUID::v4();
$sname = explode(' ', $_POST["cname"]);
$sname0 = $sname[0];
$sname1 = $sname[1];
$cphone = $_POST["cphone"];
//$cphone = '9848848450';
$cemailid = $_POST["cemailid"];
$ifare = ($_POST["ifare"] * 100);
$xnote = $_POST["note"];
//echo '<br><br>fare : ' . $ifare . '<br><br>';
$dotenv = Dotenv::create(__DIR__);
$dotenv->load();
$upper_case_environment = strtoupper(getenv('ENVIRONMENT'));
$access_token = getenv($upper_case_environment.'_ACCESS_TOKEN');
//print_r($access_token);
//echo '<br><br><br>';
$client = new SquareClient([
'accessToken' => $access_token,
'environment' => getenv('ENVIRONMENT')
]);
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
error_log('Received a non-POST request');
echo 'Request not allowed';
http_response_code(405);
return;
}
$nonce = $_POST['nonce'];
if (is_null($nonce)) {
echo 'Invalid card data';
http_response_code(422);
return;
}
searchCustomers: ///search customers
$phone_number = new \Square\Models\CustomerTextFilter();
$phone_number->setFuzzy($cphone);
$filter = new \Square\Models\CustomerFilter();
$filter->setPhoneNumber($phone_number);
$query = new \Square\Models\CustomerQuery();
$query->setFilter($filter);
$body = new \Square\Models\SearchCustomersRequest();
$body->setQuery($query);
$api_response = $client->getCustomersApi()->searchCustomers($body);
if ($api_response->isSuccess()) {
$rmn = $api_response->getBody();
$stx = json_decode($rmn,true);
echo '<br><br>';
echo '# of arrays : ' . count($stx);
if(count($stx) != 0){
//echo '<br><br>';
$cust_id = $stx["customers"][0]["id"];
//echo "Customer ID : " . $cust_id;
goto makePayment;
//goto end;
} else {
//echo 'user do not exists';
/// new customer - start
$body1 = new \Square\Models\CreateCustomerRequest();
$body1->setIdempotencyKey($idem);
$body1->setGivenName($sname0);
$body1->setFamilyName($sname1);
$body1->setEmailAddress($cemailid);
$body1->setPhoneNumber($cphone);
$api_response = $client->getCustomersApi()->createCustomer($body1);
if ($api_response->isSuccess()) {
$result = $api_response->getResult();
goto searchCustomers;
} else {
$errors = $api_response->getErrors();
}
/// new customer - end
}
} else {
echo '<br><br>sorry not found!<bR><br>';
}
goto end;
makePayment:
$amount_money = new \Square\Models\Money();
$amount_money->setAmount($ifare);
$amount_money->setCurrency('USD');
$body = new \Square\Models\CreatePaymentRequest(
'cnon:card-nonce-ok',
$idem,
$amount_money
);
$body->setCustomerId($cust_id);
$body->setNote($xnote);
$api_response = $client->getPaymentsApi()->createPayment($body);
if ($api_response->isSuccess()) {
$result = $api_response->getResult();
$srt = json_encode($result);
echo '<br><br>';
echo "PAYEMNT SUCCESSUFLL <BR><br><br>";
//print_r($srt);
goto end;
} else {
$errors = $api_response->getErrors();
echo 'payment FAILEDDDDDDDDDD';
}
goto end;
end:

Telegram API Bot - CallbackQuery response to the touch of a button

Actually the question is how to get an answer from the user at the click of a button?
What should be changed\rewritten in the code?
$access_token = '...';
$api = 'https://api.telegram.org/bot' . $access_token;
$output = json_decode(file_get_contents('php://input'), TRUE);
$message = $output['message']['text'];
$chat_id = $output['message']['chat']['id'];
if ($output['callback_query'] != null){
$data = $output['callback_query']['data'];
$data_id = $output['callback_query']['id'];
$chat = $output['callback_query']['message']['chat']['id'];
switch($data){
case "/123":
answerCallback($data_id, '123');
sendMessage($chat, "123", null);
break;
case "/plz":
answerCallback($data_id, 'plz');
sendMessage($chat, "plz", null);
break;
}
}
elseif ($message != null) {
switch($message) {
case '/test':
$inline_button1 = array("text"=>"123","callback_data"=>"/123");
$inline_button2 = array("text"=>"work plz","callback_data"=>'/plz');
$inline_keyboard = [[$inline_button1,$inline_button2]];
$keyboard=array("inline_keyboard"=>$inline_keyboard);
$replyMarkup = json_encode($keyboard);
sendMessage($chat_id, "ok", $replyMarkup);
break;
}
}
function sendMessage($chat_id, $message, $replyMarkup) {
file_get_contents($GLOBALS['api'] . '/sendMessage?chat_id=' . $chat_id . '&text=' . urlencode($message) . '&reply_markup=' . $replyMarkup);
}
function answerCallback($id, $text) {
file_get_contents($GLOBALS['api'] . '/answerCallbackQuery?callback_query_id='.$id.'&text='.$text);
}
This code only allows you to get a response from the message /test, and does not respond to button presses.
Uses webhook.
Have a look at your error log. You forgot to provide a value for $replyMarkup.
PHP Warning: Missing argument 3 for sendMessage()

The data response send to ipay88 not the result i want

for the ipay88 should include a BackendURL need to return with the Response Code as "200" and the Response Data as "RECEIVEOK"/"OK" to acknowledge that the payment status has been received.
The expected result is
but the result i sent is
Here is my code for backendURL
public function backendResponse()
{
$expected_sign = $_POST['Signature'];
$merchantcode = $this->merchantcode;
$merchantkey = $this->merchantkey;
$check_sign = '';
//$ipaySignature = '';
$str = '';
$HashAmount = '';
$orderID = $_POST['RefNo'];
$paymentID = $_POST['PaymentId'];
$paymentStatus = $_POST['Status'];
$amountPaid = $_POST['Amount'];
$transID = $_POST['TransId'];
$remark = $_POST['Remark'];
$errDesc = $_POST['ErrDesc'];
$amount = preg_replace("/[^0-9]/", "", $amountPaid);
$string = $this->iPay88_signature($merchantkey . $merchantcode .
$paymentID . $orderID . $amount . $_POST['Currency'] .
$paymentStatus);
if ($paymentStatus == "1" && $string == $expected_sign) {
echo 'RECEIVEOK';
}
}
Could anyone help? i wanted to send the response data just only RECEIVEOK, without HTML DATA TAG. Thank you so much, really appreciated..

PHP Telegram Bot (editMessageText & editReplyMarkup)

I am Kevin and these days I'm having problems with the functions editMessageText and editReplyMarkup. This is my code and I don't know where is the problem.
This is my code:
<?php
$botToken = "XXXXXXXXX:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
$website = "https://api.telegram.org/bot".$botToken;
$FilejSon = file_get_contents("php://input");
$FilejSon = json_decode($FilejSon, TRUE);
$FirstName = $FilejSon["message"]["chat"]["first_name"];
$UserChatId = $FilejSon["message"]["chat"]["id"];
$Message = $FilejSon["message"]["text"];
$MessageID = $FilejSon["message"]["message_id"];
$CallBackID = $FilejSon["callback_query"]["from"]["id"];
$CallBackData = $FilejSon["callback_query"]["data"];
$what = ["callback_query"]["message"]["inline_message_id"];
$document = "http://media.giphy.com/media/109Ku3hdapZJle/giphy.gif"; //It's just a funny image
//Emoji
$phone = json_decode('"\uD83D\uDCF2"');
$list = json_decode('"\uD83D\uDCCB"');
$money = json_decode('"\uD83D\uDCB0"');
$postbox = json_decode('"\uD83D\uDCEE"');
$sos = json_decode('"\uD83C\uDD98"');
$link = json_decode('"\uD83D\uDD17"');
$jSonCodeKeyboard = '&reply_markup={"inline_keyboard":[[{"text":"1","url":"https://core.telegram.org/bots/api"}],[{"text":"2","url":"https://www.google.it"}],[{"text":"4","switch_inline_query_current_chat":"try"}],[{"text":"5","url":"https://www.google.it"},{"text":"'.$link.'%20Link%20'.$link.'","url":"http://botkevin.altervista.org/Bot/Nuovo_documento_di_testo.txt"}],[{"text":"6","callback_data":"Press"}]]}';
$jSonCodeKeyboard1 = '&reply_markup={"inline_keyboard":[[{"text":"Indietro","callback_data":"Ok"}]]}';
switch ($Message){
case '/start':
$msg = "Hello $GLOBALS[FirstName] $GLOBALS[MessageID] $GLOBALS[UserChatId] $GLOBALS[what].\n";
sendMessage($UserChatId, $msg, $jSonCodeKeyboard);
break;
case '/prova':
sendFile($UserChatId, $document);
break;
case '/prova1':
$msg = "worked $GLOBALS[MessageID]";
sendMessage($UserChatId, $msg, $jSonCodeKeyboard1);
break;
default:
if (callback($FilejSon)){
if ($CallBackData == "Press"){
sendMessage($CallBackID, "gg", $jSonCodeKeyboard1);
}
else if($CallBackData == "Ok")
{
$msg = "Edited";
Edit($CallBackID, $MessageID, $msg);
Edit1($CallBackID, $MessageID, $jSonCodeKeyboard1);
}
}
$msg = "Unrecognized command.";
sendMessage($UserChatId, $msg);
break;
}
function sendMessage($chat_id, $text, $LayoutKey){
if($LayoutKey==""){
$url = $GLOBALS[website]."/sendMessage?chat_id=".$chat_id."&text=".urlencode($text);
file_get_contents($url);
}
else{
$url = $GLOBALS[website]."/sendMessage?chat_id=".$chat_id."&text=".urlencode($text).$LayoutKey;
file_get_contents($url);
}
}
function sendFile($chat_id, $file){
$url = $GLOBALS[website]."/sendDocument?chat_id=".$chat_id."&document=".$file; //Gif,Pdf e Zip
file_get_contents($url);
}
function Edit($chat_id, $msgID, $text){
$url = $GLOBALS[website]."/editMessageText?chat_id=".$chat_id."&message_id=".$msgID."&text=".urlencode($text);
file_get_contents($url);
}
function Edit1($chat_id, $msgID, $LayoutKey){
$url = $GLOBALS[website]."/editMessageReplyMarkup?chat_id=".$chat_id."&message_id=".$msgID.$jSonCodeKeyboard1;
file_get_contents($url);
}
function callback($getUpdate){
return $getUpdate["callback_query"];
}?>
I've searched everywhere a solution but either were in another programming language or used a library and more, I'm not very good at php so i would like a basic thing like my code.
I would like to do that when I click on the inline keyboard of the first message that sends the bot by doing "/ start", clicking a button can modify the message and the inline keyboard without sending other messages clogging the chat.
(already checked https://core.telegram.org/bots/api)

having php fatal error Function name must be a string in C:\wamp\www\drupal-7.42\sites\all\modules\form_fun\form_fun.cake.inc on line 78

I am trying to send a curl request to moodle using drupal.But each tiem i run this code i get an error message that function name must be a string.I have tried everything but nothing is working.Can anybody please help me?
function form_fun_cake_submit(&$form, &$form_state) {
$serverUrl=' http://localhost/moodle/my/webservice/rest/server.php?wstoken=d90b5d90db13711d12df525366f15db1';
$functionName = 'core_user_create_users';
$user1 = new stdClass();
$user1->username = 'testusername1';
$user1->password = 'Uk3#0d5w';
$user1->firstname = 'testfirstname1';
$user1->lastname = 'testlastname1';
$user1->email = 'testemail1#moodle.com';
$user1->auth = 'manual';
$user1->idnumber = '';
$user1->lang = 'en';
$user1->timezone = 'Australia/Sydney';
$user1->mailformat = 0;
$user1->description = '';
$user1->city = '';
$user1->country = 'AU'; //list of abrevations is in yourmoodle/lang/en/countries
$preferencename1 = 'auth_forcepasswordchange';
$user1->preferences = array(
array('type' => $preferencename1, 'value' => 'true')
);
$users = array($user1);
$params = array('users' => $users);
/// REST CALL
$rest_format = 'json';
//$server_url = $domain_name . '/webservice/rest/server.php' . '?wstoken=' . $token . '&wsfunction=' . $function_name;
$server_url = 'localhost/moodle/my' . '/webservice/rest/server.php'. '?wstoken=' . '15bd45a3dab2958b7e8fc237b14f76cd' .'&wsfunction='. $functionName;
dpm($server_url);
require_once('curl.inc');
$curl = new curl;
$rest_format = ($rest_format == 'json') ? '&moodlewsrestformat=' . $rest_format : '';
$resp =$curl($server_url . $rest_format, $params); //This is my line no 78
dpm($rest_format);
$respRc = json_decode($resp, true);
dpm($resp);
echo '</br>************************** Server Response createUser()**************************</br></br>';
echo $server_url . '</br></br>';
var_dump($resp);
}
Line 78 replace $curl(...) with new curl(..), your object instancing is incorrect. What is telling the php log is that you are using a variable as function name aka $curl (nothing to do with $functionName wich might have generated an error later with curl not on compile if it was wrong).
$resp = new curl($server_url . $rest_format, $params);

Categories