gravity form create post after add entry via web api - php

we develop mobile app for a website that have gravity form and we can make entry via web api of gravity form, but in website when submit the form it's create new post automatically because form have some post fields and when we add new entry via web api it just add entry not post.
how can we define that this entry must be saved to post via gravity forms web api?
Update:
gravity form can create post via it forms if that form have post fields. read more
and this functionality is just for submission form so you can't access it via web api.
for do this you must add it manually
complete example that must be placed at themes/YOUR_THEME/functions.php:
$api_key = 'your_public_key';
$private_key = 'your_private_key';
//set route
$route = 'entries'; // or 'forms/{formID}/entries'
//creating request URL
$expires = strtotime( '+1 day' );
$string_to_sign = sprintf( '%s:%s:%s:%s', $api_key, 'POST', $route, $expires );
$sig = calculate_signature( $string_to_sign, $private_key );
$url = 'http://your_domain.com/gravityformsapi/' . $route . '?api_key=' . $api_key . '&signature=' . $sig . '&expires=' . $expires;
if(isset($_POST)){
$body = [
[
"form_id"=> "1", // if $route is just 'entries'
'1' => "Post Title" ,
'2' => "Post Content"
]
//,[ another entry ]
];
$response = wp_remote_post($url,['body'=>json_encode($body)]);
if ( is_wp_error( $response ) ) {
wp_send_json_error($response->get_error_message());
} else {
$body = json_decode($response['body'],true);
if($body['status'] === 201){
foreach($body['response'] as $entry_id){ //get each entry ID
$entry = GFAPI::get_entry( $entry_id );
if(!is_wp_error($entry)){
$form = GFAPI::get_form( rgar($entry,'form_id') );
if($form)
GFCommon::create_post( $form, $entry); //Finally add Post.
else
wp_send_json_error("can not find entry form.");
}else
wp_send_json_error($entry->get_error_message());
}
wp_send_json_success("Success!");
}else{
wp_send_json_error($body);
}
}
}else
wp_send_json_error("request body invalid");

$api_key = 'your_public_key';
$private_key = 'your_private_key';
//set route
$route = 'entries'; // or 'forms/{formID}/entries'
//creating request URL
$expires = strtotime( '+1 day' );
$string_to_sign = sprintf( '%s:%s:%s:%s', $api_key, 'POST', $route, $expires );
$sig = calculate_signature( $string_to_sign, $private_key );
$url = 'http://your_domain.com/gravityformsapi/' . $route . '?api_key=' . $api_key . '&signature=' . $sig . '&expires=' . $expires;
if(isset($_POST)){
$body = [
[
"form_id"=> "1", // if $route is just 'entries'
'1' => "Post Title" ,
'2' => "Post Content"
]
//,[ another entry ]
];
$response = wp_remote_post($url,['body'=>json_encode($body)]);
if ( is_wp_error( $response ) ) {
wp_send_json_error($response->get_error_message());
} else {
$body = json_decode($response['body'],true);
if($body['status'] === 201){
foreach($body['response'] as $entry_id){ //get each entry ID
$entry = GFAPI::get_entry( $entry_id );
if(!is_wp_error($entry)){
$form = GFAPI::get_form( rgar($entry,'form_id') );
if($form)
GFCommon::create_post( $form, $entry); //Finally add Post.
else
wp_send_json_error("can not find entry form.");
}else
wp_send_json_error($entry->get_error_message());
}
wp_send_json_success("Success!");
}else{
wp_send_json_error($body);
}
}
}else
wp_send_json_error("request body invalid");

Related

Fulfilment response PHP webhook not showing up in Actions on Google

