I'm new to google drive api.
When I run the following piece of code (I got it from here) I get the following error:
Fatal error: Uncaught exception 'GuzzleHttp\Exception\ClientException' with message 'Client error: POST https://spreadsheets.google.com/feeds/list/1AnZ9_h3jnKogvx5AIftxypGnGM0f2P4r_ut4RGFC7AQ/od6/private/full resulted in a 400 Bad Request response'
The code:
$postBody = '<entry xmlns="http://www.w3.org/2005/Atom" xmlns:gsx="http://schemas.google.com/spreadsheets/2006/extended"><gsx:gear>more gear</gsx:gear><gsx:quantity>44</gsx:quantity></entry>';
echo "BBBB<br>";
$httpClient = new GuzzleHttp\Client(['headers' => $headers]);
echo "CCCC<br>";
$resp = $httpClient->request($method, $url, ['body' => $postBody]);
echo "DDDD<br>";
$body = $resp->getBody()->getContents();
$code = $resp->getStatusCode();
$reason = $resp->getReasonPhrase();
echo "$code : $reason\n\n";
echo "$body\n";
Can some one help me find the error?
Although this is not related to Guzzle at all, I found another method to do my task.
After creating the form go to Responses menu and select 'Get pre-filled URL'
Fill the dummy form you get and submit. Then you will be given a URL. Here change 'viewResponse' to 'formResponse'
Append the data to necessary parts of the URL.
Send request to this URL to fill the google form automatically and submit
Related
I am using twitter account activity api's to send/receive messages. In it i am facing problem in generating webhook. First time it was created successfully. In webhook file i am saving messages in database when each time message sent or received. But when I sent message nothing goes in database. Here is webhook file:
const APP_CONSUMER_SECRET = '**********';
// Example token provided by incoming GET request
if(isset($_REQUEST['crc_token'])) {
$token = $_REQUEST['crc_token'];
/**
* Creates a HMAC SHA-256 hash created from the app TOKEN and
* your app Consumer Secret.
* #param token the token provided by the incoming GET request
* #return string
*/
function get_challenge_response($token) {
$hash = hash_hmac('sha256', $token, APP_CONSUMER_SECRET, true);
$response = array(
'response_token' => 'sha256=' . base64_encode($hash)
);
return json_encode($response);
}
}else{
$feedData = file_get_contents('php://input');
$handleData = fopen('twitterDemo.txt', "w" );
fwrite($handleData,$feedData);
fclose($handleData);
$array = json_decode(file_get_contents('php://input'), true);
if (isset($array['direct_message_events'][0]['type']) && $array['direct_message_events'][0]['type'] == 'message_create' ) {
include_once ('config.php');
include_once ('database-queries.php');
$message = $array['direct_message_events'][0]['message_create']['message_data']['text'];
$sender = $array['direct_message_events'][0]['message_create']['sender_id'];
$from = $array['direct_message_events'][0]['message_create']['target']['recipient_id'];
$message_type = 'incoming';
$message_status = 'unread';
$userId = $sender;
$account_name = 'twitter';
$image_url = '';
if(isset($array['direct_message_events'][0]['message_create']['message_data']['attachment'])){
$image_url = "Not Image";
}
$data = array('to'=>$from, 'from'=>$sender, 'msg'=>$message,'image_url' =>$image_url);
insert($data, $account_name, $message_type, $message_status, $conn);
}
}
I thought there might be webhook problem so i deleted the existing app and create new one and set development environment label for it with new name. But for it when i tried to create webhook it gives me error:
[code] => 214 [message] => Webhook URL does not meet the requirements.
Invalid CRC token or json response format.
I dont know whats happening here now. I am using this api to create webhook url
$url = "https://example.com/twitter/webhook.php";
$result = $connection->post("account_activity/all/env_name/webhooks", ["url" => $url]);
Can anyone please help me this out. Any help will be appreciated.
Thanks!
I ran into the same error message.
The problem seem to be that the
if(isset($_REQUEST['crc_token']))
is not working anymore. Though the token is set. I don't know what is causing the problem but when I let the code just fetch the $_REQUEST['crc_token'] and create and print the hash its working.
But I see your code is not calling the get_challenge_response($token) function.
I think
print get_challenge_response($token)
may help? If the Webhook was deactivated by twitter you have to initiate another CRC check:
https://developer.twitter.com/en/docs/twitter-api/v1/accounts-and-users/subscribe-account-activity/guides/securing-webhooks
Your app can also trigger a CRC when needed by making a PUT request with your webhook id. Triggering a CRC is useful as you develop your webhook application, after deploying new code and restarting your service.
I am integrating Woo-commerce API's in my Laravel 5.6 site using Woo-commerce official rest sdk. I made a link using authentication endpoint URL.Which is mention at here .
When user clicks the link it takes the user to Woo-commerce authentication page, where user login and Approve the request.
After approving the request it should take me to return url which i mention in the link. Instead it shows me the following error.
Error: An error occurred in the request and at the time were unable to send the consumer data.
Here is my code.
`$store_url = 'YourStoreUrl';
$endpoint = '/wc-auth/v1/authorize';
$params = [
'app_name' => 'YourApplicationName',
'scope' => 'read_write',
'user_id' => 'yourUserId',
'return_url' => 'YourStoreUrl/callbackurl',
'callback_url' => 'YourStoreUrl/returncallback'
];
$query_string = http_build_query( $params );
$url = $store_url . $endpoint . '?' . $query_string;`
For future users who may have this same problem, ensure that your callback_url is correct. The error is mostly due to the callback_url.
In my case, I initially had this piece of python code:
store_url = 'http://localhost/wordpress'
endpoint = '/wc-auth/v1/authorize'
params = {
"app_name": "My app",
"scope": "read_write",
"user_id": 123,
"return_url": "http://localhost/wordpress/",
"callback_url": "https://f46c7c857579.ngrok.io",
}
query_string = urlencode(params)
return "%s%s?%s" % (store_url, endpoint, query_string)
But my callback_url was wrong. When I put in the correct callback_url, the error vanished. callback_url": "https://f46c7c857579.ngrok.io/return"
Also, make sure your callback_url has the POST HTTP METHOD
I am at the stage of the OAuth flow where I get the OAuth verifier and have to use it to get the permanent token, however I encounter the error "Invalid oauth_verifier parameter".
// I get a valid oauth verifier
$oauth_verifier = filter_input(INPUT_GET, "oauth_verifier");
// I am able to run var_dump($connection) and the response seems valid
$connection = new TwitterOAuth(
$config["consumer_key"],
$config["consumer_secret"],
$_SESSION["oauth_token"],
$_SESSION["oauth_token_secret"]
);
// I believe this is where the problem lies, if I try var_dump($token) nothing shows but my original error message
$token = $connection->oauth(
"oauth/access_token", [
"oauth_verifier" => $oauth_verifier
]
);
$twitter = new TwitterOAuth(
$config["consumer_key"],
$config["consumer_secret"],
$token["oauth_token"],
$token["oauth_token_secret"]
);
The full error message is:
Fatal error: Uncaught Abraham\TwitterOAuth\TwitterOAuthException: Invalid request token. in C:\xampp\htdocs\twitteroauth-master\src\TwitterOAuth.php:158 Stack trace: #0 C:\xampp\htdocs\twitter_callback.php(34): Abraham\TwitterOAuth\TwitterOAuth->oauth('oauth/access_to...', Array) #1 {main} thrown in C:\xampp\htdocs\twitteroauth-master\src\TwitterOAuth.php on line 158
If you are running this on a local server then check your url_callback, its not be in form of google tiny url, it must be in the form of "http://localhost:80/file_name" OR "http://localhots:8080/file_name". If you still have this problem then write your throw statement in try catch block.
e.g.
try {
throw new TwitterOAuthException($result);
}
catch(Exception $e) {
}
If you are running on server in spite of always check your url_callback should not be in the form of google tiny url because new twitter oauth didn't verify your google tiny url.
After 10 hours of trying various fitbit php libraries I'm turning to stackoverflow for help.
This doesn't work: https://github.com/heyitspavel/fitbitphp
Using
$profile = $fitbit->getProfile();
with that library returns
Fatal error: Uncaught exception 'FitBitException' with message 'Your Fitbit request failed. Code: 400' in /var/www/api/fitbitphp.php:324 Stack trace: #0 /var/www/api/addFitbit.php(22): FitBitPHP->getProfile() #1 {main} thrown in /var/www/api/fitbitphp.php on line 324
This the library on the fitbit website, seems like a lot of people have a problem with this.
public function getProfile()
{
$headers = $this->getHeaders();
try {
$this->oauth->fetch($this->baseApiUrl . "user/" . $this->userId . "/profile." . $this->responseFormat, null, OAUTH_HTTP_METHOD_GET, $headers);
} catch (Exception $E) {
}
$response = $this->oauth->getLastResponse();
$responseInfo = $this->oauth->getLastResponseInfo();
if (!strcmp($responseInfo['http_code'], '200')) {
$response = $this->parseResponse($response);
if ($response)
return $response;
else
throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
} else {
throw new FitBitException($responseInfo['http_code'], 'Your Fitbit request failed. Code: ' . $responseInfo['http_code']);
}
}
I tried this here as well but it doesn't return the user token or session id https://github.com/nostra999/fitbit-api
Perhaps missed out the init step, as described in the lib README file (https://github.com/heyitspavel/fitbitphp/blob/master/README.md)
Simple working usage is:
<?php
define('FITBIT_KEY', '777'); // The application key registered
define('FITBIT_SECRET', '777'); // The application secret registered
$fitbit = new FitBitPHP(FITBIT_KEY, FITBIT_SECRET);
$fitbit->initSession('http://localhost:8080/fibit'); // callback URL
$fitbit->getProfile();
Also from the Fitbit API Documentation:
https://wiki.fitbit.com/display/API/API+Response+Format+And+Errors#APIResponseFormatAndErrors-Response
400 Bad Request Any case where either endpoint doesn't exist, resource
path parameters are invalid, POST request parameters are invalid or no
Authentication header provided. This doesn't include invalid specific
resource ids
If this does not help, please provide the full code that you run, not just
$profile = $fitbit->getProfile();
I'm getting a TokenResponseException from Laravel when I try to login to my web site with Facebook using oauth-4-laravel.
OAuth \ Common \ Http \ Exception \ TokenResponseException
Failed to request resource.
Using Facebook's JavaScript API works like its supposed to, so I'm pretty sure my application is configured correctly.
Are there any known issues that might cause this problem? Am I doing something wrong, or is this a bug in the library?
With the exception of a redirect line that works around another bug, my code is identical to the example code at the GitHub page. I think the exception is thrown when I try to get the token from the Facebook Service object.
Here's the code:
public function loginWithFacebook() {
// 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 google, get the token
$token = $fb->requestAccessToken( $code );
// Send a request with it
$result = json_decode( $fb->request( '/me' ), true );
$message = 'Your unique facebook user id is: ' . $result['id'] . ' and your name is ' . $result['name'];
echo $message. "<br/>";
//Var_dump
//display whole array().
dd($result);
}
// if not ask for permission first
else {
// get fb authorization
$url = $fb->getAuthorizationUri();
// return to facebook login url
// ref: https://github.com/artdarek/oauth-4-laravel/issues/27
//return Response::make()->header( 'Location', (string)$url );
return Redirect::to((string)$url);
}
}
And a screenshot:
I had this exact same problem. It turns out that my issue was that my return_uri was missing a trailing slash, which through off the entire process. Make sure that when you're calling it you've added it.
$fb = OAuth::consumer('Facebook','http://url.to.redirect.to/');
NOT
$fb = OAuth::consumer('Facebook','http://url.to.redirect.to');
first try to load file_get_contents("https://www.facebook.com");
if allow_url_fopen=0 was set in the php.ini it will not work so you need to change it to allow_url_fopen=1
The weirdest thing i have your problem with google not with facebook, so here is my code maby it helps you fix your fb problem
public function loginWithFacebook() {
// 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' ), true );
$message = 'Your unique facebook user id is: ' . $result['id'] . ' and your name is ' . $result['name'];
echo $message. "<br/>";
//Var_dump
//display whole array().
dd($result);
}
// if not ask for permission first
else {
// get fb authorization
$url = $fb->getAuthorizationUri();
// return to facebook login url
return Redirect::to( (string)$url );
}
}
Since my previous answer was deleted.. Let's try again..
--
After some debugging I think I got it. Commenting out the error_reporting part visible in your code snippet will already tell you a lot. The file_get_contents call got a 401 Unauthorized because the tokens were no longer valid.
After changing code, start your auth process from the beginning and don't refresh your url half-way, that wil cause the error.
The problem should be here $token = $fb->requestAccessToken( $code );
When I tried var_dump it, I get this.
object(OAuth\OAuth2\Token\StdOAuth2Token)[279]
protected 'accessToken' => string 'your-accessToken' (length=180)
protected 'refreshToken' => null
protected 'endOfLife' => int 1404625939
protected 'extraParams' =>
array (size=0)
empty
Try this and check what you've get as accessToken. Anyway, your function loginWithFacebook working fine with me.
I had the same problem. I was trying to access facebook graph. It wasn't that it could not access the URL, it was that Facebook was returning a 400 error because I wasn't passing parameters through. Try connecting to HTTPS on a site that will have a working HTTPS connection. E.g. Try this:
file_get_contents("https://www.namhost.com");
If that works, you must see why the HTTPs connection you are connecting to is failing, because the problem isn't that you can't connect to HTTPs, but rather that what you are connecting to isn't liking the request.