Answer the question
In order to leave comments, you need to log in
Receiving data from Viber and writing to the database?
Hello.
I'm making a Viber bot in php and ran into a problem.
I want that as the user wrote a message, the received response from Viber was recorded in the database.
I do it like this:
$output = json_decode(file_get_contents('php://input'), true);
$sqlViber = $pdo->prepare(' SELECT * FROM viber WHERE us_id=:us_id ');
$sqlViber->execute(array(
':us_id' => $output['sender']['id']
));
if ($sqlViber->rowCount()==0) {
$sqlAddUser = $pdo->prepare('INSERT INTO viber (us_id,info,create_us) VALUES (:us_id,:info,:create_us)');
$sqlAddUser->execute(array(
':us_id' => $output['sender']['id'],
':info' => serialize(array(
'name' => $output['sender']['name'],
'avatar' => $output['sender']['avatar']
)),
':create_us' => time()
));
}
$output = json_decode(file_get_contents('php://input'), true);
file_put_contents($_SERVER['DOCUMENT_ROOT'].'/0/'.uniqid(time().'_').'.txt', file_get_contents('php://input'));
Array
(
[event] => message
[timestamp] => 15178994*****
[message_token] => 51415526242759*****
[sender] => Array
(
[id] => XnDifpu********oCc6lpg==
[name] => My name
[avatar] => My avatar
[language] => ru
[country] => RU
[api_version] => 2
)
[message] => Array
(
[text] => 5
[type] => text
[media] =>
[thumbnail] =>
[tracking_data] => tracking data
)
[silent] =>
)
Array
(
[event] => delivered
[timestamp] => 1517****49597
[message_token] => 5141****29706804015
[user_id] => XnDifpu********oCc6lpg==
)
Array
(
[event] => seen
[timestamp] => 1517******500
[message_token] => 514******9706804015
[user_id] => XnDifpu********oCc6lpg==
)
Answer the question
In order to leave comments, you need to log in
Handle errors and see where the problem is php.net/manual/ru/pdo.error-handling.php
//Do this, it works for me....
# array with user data...
$json = file_get_contents('php://input');
$viber = json_decode($json);
//$sender=$viber->sender->id;//ID To send a message
$sender = $viber->{'sender'}; // sender is an array with user data
$name_user=$sender->name;//Name
$avatar = $sender->avatar; //Image
$receiverID = $sender->id; // ID
# Message from user
$message=$viber->message->text;
if ($receiverID!= "") //If the ID is not empty, then we save the user to the database
{
# Write to the database the data about the user who subscribed ....
# Connect to the database
include 'config.php';
$db = mysql_connect($servername, $username, $password);
if (!$db) {die('Connection error: ' . mysql_error());}
mysql_select_db($dbname, $db);
/*Making a database query*/
$result = mysql_query ("INSERT IGNORE INTO viber (receiver,name, avatar) VALUES ('$receiverID','$name_user', '$avatar')");
mysql_close($db);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question