The fulfilment response is visible in diagnostic info in the Dialogflow environment. But it's not showing up when I test it in Actions on Google. Anyone who knows how to let it work? Here is my webhook code:
<?php
$method = $_SERVER['REQUEST_METHOD'];
if($method == 'POST'){
$requestBody = file_get_contents('php://input');
$json = json_decode($requestBody);
$text = $json->queryResult->queryText;
$date = (!empty($json->queryResult->parameters->date)) ? $json->queryResult->parameters->date : '';
$environment = (!empty($json->queryResult->parameters->environment)) ? $json->queryResult->parameters->environment : '';
$intent = (!empty($json->queryResult->intent->displayName)) ? $json->queryResult->intent->displayName : '';
$responseText = prepareResponse($intent, $text, $date, $environment);
$response = new \stdClass();
$response->speech = $responseText;
$response->displayText = $responseText;
$response->source = "webhook";
header("Content-type:application/json");
echo json_encode($response);
}
else
{
echo "Method not allowed";
}
function prepareResponse($intent, $text, $date, $environment)
{
return "You said: " . $text . " | I found Intent: " . $intent . " | with parameters: date=" . $date . " environment=" . $environment;
}
?>
Responses for Actions on Google should be in an object under the payload attribute that contains a single attribute google with the AoG response format.
I haven't tested it, and this may not be the best way to build it, but something like the following should work:
$response->payload = array(
"google" => array(
"expectUserResponse" => TRUE,
"richResponse" => array(
"items" => array(
array(
"simpleResponse" => array(
"textToSpeech" => $responseText
)
)
)
)
)
);

502 Bad Gateway Foreach loop

hope for some help, basically i have a script that gets the latest posts from facebook users, and basically i check if there is any new post that is not available on my database, in case that this post is new, than i save it in my database along with the post id (this way i check if exist on DB).
But i have a issue with it, in my case i need to check a number of users, and this users keeps growing, in my case i have 400 users. If i go more thatn 100 users i get the 500 error of course, it is many requests.
So does someone have a ideia of how could i handle it?
My code: FarcebookParcer.php
public function facebook($id, $num) {
//Set your App ID and App Secret.
$appID = 'xxxxxxxxxx';
$appSecret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx';
//Create an access token using the APP ID and APP Secret.
$accessToken = $appID . '|' . $appSecret;
//Tie it all together to construct the URL
$url = "https://graph.facebook.com/$id/posts?fields=attachments,created_time&limit=$num&access_token=$accessToken";
if (Helper::get_http_response_code($url) != 200) {
return false;
}
//Make the API call
$opts = array(
'http' => array(
'method' => 'GET',
'timeout' => 120
)
);
$context = stream_context_create($opts);
$result = file_get_contents($url, false, $context);
//Decode the JSON result.
$dt = json_decode($result, true);
$posts = $dt;
return $posts;
}
CronController.php
public function socialfacebook() {
$facebook = SocialSnap::all();
$socialparser = new FacebookParser();
$appID = 'xxxxxxxxxxx';
$appSecret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$accessToken = $appID . '|' . $appSecret;
set_time_limit(0);
foreach ($facebook as $key => $value) {
if ($value->facebook != NULL) {
$facebook_user = $socialparser->facebook_user(substr($value->facebook, 1));
$facebook_posts = $socialparser->facebook(substr($value->facebook, 1), 1);
//Check if valid url
if ($facebook_posts == false || $facebook_user == false) {
continue;
}
if (isset($facebook_posts['data'][0]['attachments']['data'][0]['target']['url']) && isset($facebook_posts['data'][0]['attachments']['data'][0]['description'])) {
SnapChat::where('facebook', $value->facebook)->update(['facebook_photo' => 'https://graph.facebook.com/'. substr($value->facebook, 1) . '/picture/?type=normal']);
$post_current = SocialSnap::where('id_social', $facebook_posts['data'][0]['id'])->first();
//return $post_current;
if ($post_current == NULL) {
$post = new SocialSnap;
$post->id_social = $facebook_posts['data'][0]['id'];
$post->id_snapchats = $value->id;
$post->date_social = isset($facebook_posts['data'][0]['created_time']) ? date("Y-m-d H:m:s", strtotime($facebook_posts['data'][0]['created_time'])) : "";
$post->type = 'facebook';
$post->url = $facebook_posts['data'][0]['attachments']['data'][0]['target']['url'];
$post->message = $facebook_posts['data'][0]['attachments']['data'][0]['description'];
if (isset($facebook_posts['data'][0]['attachments']['data'][0]['media']['image']['src'])) {
$post->image = $facebook_posts['data'][0]['attachments']['data'][0]['media']['image']['src'];
}
$post->save();
}
}
}
}
echo 'DONE';
}

How to use linked in login for https server?

