I've been looking around for the past few days for an answer to this question, but I haven't been able to find the solution I'm after.
I have a fully working version of doing this task using Google_Client, however I want to be able to do this without using the Google_Client. I can create buckets without using it, but not Objects. I cannot understand the Google Documentation on this at all (it's pretty poor).
So, I have a function below which takes in several parameters to try and upload a file. I'm not sure what needs to go in $authheaders, $post_fields (the body of the post) or the url.
public function upload_file($bucket, $fileName, $file, $fileType) {
// Check if we have auth token
if(empty($this->authtoken)) {
echo "Please login to Google";
exit;
}
// Prepare authorization headers
$authheaders = array(
"Authorization: Bearer " . $this->authtoken
);
$postbody = array();
//Http call for creating a file
$response = $this->http_call(self::FILE_UPLOAD_URL.$bucket.'/o?uploadType=multipart&name='.$fileName, $postbody, $authheaders);
// Has the file been created successfully?
if($response->success=="1") {
return array('status' => 'success', 'errorcode' =>'', 'errormessage'=>"", 'id' => $response->job->id);
}
else {
return $response;
}
}
The http_call function:
public function http_call($url, $post_fields, $authheaders) {
// Make http call
$this->httpRequest->setUrl($url);
$this->httpRequest->setPostData(json_encode($post_fields));
$this->httpRequest->setHeaders($authheaders);
$this->httpRequest->send();
$response = json_decode($this->httpRequest->getResponse());
return $response;
}
Any help on this would be greatly appreciated.
If anyone else is looking to do this without using the API, here is how I solved my question using curl.
// Prepare authorization headers
$authheaders = array(
"Authorization: Bearer " . $this->authtoken,
"Content-Type: application/pdf"
);
$url = self::FILE_UPLOAD_URL.$bucket.'/o/?uploadType=multipart&name='.$fileName.'';
$curl = curl_init();
curl_setopt($curl, CURLOPT_POSTFIELDS, $file);
curl_setopt($curl, CURLOPT_HTTPHEADER, $authheaders);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_USERAGENT, "Goole Cloud Storage PHP Starter Application google-api-php-client/1.1.5");
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
// 1 is CURL_SSLVERSION_TLSv1, which is not always defined in PHP.
curl_setopt($curl, CURLOPT_SSLVERSION, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, true);
$response = curl_exec($curl);
Related
I'm trying to delete all message of a slack channel
i tried to add the required scopes to the app but this two scopes aren't available
chat:write:user
chat:write:bot
i tried with the bot and the user token after reinstall the workspace
the function getAllMessagesFromChannel() i wrote works and i get all the timestamps correctly
public function clearChannel()
{
$jsonData = $this->getAllMessagesFromChannel();
foreach ($jsonData->messages as $message) {
$this->deleteMessage($message->ts);
}
}
private function deleteMessage($ts)
{
$data = json_encode(array("channel" => $this->channel, "ts" => $ts));
$ch = curl_init("https://slack.com/api/chat.delete");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8', "Authorization: Bearer " . $this->token));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
echo $result . "\n";
curl_close($ch);
}
i get this error for every message:
{"ok":false,"error":"cant_delete_message"}
enter image description here
any idea how to fix this?
I am currently working with the setup of PayPal Subscription through REST API in sandbox environment.
I am able to add product, add plan and also add subcription with APIs.
But at the payment page ( on the PayPal side ), where it asks to click for subscription, error occurs.
Error occurs at the page: https://www.sandbox.paypal.com/webapps/billing/subscriptions?ba_token=BA-0T473376T5204322K, when i hit the Login to subscribe button.
Error Page Image
When i check the console, here's the response that it triggers on the page:
Request URL : https://www.sandbox.paypal.com/webapps/billing/api/billagmt/BA-0T473376T5204322K/createCart
Headers
Request Method: POST
Status Code: 400 Bad Request
Response
{"ack":"contingency","contingency":"VALIDATION_ERROR","meta":{"calc":"...some string...","rlog":"...some string.."},"server":"...some string..."}
I am unable to do any kind of debug as it occurs over PayPal Page.
Kindly help me to find if what is going wrong at my side (i.e., API) ?
My Code
API Call ( Add Subscription )
$request = json_encode($req);
$header = [ 'Content-Type: application/json', 'Authorization: Bearer '.$this->getOauthToken() ];
$method = 'POST';
$url = $this->paypal_url.'billing/subscriptions';
$response = json_decode($this->callAPI($header, $method, $request, $url));
Helpers
// Call API
private function callAPI($header, $method, $request, $url)
{
$curl = curl_init();
switch ($method) {
case "POST":
curl_setopt($curl, CURLOPT_POST, 1);
if ($request)
curl_setopt($curl, CURLOPT_POSTFIELDS, $request);
break;
case "PUT":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
if ($request)
curl_setopt($curl, CURLOPT_POSTFIELDS, $request);
break;
default:
if ($request)
$url = sprintf("%s?%s", $url, http_build_query($request));
}
// OPTIONS:
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
// EXECUTE:
$result = curl_exec($curl);
if(!$result){ die("Connection Failure"); }
curl_close($curl);
return $result;
}
// Fetch Oauth Token
private function getOauthToken()
{
$url = $this->paypal_url.'oauth2/token';
$header = [
"Content-Type: application/x-www-form-urlencoded",
"Authorization: Basic " . base64_encode($this->client_id.':'.$this->client_secret)
];
$curl = curl_init();
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, 'grant_type=client_credentials');
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
if(!$result) { die("Connection Failure"); }
curl_close($curl);
$response = json_decode($result);
return $response->access_token;
}
It gives me HATEOAS link like: https://www.sandbox.paypal.com/webapps/billing/subscriptions?ba_token=BA-0T473376T5204322K, where the error occurs.
Also my data is complete OK as per API requirements.
Because i have already modified all possible errors regarding the data incompatibilty.
If it's complete description about problem, then please try to help me not by just triggering hold, but figuring out the issue.
We had a similar problem. Some subscription payments were going through and others not. The form payload looked the same.
When it was returning the error, we realised that the value for the number of times that subscription payments recur (srt) was set to 1. The docs point out that the minimum value shoudbe 2 and maximum of 52.
I just want to use "file_get_html" to get content of specific pages, but this content just avaiable for loggin user, is there any way to send cookie to let target site know that the page is accessed by logged in user.
require_once 'simple_html_dom.php';
$opts = array("Cookie: __qca=P0-1170249003-1395413811270"); //__qca=P0-1170249003-1395413811270
$current_url = 'http://abc.xyz';
// But it will be redirect to
$url = 'http://www.blogger.com/blogin.g?blogspotURL=http://abc.xyz'
$context = stream_context_create($opts);
$html = file_get_html($url, FALSE, $context);
echo $html;
I do something like this, but it doesn't work.
How Can I do this with Curl?
Thanks.
$ch = curl_init(); // your curl instance
curl_setopt_array($ch, [CURLOPT_URL => "http://www.blogger.com/blogin.g?blogspotURL=http://abc.xyz", CURLOPT_COOKIE => "__qca=P0-1170249003-1395413811270"], CURLOPT_RETURNTRANSFER => true]);
$result = curl_exec($ch); // request's result
$html = new simple_html_dom(); // create new parser instance
$html->load($result); // load and parse previous result
In this example I used curl_setopt_array() to set the various CURL parameters instead of calling curl_setopt() for each one of them.
CURLOPT_URL sets the target URL, CURLOPT_COOKIE sets the cookies to send, if there are multiple cookies then they must be separated with a semicolon followed by a space, finally the CURLOPT_RETURNTRANSFER tells CURL to return the server's response as a string.
curl_exec() executes the request and returns its result.
Then we create an instance of simple_html_dom and load that previous result into it.
Thank you so much #andre, I spent all evening yesterday to find the solution :
The first we make curl exe to login to google account.
and save cookie to a text file (exam : "/tmp/cookie.txt")
and the next time everything we have to do is only take cookie content in this file to get remote content.
<?php
require_once 'simple_html_dom.php';
// Construct an HTTP POST request
$clientlogin_url = "https://www.google.com/accounts/ClientLogin";
$clientlogin_post = array(
"accountType" => "HOSTED_OR_GOOGLE",
"Email" => "youracc#gmail.com",
"Passwd" => "yourpasswd",
"service" => "blogger",
"source" => "your application name"
);
// Initialize the curl object
$curl = curl_init($clientlogin_url);
// Set some options (some for SHTTP)
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $clientlogin_post);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_COOKIEFILE, "/tmp/cookie.txt");
curl_setopt($curl, CURLOPT_COOKIEJAR, "/tmp/cookie.txt");
// Execute
$response = curl_exec($curl);
echo $response;
// Get the Auth string and save it
preg_match("/Auth=([a-z0-9_\-]+)/i", $response, $matches);
$auth = $matches[1];
echo "The auth string is: " . $auth;
// Include the Auth string in the headers
// Together with the API version being used
$headers = array(
"Authorization: GoogleLogin auth=" . $auth,
"GData-Version: 3.0",
);
$url = 'http://testlink.html';
$curl = curl_init();
// Make the request
curl_setopt($curl, CURLOPT_URL, $url );
//curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POST, false);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_COOKIEFILE, "/tmp/cookie.txt");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($curl);
curl_close($curl);
$html = new simple_html_dom(); // Create new parser instance
$html->load($response);
foreach($html->find('img') as $img) {
//echo $img->src . '</br>';
}
I'm working with the Google Translate API and there's the possibility that I could be sending in quite a bit of text to be translated. In this scenerio Google recommends to do the following:
You can also use POST to invoke the API if you want to send more data
in a single request. The q parameter in the POST body must be less
than 5K characters. To use POST, you must use the
X-HTTP-Method-Override header to tell the Translate API to treat the
request as a GET (use X-HTTP-Method-Override: GET). Google Translate API Documentation
I know how to make a normal POST request with CURL:
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($curl);
curl_close($curl);
echo $response;
But how do I modify the header to use the X-HTTP-Method-Override?
curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-HTTP-Method-Override: GET') );
http://php.net/manual/en/function.curl-setopt.php
CURLOPT_HTTPHEADER
An array of HTTP header fields to set, in the format array('Content-type: text/plain', 'Content-length: 100')
Thus,
curl_setopt($curl, CURLOPT_HTTPHEADER, array('X-HTTP-Method-Override: GET'));
use the CURLOPT_HTTPHEADER option to add a header from a string array
Not enough for me , i need to use http_build_query fo my array post data
my full example :
$param = array(
'key' => 'YOUR_API_KEY_HERE',
'target' => 'en',
'source' => 'fr',
"q" => 'text to translate'
);
$formData = http_build_query($param);
$headers = array( "X-HTTP-Method-Override: GET");
$ch=curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$formData);
curl_setopt($ch, CURLOPT_HTTPHEADER,$headers );
curl_setopt($ch, CURLOPT_REFERER, 'http://yoursite'); //if you have refere domain restriction for your google API KEY
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,'https://www.googleapis.com/language/translate/v2');
$query = curl_exec($ch);
$info = curl_getInfo($ch);
$error = curl_error($ch);
$data = json_decode($query,true);
if (!is_array($data) || !array_key_exists('data', $data)) {
throw new Exception('Unable to find data key');
}
if (!array_key_exists('translations', $data['data'])) {
throw new Exception('Unable to find translations key');
}
if (!is_array($data['data']['translations'])) {
throw new Exception('Expected array for translations');
}
foreach ($data['data']['translations'] as $translation) {
echo $translation['translatedText'];
}
I found this help here https://phpfreelancedeveloper.wordpress.com/2012/06/11/translating-text-using-the-google-translate-api-and-php-json-and-curl/
Hope that helps
Not being able to authenticate Google Spreadsheet API.
I'm using this code stolen from here,
$clientlogin_url = "https://www.google.com/accounts/ClientLogin";
$clientlogin_post = array(
"accountType" => "HOSTED_OR_GOOGLE",
"Email" => "MY_EMAIL#GOOGLE.COM",
"Passwd" => "MY_EMAIL_PASS",
"service" => "writely",
"source" => "MY_APPLICATION_NAME"
);
// Initialize the curl object
$curl = curl_init($clientlogin_url);
// Set some options (some for SHTTP)
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $clientlogin_post);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
// Execute
$response = curl_exec($curl);
// Get the Auth string and save it
preg_match("/Auth=([a-z0-9_\-]+)/i", $response, $matches);
$auth = $matches[1];
echo "The auth string is: " . $auth; //this worked!
So this works and now I have a key But actually using it...with the bellow code gives me a user not authenticated error:
$headers = array(
"Authorization: GoogleLogin auth=" . $auth,
"GData-Version: 3.0",
);
$key = 'MY_KEY';
// Make the request
curl_setopt($curl, CURLOPT_URL, 'https://spreadsheets.google.com/tq?tqx=version:0.6;out:json&key='.$key);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POST, false);
$response = curl_exec($curl);
curl_close($curl);
var_dump ($response);
this gives me
string(272) "google.visualization.Query.setResponse({version:'0.6',status:'error',errors:[{reason:'user_not_authenticated',message:'User not signed in',detailed_message:'\u003ca target=\u0022_blank\u0022 href=\u0022http://spreadsheets.google.com/\u0022\u003eSign in\u003c/a\u003e'}]});"
So apparently it is not able to use the authentication key for the Google Visualization Query Language.. what am I doing wrong?
Thank you so much!
I would try the following modifications in the code that uses google authentication string:
add urlencode
$headers = array(
"Authorization: GoogleLogin auth=" . urlencode($auth),
"GData-Version: 3.0",
);
and skip verifying SSL sertificates:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
I've described my experience implementing authentication with CURL in this post. There you'll find some tips on debugging CURL requests.