I am using dialogflow php client library for accessing v2 rest api of dialogflow. I can call detectIntent and other stuffs and it is working. But some times i should need to search for a specific trainingPhrase and if not present then add new training phrase for detected intent. How could i do this using php client library? I am tired of searching on this. Please help me. Any answers will be appreciated. The function I'm using to getIntent with the some text is as below,
function detect_intent_texts($projectId, $text, $sessionId, $languageCode = 'en-US')
{
global $common;
// new session
$test = array('credentials' => 'key_file.json');
$sessionsClient = new SessionsClient($test);
$session = $sessionsClient->sessionName($projectId, $sessionId ?: uniqid());
//printf('Session path: %s' . PHP_EOL, $session);
// create text input
$textInput = new TextInput();
$textInput->setText($text);
$textInput->setLanguageCode($languageCode);
// create query input
$queryInput = new QueryInput();
$queryInput->setText($textInput);
// get response and relevant info
$response = $sessionsClient->detectIntent($session, $queryInput);
$queryResult = $response->getQueryResult();
$queryText = $queryResult->getQueryText();
$intent = $queryResult->getIntent();
$displayName = $intent->getDisplayName();
$common->write_to_log("intent displayName : ".$displayName);
if($displayName == "Default Fallback Intent")
{
$result = json_encode(array("result"=>false));
$common->write_to_log("No matching intent found");
}
else
{
$confidence = $queryResult->getIntentDetectionConfidence();
$fulfilmentText = $queryResult->getFulfillmentText();
$common->write_to_log("intent response : ".$fulfilmentText);
$result = json_encode(array("result"=>true,"message"=>$fulfilmentText));
}
echo $result;
$sessionsClient->close();
}
Related
I am trying to use this quick guide to set up dialogFlow API on my laravel project - https://cloud.google.com/dialogflow/docs/quick/api.
This is the method I have created to detect intents, etc.
function detect_intent_texts($projectId, $texts, $sessionId, $languageCode = 'en-US'){
// new session
$filePath = base_path('dialogflow.json');
putenv("GOOGLE_APPLICATION_CREDENTIALS=".$filePath);
$sessionsClient = new SessionsClient();
$session = $sessionsClient->sessionName($projectId, $sessionId ?: uniqid());
printf('Session path: %s' . PHP_EOL, $session);
// query for each string in array
foreach ($texts as $text) {
// create text input
$textInput = new TextInput();
$textInput->setText($text);
$textInput->setLanguageCode($languageCode);
// create query input
$queryInput = new QueryInput();
$queryInput->setText($textInput);
// get response and relevant info
//dd($queryInput);
$response = $sessionsClient->detectIntent($session, $queryInput);
$queryResult = $response->getQueryResult();
$queryText = $queryResult->getQueryText();
$intent = $queryResult->getIntent();
$displayName = $intent->getDisplayName();
$confidence = $queryResult->getIntentDetectionConfidence();
$fulfilmentText = $queryResult->getFulfillmentText();
// output relevant info
print(str_repeat("=", 20) . PHP_EOL);
printf('Query text: %s' . PHP_EOL, $queryText);
printf('Detected intent: %s (confidence: %f)' . PHP_EOL, $displayName,
$confidence);
print(PHP_EOL);
printf('Fulfilment text: %s' . PHP_EOL, $fulfilmentText);
}
$sessionsClient->close();
}
When I try to run the function using this -
$array = ['hello'];
detect_intent_texts(env('DIALOGFLOW_PROJECT_ID'), $array, '134253474848');
I get this error-
{ "message": "IAM permission 'dialogflow.sessions.detectIntent' on 'projects\/********\/agent' denied.", "code": 7, "status": "PERMISSION_DENIED", "details": [] }
Please what might be the problem here?
It sounds like you have not properly setup roles when configuring your service account. See the auth setup steps.
I'm trying to build a simple project in which the google plus profile data will be saved or will get updated into the database. I'm unable to figure the way out of invalid character URI problem. I'm getting invalid character URI as response from google.
How can I solve this problem of invalid URI?
I have attached the image of the error at the end of this post.
Login Controller class code is:
public function index() {
// Include the google api php libraries
include_once APPPATH."libraries/google-api-php-client/Google_Client.php";
include_once APPPATH."libraries/google-api-php-client/contrib/Google_Oauth2Service.php";
// Google Project API Credentials
$clientId = 'My Client ID';
$clientSecret = 'My Secret here';
$redirectUrl = 'https://example.com/index.php?login/index/';
// Google Client Configuration
$gClient = new Google_Client();
$gClient->setApplicationName('Login to Application');
$gClient->setClientId($clientId);
$gClient->setClientSecret($clientSecret);
$gClient->setRedirectUri($redirectUrl);
$google_oauthV2 = new Google_Oauth2Service($gClient);
if (isset($_REQUEST['code'])) {
$gClient->authenticate();
$this->session->set_userdata('token', $gClient->getAccessToken());
redirect($redirectUrl);
}
$token = $this->session->userdata('token');
if (!empty($token)) {
$gClient->setAccessToken($token);
}
if ($gClient->getAccessToken()) {
$userProfile = $google_oauthV2->userinfo->get();
// Preparing data for database insertion
$userData['oauth_provider'] = 'google';
$userData['oauth_uid'] = $userProfile['id'];
$userData['first_name'] = $userProfile['given_name'];
$userData['last_name'] = $userProfile['family_name'];
$userData['email'] = $userProfile['email'];
$userData['gender'] = $userProfile['gender'];
$userData['locale'] = $userProfile['locale'];
$userData['profile_url'] = $userProfile['link'];
$userData['picture_url'] = $userProfile['picture'];
// Insert or update user data
$userID = $this->user->checkUser($userData);
if(!empty($userID)){
$data['userData'] = $userData;
$this->session->set_userdata('userData',$userData);
} else {
$data['userData'] = array();
}
} else {
$data['authUrl'] = $gClient->createAuthUrl();
}
$this->load->view('backend/login',$data);
}
The image of the error :
I am unable to tackle the problem. Please suggest me how can I avoid this.
I am working in building a restful api using php & slim for my app backend and also we have a web version but my team use pure php with the web suit , we work separately . it is just the first time that i have the backend responsibility I have a miss understanding about how i can handle the authentication in a secure and professional way i have read this article but i need a detailed way how to implement it in php & slim and extend it to the web team so to use the same authentication technic .
this is how the log in / sign up code that i have used :
help me to improve it :
$app->post('/api/create_user', function( $request , $response , $args ){
require('../config.php');
$email = $_POST['email'];
$qry= "select * from user where email ='". $email."'";
$result=$mysqli->query($qry);
if(mysqli_num_rows($result)>0){
$user = new stdClass();
$user->status=0;
$user->error=" the email is registered ";
$result = new stdClass();
$result->result=$user;
}
else {
$password = md5($_POST['password']);
$image=$_FILES['image']['name'];
$email=$_POST['email'] ;
$nickname =$_POST['nickname'];
$birthDay=$_POST['birthdate'];
$insert_req="INSERT INTO user VALUES ('', '$email', '$password','$nickname')";
$insert_user_result=$mysqli->query($insert_req);
if ($insert_user_result) {
$user = new stdClass();
$user->status=1;
$result = new stdClass();
$result->result=$user;}
else {$user = new stdClass();
$user->status=2;
$user->error=mysql_error();
$result = new stdClass();
$result->result=$user;}
}
if (isset($result)){
header('Content-type: application/json');
echo json_encode($result);}
});
?>
<?php
$app->post('/api/login', function( $request , $response , $args ){
require('../config.php');
$email =$_POST['email'];
$password = md5($_POST['password']);
$findemail_qry= "select user_id from user where email ='". $email."'";
$findemail_result =$mysqli->query($findemail_qry);
if(mysqli_num_rows($findemail_result)>0)
{
$login_qry="select user_id from user where email ='". $email."'AND password ='".$password."'";
$login_result =$mysqli->query($login_qry);
if(mysqli_num_rows($login_result)>0)
{
$data =mysqli_fetch_assoc ($login_result);
$user_id=$data['user_id'];
$user = new stdClass();
$user->status=1;
$user->user_id=$user_id;
$result = new stdClass();
$result->result=$user;}
else
{$user = new stdClass();
$user->status=2;
$user->error="wrong password";
$result = new stdClass();
$result->result=$user; }
}
else
{$user = new stdClass();
$user->status=0;
$user->error=" this email not registered ";
$result = new stdClass();
$result->result=$user;}
if (isset($result)){
header('Content-type: application/json');
echo json_encode($result);
}
});
?>
You can use JWT in your slim application as your authntication layer for Your API
You can use this library to implement it
Slim JWT
In a simple way you can use something like this
Try to use Basic authorization to send user name and password
Then You will generate a new JWT Token ,That will used in all others API
<?php
use \Firebase\JWT\JWT;
use \Slim\Middleware\HttpBasicAuthentication\AuthenticatorInterface;
require '../vendor/autoload.php';
$app = new \Slim\App;
class RandomAuthenticator implements AuthenticatorInterface {
public function __invoke(array $arguments) {
//validation for user and password
$Password=$arguments['password'];
$user=$arguments['user'];
if(($Password=="admin") &&($user=="admin") ){
return true;
}
else{
return false ;
}
}}
//add http basic middleware for login route
$app->add(new \Slim\Middleware\HttpBasicAuthentication([
"path" => "/login",
"realm" => "Protected",
"authenticator" => new RandomAuthenticator()
]));
$app->post("/login", function ($request, $response, $arguments) {
//generate JWT token
$now = new DateTime();
$future = new DateTime("now +20 minutes");
$server = $request->getServerParams();
$payload = [
"iat" => $now->getTimeStamp(),
"exp" => $future->getTimeStamp(),
"sub" => $server["PHP_AUTH_USER"],
];
$secret = "TOURSECERTKEY";
$token = JWT::encode($payload, $secret, "HS512");
$data["status"] = "ok";
$data["token"] = $token;
return $response->withStatus(201)
->withHeader("Content-Type", "application/json")
->write(json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
});
//Add jWT token Authorization middleware for all API
$app->add(new \Slim\Middleware\JwtAuthentication([
"path" => ["/"],
"passthrough" => ["/login"],
"secret" => "TOURSECERTKEY",
"error" => function ($request, $response, $arguments) {
$data["status"] = "error";
$data["message"] = $arguments["message"];
return $response
->withHeader("Content-Type", "application/json")
->write(json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
}
]));
Users on my website can login to Twitter and post their status on my website and twitter at once. I'm using https://github.com/abraham/twitteroauth to connect to Twitter. Login and posting is performed on different pages of website.
This is login script:
public function loginTwitter() {
$twitter = new TwitterOAuth(
$this->getContext()->params['social']['twitter']['consumerKey'],
$this->getContext()->params['social']['twitter']['consumerSecret']
);
$request_token = $twitter->getRequestToken($this->link('//User:connectFromTwitter'));
// Saving to session (Nette Framework)
$twitterSession = $this->getContext()->session->getSection('twSes');
$twitterSession->oauth_request_token = $token = $request_token['oauth_token'];
$twitterSession->oauth_request_token_secret = $request_token['oauth_token_secret'];
if ($twitter->http_code == 200) {
$requestLink = $twitter->getAuthorizeURL($token);
$this->redirectUrl($requestLink);
} else {
echo 'Error';
}
}
This is callback script (posting works right after user has been logged in):
public function twitterOauth() {
// $_GET parameter oauth_verifier
$oauthVerifier = $this->getParam('oauth_verifier');
// Session section
$twitterSession = $this->getContext()->session->getSection('twSes');
$twitter = new TwitterOAuth(
$this->getContext()->params['social']['twitter']['consumerKey'],
$this->getContext()->params['social']['twitter']['consumerSecret'],
$twitterSession->oauth_request_token,
$twitterSession->oauth_request_token_secret
);
$access_token = $twitter->getAccessToken($oauthVerifier);
$twitterSession->access_token = $access_token;
$user_info = $twitter->get('account/verify_credentials');
// Saving to DB to be able to post without login
$tm = new TwitterUserManager();
if (!$tm->isInDatabase($this->getUser()->getId())) {
$tu = new TwitterUser();
$tu->setUser($this->loggedUser);
$tu->setOauthProvider('twitter');
$tu->setOauthUid("'".$user_info->id."'");
$tu->setUsername("'".$user_info->screen_name."'");
$tu->setOauthToken("'".$access_token['oauth_token']."'"); // Saving the access token for further posting
$tu->setOauthSecret("'".$access_token['oauth_token_secret']."'");
$tm->persist($tu);
}
$twitter->post('statuses/update', array('status' => 'Hello ' . date('d.m.Y H:i:s'))); // <== HERE IT WORKS
$this->redirect('User:socialConnect'); // Redirect to another page
}
This is posting function (User posts from any page):
public function postToTwitter() {
$twitterSession = $this->getContext()->session->getSection('twitter');
$twitter = new TwitterOAuth(
$this->getContext()->params['social']['twitter']['consumerKey'],
$this->getContext()->params['social']['twitter']['consumerSecret'],
$twitterSession->access_token['oauth_token'],
$twitterSession->access_token['oauth_token_secret']
);
return $twitter->post('statuses/update', array('status' => 'Hello' . date('d.m.Y H:i:s')));
}
When I use posting function I get this error:
stdClass(2) {
request => "/1/statuses/update.json" (23)
error => "Could not authenticate you." (27)
}
Thanks for help in advance.
EDIT: Solution:
Use this to connect to Twitter (save all info into DB):
http://framework.zend.com/manual/1.12/en/zend.oauth.introduction.html
Use this to post from any page:
http://framework.zend.com/manual/1.12/en/zend.service.twitter.html
Nice example:
http://www.joeyrivera.com/2010/twitter-api-oauth-authentication-and-zend_oauth-tutorial/
I always used the Zend-Framework-Component: http://framework.zend.com/manual/1.12/en/zend.service.twitter.html
I think it's simple and I could confirm, that it works. You just have to read through the tutorial (see link above).
I am trying to send context and payload to the Dialogflow V2 API. I am able to successfully send a queryString and get a response from my agent. However, I need to pass context and payload parameters with this query and I cannot seem to find ANY help on this for PHP. Please see my code below. I am able to create the context object and the payload object (atleast I think its created), but how do I pass it to the API?
Any help would be appreciated as I am very new to dialogflow and have been struggling with this for a few days now.
function detect_intent_texts($projectId, $text, $sessionId, $context, $parameters, $languageCode = 'en-US') {
// new session
$test = array('credentials' => 'client-secret.json');
$sessionsClient = new SessionsClient($test);
$session = $sessionsClient->sessionName($projectId, $sessionId ?: uniqid());
//printf('Session path: %s' . PHP_EOL, $session);
// create text input
$textInput = new TextInput();
$textInput->setText($text);
$textInput->setLanguageCode($languageCode);
$contextStruct = new Struct();
$contextStruct->setFields($context['parameters']);
$paramStruct = new Struct();
$paramStruct->setFields($parameters['parameters']);
$contextInput = new Context();
$contextInput->setLifespanCount($context['lifespan']);
$contextInput->setName($context['name']);
$contextInput->setParameters($contextStruct);
$queryParams = new QueryParameters();
$queryParams->setPayload($paramStruct);
// create query input
$queryInput = new QueryInput();
$queryInput->setText($textInput);
// get response and relevant info
$response = $sessionsClient->detectIntent($session, $queryInput); // Here I don't know how to send the context and payload
$responseId = $response->getResponseId();
$queryResult = $response->getQueryResult();
$queryText = $queryResult->getQueryText();
$intent = $queryResult->getIntent();
$displayName = $intent->getDisplayName();
$confidence = $queryResult->getIntentDetectionConfidence();
$fulfilmentText = $queryResult->getFulfillmentText();
$returnResponse = array(
'responseId' => $responseId,
'fulfillmentText' => $fulfilmentText
);
$sessionsClient->close();
return $returnResponse;
}
Just as it happens, the moment I post my question, I get a result.
Thanks to this post How to set query parameters dialogflow php sdk.
I added the following to my code and it worked.
Added
$optionalsParams = ['queryParams' => $queryParams];
Changed
$response = $sessionsClient->detectIntent($session, $queryInput, $optionalsParams);