Previously i was used http server for my linkedin login. Now I changed https server for my entire site. But now i cannot show login details after changed that. Here i post my function, In this fuction i also changed https. But yet not i show the details. I use this function in codeigniter.
public function login(){
$client_id = $this->config->item('linkedin_app_id');
$redirect_uri = base_url().'linkedinLogin';
if (isset($_GET['error'])) {
echo $_GET['error'] . ': ' . $_GET['error_description'];
} elseif (isset($_GET['code'])) {
$this->loginAccessToken();
$user = $this->login_fetch('GET', '/v1/people/~:(id,firstName,lastName,email-address,picture-url)');//get name
$email = $user->emailAddress;
$user_name = $user->firstName;
$last_name = $user->lastName;
$social_id = $user->id;
$profile_image_url = 'user-thumb.png';
echo "<pre>";print_r($user); die;
if($email != '')
{
$googleLoginCheck = $this->user_model->googleLoginCheck($email);
if($googleLoginCheck > 0)
{
//echo "login";
$getGoogleLoginDetails = $this->user_model->google_user_login_details($email);
//echo "<pre>";print_r($getGoogleLoginDetails);die;
$userdata = array(
'fc_session_user_id' => $getGoogleLoginDetails['id'],
'session_user_email' => $getGoogleLoginDetails['email']
);
//echo "<pre>";print_r($userdata);die;
$this->session->set_userdata($userdata);
if($this->data['login_succ_msg'] != '')
$lg_err_msg = $this->data['login_succ_msg'];
else
$lg_err_msg = 'You are Logged In ...';
$this->setErrorMessage('success',$lg_err_msg);
redirect(base_url());
}
else
{
$google_login_details = array('social_login_name'=>$user_name,'social_login_unique_id'=>$social_id,'screen_name'=>$user_name,'social_image_name'=>'','social_email_name'=>$email,'loginUserType'=>'google');
//echo "<pre>";print_r($google_login_details);die;
//echo "redirect to registration page";
$social_login_name = $user_name;
$this->session->set_userdata($google_login_details);
$firstname = $user_name;
$lastname = $last_name;
$orgPass = time();
$pwd = md5($orgPass);
$Confirmpwd = $orgPass;
$username = $user_name;
$condition = array ('email' => $email);
$duplicateMail = $this->user_model->get_all_details ( USERS, $condition );
$expireddate = date ( 'Y-m-d', strtotime ( '+15 days' ) );
$dataArr = array('firstname'=>$firstname,'lastname'=>$lastname,'user_name'=>$firstname,'group'=>'User','image'=>$profile_image_url,'email'=>$email,'password'=>$pwd,'status'=>'Active','expired_date'=>$expireddate,'is_verified'=>'No','loginUserType'=>'linkedin','google'=>'Yes','created'=>date('Y-m-d H:i:s'));
$this->user_model->simple_insert(USERS,$dataArr);
$lstID = $this->db->insert_id();
//echo $this->db->last_query(); die;
$userdata = array (
'quick_user_name' => $firstname,
'quick_user_email' => $email,
'fc_session_user_id' => $lstID,
'session_user_email' => $email
);
$this->session->set_userdata ( $userdata );
$this->setErrorMessage('success','Registered & Login Successfully');
redirect(base_url());
}
}
else
{
redirect('');
}
}else {
header("Location:https://www.linkedin.com/uas/oauth2/authorization?response_type=code&client_id=$client_id&redirect_uri=$redirect_uri&state=987654321&scope=r_basicprofile%20r_emailaddress%20w_share");
}
}
public function loginAccessToken() {
$params = array(
'grant_type' => 'authorization_code',
'client_id' => $this->config->item('linkedin_app_id'),
'client_secret' => $this->config->item('linkedin_app_key'),
'code' => $_GET['code'],
'redirect_uri' => base_url().'linkedinLogin'
);
// Access Token request
$url = 'https://www.linkedin.com/uas/oauth2/accessToken?' . http_build_query($params);
// Tell streams to make a POST request
$context = stream_context_create(
array('https' =>
array('method' => 'POST',
)
)
);
// Retrieve access token information
$response = file_get_contents($url, false, $context);
// Native PHP object, please
$token = json_decode($response);
// Store access token and expiration time
$_SESSION['access_token'] = $token->access_token; // guard this!
$_SESSION['expires_in'] = $token->expires_in; // relative time (in seconds)
$_SESSION['expires_at'] = time() + $_SESSION['expires_in']; // absolute time
return true;
}
public function login_fetch($method, $resource, $body = '') {
$opts = array(
'https' => array(
'method' => $method,
'header' => "Authorization: Bearer " .
$_SESSION['access_token'] . "\r\n" .
"x-li-format: json\r\n"
)
);
$url = 'https://api.linkedin.com' . $resource;
// if (count($params)) {
// $url .= '?' . http_build_query($params);
// }
$context = stream_context_create($opts);
$response = file_get_contents($url, false, $context);
return json_decode($response);
}
Here look the login() fuction. I print the user details. But i got empty window only
echo "<pre>";print_r($user); die;
But when i use http, i got the user details. Can help me anyone?

