Google Spreadsheet API and Codeigniter - php

I have a form, it has 4 data..
Right now I got the data on $_POST. And I want to put it to Google Spreadsheet using their API.. But i'm too newbie to understand the code..
I just only achived put Google Client API to codeigniter, but I don't know how to use it.
My code is look like this..
$this->load->library('google');
$values = array(
array(
$this->input->post('name'),
$this->input->post('email'),
$this->input->post('reason'),
$this->input->post('mobile'),
date('Y-m-d')
)
);
$body = new Google_Service_Sheets_ValueRange(array(
'values' => $values
));
// $params = array(
// 'valueInputOption' => $valueInputOption
// );
$result = $this->google->spreadsheets_values->update("1gg8rHsKM3DhMaJVY-YexQyggAoq1pUCB5LpP5NFah8A", "Sheet1!A2:E2", $body, "");
I don't know what the param is intended for, so I leave it blank..
I run this code and get error Message: Undefined property: Google::$spreadsheets_values

You're missing a few things, let's go step by step.
Firstly, you need to authenticate (seems like you've done it already):
$client = $this->getClient();
$service = new Google_Service_Sheets($client);
Specify how are you sending the data:
$valueInputOption = 'RAW';
Creating the array (note that 0 is column one, 1 is column 2 and 2 is column 3). If you want to send multiple lines just do like the example bellow or if it's just one line take the [$i] and just do $values = array(...);:
$valuesb[$i] = array(
0 => "Value 1",
1 => "Value 2",
2 => "Value 3"
);
Please note that you need to specify the spreadsheet range and tab name:
$data[] = new Google_Service_Sheets_ValueRange(
array(
'range' => '\'TAB NAME HERE\'!A2:AU10000',
'values' => $valuesb
)
);
Then finally sending the data
$requestBody = new Google_Service_Sheets_BatchUpdateValuesRequest();
$requestBody->setValueInputOption($valueInputOption);
$requestBody->setData($data);
$response = $service->spreadsheets_values->batchUpdate("Spreadsheet ID goes here", $requestBody);
Print the response:
echo "<pre>";
print_r($response);
echo "</pre>";

Related

Google Sheets API (""Invalid JSON payload received. Unknown name \"\": Root element must be a message."")

Trying to add data to a Google Sheet via the Google Sheets API and the BatchUpdate method, but I get this error (don't know what it refers to)
> PHP Fatal error: Uncaught Google\Service\Exception: { "error": {
> "code": 400,
> "message": "Invalid JSON payload received. Unknown name \"\": Root element must be a message.",
> "errors": [
> {
> "message": "Invalid JSON payload received. Unknown name \"\": Root element must be a message.",
> "reason": "invalid"
> }
> ],
> "status": "INVALID_ARGUMENT" } }
Here's my new code:
$spreadsheetId = 'myspreadsheetid';
$client = new Google_Client();
$client->setAuthConfig('mycredntials.json');
$client->setApplicationName('Sheet Automation');
$client->setScopes(Google_Service_Sheets::SPREADSHEETS);
$service = new Google_Service_Sheets($client);
$range = 'A2:L';
$valueInputOption = 'USER_ENTERED';
$body = new Google_Service_Sheets_ValueRange([
'values' => $row1
]);
$params = [
'valueInputOption' => $valueInputOption
];
$result = $service->spreadsheets_values->append($spreadsheetId, $range, $body, $params);
EDIT:
The data I get from the database is put into an array ($row1) that when echoed looks like this:
(
[cdr_id] => myid
[calldate] => 2021-05-27
[src] => mysource
[accountcode] => myaccountcode
[userfield] => disposition
[ivr_std_txn_full] =>
)
I then grab that info and use implode to put it all in one line (this may be the issue)
echo $line1 = implode(',', $row1)
I tried setting the values to be appended to both $row1 and $line1, but still get the payload issue.
in my condition, its because some data have null value, so make sure data you want send not null, you can change it to empty string or other.
example :
[ivr_std_txn_full] => null
change to :
[ivr_std_txn_full] => ''
The solution was pretty simple once I finally figured it out. If you won't be putting the values in manually and instead have an array filled with data you just need to reference each key in the array instead of just the array.
The request body ended up looking like this:
$body = new Google_Service_Sheets_ValueRange([
//'values' => $row1
'values' =>
[
[
$row1['cdr_id'], $row1['calldate'], $row1['src'], $row1['accountcode'], $row1['userfield'], $row1['ivr_std_txn_full']
]
]
]);
$params = [
'valueInputOption' => $valueInputOption
];
$result = $service->spreadsheets_values->append($spreadsheetId, $range, $body, $params);

Shapeshift API always returns "No Withdrawal Address Specified" error

I am using Shape Shift API for sending transaction with Guzzle. I am always getting the error given in title. My code given below:
$client = new GuzzleHttp\Client();
$data = [
"amount" => 1,
"withdrawal" => '0x23f016d7a8e408e5551ae7aa51b3fe1534165463',
"pair" => 'btc_eth',
"returnAddress" => '12stJs8vZNuuVfjZSSzpLPA96quNissk1b'
];
$result = $client->post( 'https://shapeshift.io/shift', [ 'Content-Type' => 'application/json' ],
[ 'json' => $data ] );
print "<pre>";
print_r( $result->getBody()->getContents() );
print "</pre>";
Same parameters work fine when using in Python.
You are doing the request wrong. The correct variant is with two parameters:
$result = $client->post('https://shapeshift.io/shift', ['json' => $data]);
Content type is configured automatically when you use json option.

ElasticSearch PHP SDK search returning null on match_all query

I recently tried to use ES. So I set it up in a cloud 9 environnement. I inserted data using a curl request file and I can see them with
http://mydomain/ingredients/aliments/_search?size=350&pretty=true
I then tried to set up elastic SDK (v.2.0) with Silex but I can't get the same output...
Here is my code :
$client = $app['elasticsearch'];
$params = array(
'size' => 350,
'index' => 'ingredients',
'type'=>'aliment',
'body' => array(
'query'=>array(
'match_all' => new \stdClass()
)
)
);
$ingredients = $client->search($params);
The output is NULL but when I do the following :
$params = array(
'index' => 'ingredients',
'type' => 'aliment'
);
$count = $client->count($params);
The output is as expected : {"count":240,"_shards":{"total":5,"successful":5,"failed":0}}
I've already spent a few hours trying to figure what's going on, I tried to replace the 'query' args with a json string, I tried empty array instead of the new stdClass but nothing seems to work.
Edit : I read the documentation again and tried the official example :
$client = $app['elasticsearch'];
$params = [
"search_type" => "scan", // use search_type=scan
"scroll" => "30s", // how long between scroll requests. should be small!
"size" => 50, // how many results *per shard* you want back
"index" => "ingredients",
"body" => [
"query" => [
"match_all" => []
]
]
];
$output = $client->search($params);
$scroll_id = $output['_scroll_id']; /*<<<This works****/
while (\true) {
// Execute a Scroll request
$response = $client->scroll([
"scroll_id" => $scroll_id, //...using our previously obtained _scroll_id
"scroll" => "30s" // and the same timeout window
]
);
var_dump($response); /*<<<THIS IS NULL****/
...
}
And unfortunately got same null result...
What am I doing wrong ?
Thanks for reading.
In my case it works this way:
$json = '{
"query": {
"match_all": {}
}
}';
$params = [
'type' => 'my_type',
'body'=> $json
];
I found out that the inserted data was malformed.
Accessing some malformed data via browser URL seems to be OK but not with a curl command line or the SDK.
Instead of {name:"Yaourt",type:"",description:""} , I wrote {"name":"Yaourt","description":""} in my requests file and now everything work as expected !
#ivanesi 's answer works. You may also try this one:
$params["index"] = $indexName;
$params["body"]["query"]["match_all"] = new \stdClass();

Sharepoint GetListItemChangesSinceToken CURL request in PHP

I'm trying to get the latest changes from my documentlist in Sharepoint using PHP and GetListItemChangesSinceToken. I'm using phpSPO as a SDK since there aren't any official Sharepoint SDK's for PHP.
So far I have this:
$payload = array(
'query' => array(
'__metadata' => array('type' => 'SP.ChangeLogItemQuery'),
'ViewName' => '',
'QueryOptions'=> '<QueryOptions><Folder>Shared Documents</Folder></QueryOptions>'
)
);
$headers = array();
$headers["X-HTTP-Method"] = "MERGE";
$changes = $this->request->executeQueryDirect($this->settings->URL . "/_api/web/Lists/GetByTitle('Documents')/GetListItemChangesSinceToken", $headers, $payload);
Which returns: {"error":{"code":"-2147467261, System.ArgumentNullException","message":{"lang":"en-US","value":"Value cannot be null.\r\nParameter name: query"}}}
I've tried changing the X-HTTP-Method and changing the array to fit the documented JSON/XML request (XML in JSON objects, come on Microsoft)
First approach
The following example demonstrates how to utilize GetListItemChangesSinceToken method:
$listTitle = "Documents";
$payload = array(
'query' => array(
'__metadata' => array('type' => 'SP.ChangeLogItemQuery'),
'ViewName' => '',
'QueryOptions'=> '<QueryOptions><Folder>Shared Documents</Folder></QueryOptions>'
)
);
$request = new ClientRequest($webUrl,$authCtx);
$options = array(
'url' => $webUrl . "/_api/web/Lists/GetByTitle('$listTitle')/GetListItemChangesSinceToken",
'data' => json_encode($payload),
'method' => 'POST'
);
$response = $request->executeQueryDirect($options);
//process results
$xml = simplexml_load_string($response);
$xml->registerXPathNamespace('z', '#RowsetSchema');
$rows = $xml->xpath("//z:row");
foreach($rows as $row) {
print (string)$row->attributes()["ows_FileLeafRef"] . "\n";
}
Second approach
Since SharePoint REST Client SDK for PHP now supports GetListItemChangesSinceToken method, the previous example could be invoked like this:
$list = $ctx->getWeb()->getLists()->getByTitle($listTitle);
$query = new ChangeLogItemQuery();
//to request all the items set ChangeToken property to null
$query->ChangeToken = "1;3;e49a3225-13f6-47d4-a146-30d9caa05362;635969955256400000;10637059";
$items = $list->getListItemChangesSinceToken($query);
$ctx->executeQuery();
foreach ($items->getData() as $item) {
print "[List Item] $item->Title\r\n";
}
More examples could be found here under phpSPO repository.

Resteasy service expecting 2 json objects

I have a service that expects 2 objects... Authentication and Client.
Both are mapped correctly.
I am trying to consume them as Json, but I'm having a hard time doing that.
If I specify just one parameter it works fine, but how can I call this service passing 2 parameters? Always give me some exception.
Here is my rest service:
#POST
#Path("login")
#Consumes("application/json")
public void login(Authentication auth, Client c)
{
// doing something
}
And here is my PHP consumer:
$post[] = $authentication->toJson();
$post[] = $client->toJson();
$resp = curl_post("http://localhost:8080/login", array(),
array(CURLOPT_HTTPHEADER => array('Content-Type: application/json'),
CURLOPT_POSTFIELDS => $post));
I tried some variations on what to put on CURLOPT_POSTFIELDS too but couldn't get it to work.
The problem you are probably having, is that you are declaring $post as a numbered array, which probably contains the array keys you are mapping. Basically, this is what you are giving it:
Array(
1 => Array(
'authentication' => 'some data here'
),
2 => Array(
'client' => 'some more data here'
)
)
When in reality, you should be creating the $post var like so:
Array(
'authentication' => 'some data here',
'client' => 'some more data here'
)
Try changing your code to something more like this (not optimal, but should get the job done):
$authentication = $authentication->toJson();
$client = $client->toJson();
$post = array_merge($authentication, $client);
$resp = curl_post("http://localhost:8080/login", array(),
array(CURLOPT_HTTPHEADER => array('Content-Type: application/json'),
CURLOPT_POSTFIELDS => $post));

Categories