Google API Data Transfer Insert: missing resource.applicationDataTransfer - php

I'm creating simple PHP script for transfering ownerships of drive files between users in the same domain. I want to use Admin SDK Transfers and Insert method.
Google has documentation about transfers here
I tried to transfer data through their webpage GUI and it went fine. What I can't do is how to make it work with PHP Client library.
Let's say I have prepared object for creating requests to Transfers resource
$transfers = new \Google_Service_DataTransfer($googleConnection);
googleConnection handles service account authorization so i can make requests like this:
$data = $this->transfers->transfers->listTransfers();
This returns data of all existing transfers in domain. Based on documentation and PHP Client library insert operation should work also.
$transferParams = new \Google_Service_DataTransfer_ApplicationTransferParam();
$transferParams->setKey("PRIVACY_LEVEL"); //what kind of docs I want to transfer
$transferParams->setValue(['SHARED', 'PRIVATE']);
$appDataTransfer = new \Google_Service_DataTransfer_ApplicationDataTransfer();
$appDataTransfer->setApplicationTransferParams($transferParams);
$appDataTransfer->applicationId = "iDString"; //set application ID
$newTransfer = New \Google_Service_DataTransfer_DataTransfer();
$newTransfer->setOldOwnerUserId('accountID'); //origin account IDs are placeholders
$newTransfer->setNewOwnerUserId('account2ID'); //destination account
$newTransfer->setApplicationDataTransfers($appDataTransfer);
$result = $this->transfers->transfers->insert($newTransfer); //execute insert
After executing insert I am getting code 400 with message Missing required field: [resource.applicationDataTransfer].
If I test real parameters via web they work.
I must be missing something, because that exception doesn't make sense at all.
I'm also open to alternative solutions.

setApplicationDataTransfers method expects an array of Google_Service_DataTransfer_DataTransfer so you just need to update the following line (note the [] in the params)
$newTransfer->setApplicationDataTransfers([$appDataTransfer]);

Related

Vtiger Query webservice returnes 403 access forbidden error in postman