Usage of facebook login + Laravel

Just implemented facebook login on my test site, and it seems too simple to be true?
I am using these two from GitHub
https://github.com/Lusitanian/PHPoAuthLib
https://github.com/artdarek/oauth-4-laravel
To implement this I added a button:
{{ link_to_action('UserController#loginWithFacebook', 'Facebook Login in', $parameters = array(), $attributes = array('class' => 'btn btn-primary fb-login-btn')); }}
And then modifiying the example login method to authorise the user after success:
public function loginWithFacebook() {
$code = Input::get( 'code' );
$fb = OAuth::consumer( 'Facebook' );
if ( !empty( $code ) ) {
$token = $fb->requestAccessToken( $code );
$result = json_decode( $fb->request( '/me' ), true );
// ADDED SECTION
$newUser = User::create(
array(
'email' => $result['email']
)
);
$user = User::find($newUser->id);
Auth::login($user);
return Redirect::to('/');
} else {
$url = $fb->getAuthorizationUri();
return Redirect::to( (string)$url );
}
}
This works, which has surprised me... is this really all it takes?
The question im asking really is would this be the way its intended to be used? The response is used to create a user, then log them in after with their ID.
I only use their email, since they only need to login using the facebook button. In the future I could prompt them to add a password so they don't always have to use facebook login but the basics of this is correct?
// get data from input
$code = Input::get( 'code' );
// get fb service
$fb = OAuth::consumer( 'Facebook' );
// check if code is valid
// if code is provided get user data and sign in
if ( !empty( $code ) ) {
// This was a callback request from facebook, get the token
$token = $fb->requestAccessToken( $code );
// Send a request with it
$result = json_decode($fb->request( '/me?fields=id,name,first_name,last_name,email,photos' ), true);
$message = 'Your unique facebook user id is: ' . $result['id'] . ' and your name is ' . $result['name']. $result['email'];
//echo $message. "<br/>";
//Var_dump
//display whole array().
//echo('http://graph.facebook.com/'.$result['id'].'/picture?type=large<br>');
//dd($result);
$user = \User::where("email",$result['email'])->first();
if($user!=NULL){
$userxx = Sentry::findUserByLogin($result['email']);
Sentry::login($userxx, false);
return Redirect::to('Beşiktaş');
}
else
{
$k=str_random(8);
$user = Sentry::register(array(
'activated' => 1,
'facebook' => 1,
'password' => $k,
'email' => $result['email'],
'first_name' =>$result['first_name'],
'last_name' => $result['last_name'] ,
'avatar' => 'http://graph.facebook.com/'.$result['id'].'/picture?type=large',
));
Sentry::login($user, false);
return Redirect::to('Beşiktaş');
}
}
// if not ask for permission first
else {
// get fb authorization
$url = $fb->getAuthorizationUri();
// return to facebook login url
return Redirect::to( (string)$url );
}

Twitter access token request returns "Invalid or expired token"