I am new to vtiger and recently I tried working with third party API integration of vtiger where we can have a query webservice. I tried following API in Postman
http://myurl/webservice.php?operation=query&sessionName=63c67873606f00c2d94fa&query=select count(*) from Leads where Leadid = 1
which is giving 403 error. Also please let me know where to create a webservice in vtiger.
You have to authenticate:
First, get a challenge token:
GET /webservice.php?operation=getchallenge&username=<USERNAME> HTTP/1.1
Then use that token, together with a username and the accesskey of that user (not to be confused with the user's password) to login:
POST /webservice.php HTTP/1.1
operation=login
username=<USERNAME>
accessKey=md5(TOKENSTRING + <ACCESSKEY>) // Note: accessKey= K here is capitalized.
Notice that the concatenation of TOKENSTRING and ACCESSKEY need to be encoded using the md5 function. I recommend using php to do that operation because I've had problems using online encoders.
About the second question, take a look at the folder include/Webservices. Many of the files under that folder are ws functions and you have to create something similar. After created, you have to register
the function by calling vtws_addWebserviceOperation() and
each parameter of the function by calling vtws_addWebserviceOperationParam.
Both of the above functions are defined under /include/Webservices/Utils.php
source: https://community.vtiger.com/help/vtigercrm/developers/third-party-app-integration.html

Error :service account does not have bigquery.jobs.create permission

I created one service account with role big query admin.I am Using big query PHP API. Let me know if any other permission is required or not?
It gives me an error stating that the:
service account does not have bigquery.jobs.create permission.
I wanted to run a query on bigquery. Please help.
Following is my code:
$service = new Google_Service_Bigquery($client);
$query = new Google_Service_Bigquery_QueryRequest($client);
$query->setQuery('SELECT * FROM [xxx:xxx.xxs] LIMIT 1000;');
$jobs = $service->jobs;
$response = $jobs->query($project_id, $query);
// Do something with the BigQuery API $response data
print_r($response)
;
I ran into this problem using the BQ library for nodejs.
It seems being signed into a user/service account via the CLI is not always enough. My service account was authenticated and had the correct permissions in the GCP SDK Shell, but I still got service account does not have bigquery.jobs.create permission..
I was able to fix this by simply adding the same service account details, using the client library methods. I used https://googleapis.dev/nodejs/bigquery/latest/BigQuery.html.
In the case of nodejs, I just had to add
// Imports BigQuery library
const {BigQuery} = require('#google-cloud/bigquery');
// Create BQ Options - this object is what fixed the issue
const bqOptions = {};
bqOptions.projectId = '*your-project-name*';
bqOptions.keyFilename = '*Path-to-service-account-private-key*';
// Creates BQ client
const bq = new BigQuery(bqOptions);
I know you are using the PHP library, but I think the PHP equivalent would work the same.

Pulling Bright Local API Data into my Ruby on Rails App - API Docs written in PHP

I'm trying to build a rails app that pulls data from several different SEO tool API's. For Bright Local (see their API docs here - http://apidocs.brightlocal.com/) all the API doc examples are written in PHP, which I can't read all that great.
So first, to ask a specific question, how would I write this batch request in Ruby:
<?php
use BrightLocal\Api;
use BrightLocal\Batches\V4 as BatchApi;
$api = new Api('[INSERT_API_KEY]', '[INSERT_API_SECRET]');
$batchApi = new BatchApi($api);
$result = $batchApi->create();
if ($result['success']) {
$batchId = $result['batch-id'];
}
Also, any suggestions for how I can bring myself up to snuff on using API's in my rails apps?
Our docs do currently only show PHP examples - although we are planning to expand on that and Ruby is one of the languages we'll be looking to add.
A simple command line CURL request for the above PHP code would look like this:
curl --data "api-key=<YOUR API KEY HERE>" https://tools.brightlocal.com/seo-tools/api/v4/batch
and would return a response like this:
{"success":true,"batch-id":<RETURNED BATCH ID>}
All our API endpoints respond to either POST, PUT, GET or DELETE. It's also important to note that whenever data is posted with POST or PUT it's passed like "param1=value1&param2=value2" in the body of the request rather than JSON encoded.
I don't know Ruby at all I'm afraid but something like this might make the request you want:
params = {"api-key" => "<YOUR API KEY>"}
Net::HTTP::Post.new("https://tools.brightlocal.com/seo-tools/api/v4/batch").set_form_data(params)
I'm also implementing brightlocal into my Rails app. I'm using the HTTParty gem. this is what I have so far and am able to make successful calls
this is to obtain your batch id:
api_key = YOUR_API_KEY
secret_key = YOUR_SECRET_KEY
request_url = "https://tools.brightlocal.com/seo-tools/api/v4/batch?api-key=#{api_key}"
response = HTTParty.post(request_url)
if response.code == 201
batch_id = response['batch-id']
end
this is an example of running one job in the batch (the query parameters go inside the body):
rank_url = "https://tools.brightlocal.com/seo-tools/api/v4/rankings/search"
response = HTTParty.post(rank_url, {
:body => {
"api-key" => api_key,
"batch-id" => batch_id,
"search-engine" => "google",
"country" => "USA",
"search-term" => "restaurant"
}
})
I have not tested this next part, but theoretically, this is how you would deal with signatures and expirations
expires = Time.now.to_i + 1800
string_to_sign = "#{api_key}.#{expires}"
binary_signature = OpenSSL::HMAC.digest('sha1', string_to_sign, secret_key)
url_safe_signature = CGI::escape(Base64.encode64(binary_signature).chomp)
All that would be left is to use a PUT request to commit the batch, and a GET request to retrieve the data inside the batch.
EDIT: Figured out how to correctly get a passing signature for the jobs that require one. (this example is for local search rank checker http://apidocs.brightlocal.com/#local-search-rank-checker)
expires = Time.now.to_i + 1800
concat = api_key + expires.to_s
sig = OpenSSL::HMAC.digest('sha1', secret_key, concat)
sig = CGI::escape(Base64.encode64(sig).chomp)
local_rank = "https://tools.brightlocal.com/seo-tools/api/v2/lsrc/add?api-key=#{api_key}&sig=#{sig}&expires=#{expires}"
response = HTTParty.post(local_rank, {
:body => {
"name" => "pizza hut",
"search-terms" => "restaurant"
}
})
Since you are using Ruby and not PHP you will have to implement everything yourself. The example you give shows the user of a PHP wrapper created by BrightLocal (and it seems they only have it in PHP).
Basically you will have to make calls to the endpoints yourself and manage the data yourself instead of using their wrapper.

How to insert and retrieve postBody in Mirror API account insert method using PHP

I need to insert user's email in postBody of mirror API insert method. I am using this code:
$authtoken=null;
$postBody = new Google_Service_Mirror_Account();
$postBody->setAuthTokens($authtoken);
$userdata=array("email"=>$email);
$postBody->setUserData($userdata);
$account = $service->accounts->insert($userToken, package-name-here, $accountName, $postBody);
The above method returns null in response! I am not sure what to add as authtoken.
After this, I need to retrieve user's email account through Android's account manager:
AccountManager manager = AccountManager.get(c);
Account[] list = manager.getAccountsByType(package-name-here);
for (Account acct : list) {
accountEmailId= manager.getUserData(acct, "email");
break;
}
This doesn't seem to work. I do not get accounts of this type in Glass device. Any help will be great.
EDIT:
Added the authTokenArray and userDataArray to postBody as suggested below:
$userDataArray= array();
$userData1= new Google_Service_Mirror_UserData();
$userData1->setKey('email');
$userData1->setValue($email);
$userDataArray[]=$userData1;
$authTokenArray= array();
$authToken1= new Google_Service_Mirror_AuthToken();
$authToken1->setAuthToken('randomtoken');
$authToken1->setType('randomType');
$authTokenArray[]=$authToken1;
$postBody = new Google_Service_Mirror_Account();
$postBody->setUserData($userDataArray);
$postBody->setAuthTokens($authTokenArray);
Account insert method still returns null. Unable to solve the issue till now.
[SOLVED]
Mirror API still returns NULL response, but account is actually being inserted in Mirror API. Updated code can be viewed here: http://goo.gl/DVggO6
setAuthTokens takes an array of Google_Service_Mirror_AuthToken objects (see the source here), each of which has an authToken (an arbitrary string of your choosing) and a type (another arbitrary string). These values are copied directly into the account in the Android AccountManager so that you can look them on the device.
Your problem might be coming from the fact that you're passing in null for that right now. I would try fixing that and then see if you're able to see the account on the device.

How can I log into multiple accounts at the same time using the Google Api PHP Client

Background: We've got two Accounts that each hold several profiles.
I am developing an application in PHP using the provided API.
I can successfully retrieve data from both accounts separately, but whenever I instantiate the Google_Client object a second time (using a different variable name, of course), it instantly logs me out of the first account and overwrites the first account's settings.
Has anyone successfully managed to log into two accounts at the same time using the PHP API Client and could give me a hint on how to accomplish that?
Relevant code sections:
$client1 = new Google_Client();
$client1 ->setAssertionCredentials($omitted);
$client1 ->setClientId($id);
$client1 ->setAccessType('offline_access');
$gaClient1 = new Google_AnalyticsService($client);
//I can now successfully query the Analytics API, but when I do this
$client2 = new Google_Client();
//and query gaClient1 again, it throws a "you must login/401"-error
I guess the problem is that the api uses caching with files to handle request. Now when the second client is created, it is using the same cache folder and thus it is overwriting the previous settings.
now in your config.php is the following:
'ioFileCache_directory' =>
(function_exists('sys_get_temp_dir') ?
sys_get_temp_dir() . '/Google_Client' :
'/tmp/Google_Client')
This is the part that is always returning the same result. When creating a client, you can send in your own config array and it will be combined with the master. So you could use:
$client1 = new Google_Client(array('ioFileCache_directory' => '/tmp/dirclient1'));
$client2 = new Google_Client(array('ioFileCache_directory' => '/tmp/dirclient2'));
Also in your code you created a $client1, but later on you use $gaClient1 = new Google_AnalyticsService($client);. Shouldnt that be $gaClient1 = new Google_AnalyticsService($client1);?

Categories