I am using custom code to connect to Twitter and request an access token. For some reason when trying to post to "access_token" on the API it returns "invalid or expired token". The code is as follows (apart from a few external function calls and properties this should be sufficient to replicate the error):
public function authenticate($get,$return = false) {
session_start();
if (!isset($get['oauth_verifier'])){
// Step 1 - get a request token
$step1 = $this->processRequest('oauth/request_token',0,$this->pObj->getRedirectUrl().'?process=true');
parse_str($step1,$parts);
if ($parts['oauth_callback_confirmed'] !== 'true'){ die('Error with process'); }
$_SESSION['tw_secret'] = $parts['oauth_token_secret'];
// Step 2
$url = str_replace('1.1/','',$this->api_url);
header("Location: {$url}oauth/authenticate?oauth_token={$parts['oauth_token']}");
} else {
// Step 3
$this->o_token = $get['oauth_token'];
$this->o_secret = $_SESSION['tw_secret'];
$content['oauth_verifier'] = $get['oauth_verifier'];
$step3 = $this->processRequest('oauth/access_token',1,null,$content,'array');
}
}
// https://dev.twitter.com/docs/auth/creating-signature
private function generateSignature($oauth,$fullurl,$http_method,$content){
// Take params from url
$main_url = explode('?',$fullurl);
// Split the content
$contents = explode('&',$content);
$urls = array_merge(explode('&',$main_url[1]),$contents);
foreach ($urls as $param){
$bits = explode('=',$param);
if (strlen($bits[0])){
$oauth[$bits[0]] = rawurlencode($bits[1]);
}
}
ksort($oauth);
$string = http_build_query($oauth);
$new_string = strtoupper($http_method).'&'.urlencode($main_url[0]).'&'.urlencode(urldecode($string));
// The request_token request doesn't need a o_secret because it doesn't have one!
$sign_key = strstr($fullurl,'request_token') ? $this->c_secret.'&' : $this->c_secret.'&'.$this->o_secret;
return urlencode(base64_encode(hash_hmac('sha1',$new_string,$sign_key,true)));
}
public function processRequest($in_url,$test = false,$callback = null,$content = null, $content_type = 'json',$form_content_type = 'application/x-www-form-urlencoded'){
$method = 'GET';
// Twitter still uses Oauth1 (which is a pain)
$oauth = array(
'oauth_consumer_key'=>$this->c_key,
'oauth_nonce'=>$this->random(32),
'oauth_signature_method'=>'HMAC-SHA1',
'oauth_timestamp'=>time(),
'oauth_token'=>$this->o_token,
'oauth_version'=>'1.0'
);
$url = $this->api_url.$in_url;
if (strlen($callback)){
$oauth['oauth_callback'] = urlencode(urldecode($callback));
unset($oauth['oauth_token']);
$method = 'POST';
$url = str_replace('1.1/','',$url);
}
if (is_array($content) || strlen($content)){ $method = 'POST'; }
$oauth['oauth_signature'] = $this->generateSignature($oauth,$url,$method,'');
ksort($oauth);
foreach ($oauth as $k=>$v){
$auths[] = $k.'="'.$v.'"';
}
$stream = array('http' =>
array(
'method' => $method,
'ignore_errors'=>true, // http://php.net/manual/en/context.http.php - otherwise browser returns error not error content
'follow_location'=>false,
'max_redirects'=>0,
'header'=> array(
'Content-type: '.$form_content_type,
'Authorization: OAuth '.implode(', ',$auths),
'Connection: close'
)
)
);
if (is_array($content)){
$content = $content_type == 'json' ? json_encode($content) : http_build_query($content);
/* foreach ($content as $k=>$v){
$strs[] = "$k=".urlencode(urldecode($v));
}
// Just for now to keep things simple
$content = 'status=Hello%20Ladies%20%2b%20Gentlemen%2c%20a%20signed%20OAuth%20request%21';*/
}
if (!is_null($content)){
$stream['http']['content'] = $content;
}
// Tell streams to make a request
// Invalid key or 401 error tends to suggest an incorrect signing key / signature
$response = file_get_contents($url, false, stream_context_create($stream));
if ($test){
print'<pre>';print_r($oauth);print'</pre>';
print'<pre>';print_r($stream);print'</pre>';
//echo $callback.'<br>';
echo $url.'<br>';
//print'<pre>';print_r($http_response_header);print'</pre>';
print'<pre>[';print_r($response);print']</pre>';
}
if (!is_object(json_decode($response))){
// Content supplied is not json - just return it
return $response;
} else {
$response = json_decode($response);
}
return $this->pObj->convertObjectToArray($response);
}
The reason for the problems are:
1) The version of the Twitter API should not be included
2) The post is missing the Oauth_verifier in the signature
Thanks to twitteroauth for providing some guiding light.

Categories