about pagination gmail api with php - php

I listed the messages in My App successfully. Now I need to paginate the messages
(about 8 in every page). I followed the doc of google but it only gives a pageToken but how to make it work?

If you list messages, and there still are more results to fetch, the response will contain a nextPageToken.
Request
userId = me
maxResults = 8
GET https://www.googleapis.com/gmail/v1/users/me/messages?maxResults=8&access_token={YOUR_API_KEY}
Response
{
"messages": [
{
"id": "151596a5055b9412",
"threadId": "151596a5055b9412"
},
{
"id": "1515915d0fcfd685",
"threadId": "1515915d0fcfd685"
},
{
"id": "15158e6826ed7587",
"threadId": "15158e6826ed7587"
},
{
"id": "15158e0e37572671",
"threadId": "15158e0e37572671"
},
{
"id": "151586443b5b309a",
"threadId": "151586443b5b309a"
},
{
"id": "15157c4b11732c5c",
"threadId": "1510f004b81a9de2"
},
{
"id": "151576512d37c9ec",
"threadId": "1515765122918d37"
},
{
"id": "1515765122918d37",
"threadId": "1515765122918d37"
}
],
"nextPageToken": "01770178536732383613", // Here it is!
"resultSizeEstimate": 26
}
Just include this value as the pageToken in the next request.
Request
userId = me
maxResults = 8
pageToken = 01770178536732383613
GET https://www.googleapis.com/gmail/v1/users/me/messages?maxResults=8&pageToken=01770178536732383613&access_token={YOUR_API_KEY}
Response
{
"messages": [
{
"id": "1515762549119366",
"threadId": "1513f096ab90fdab"
},
{
"id": "15157616d03a66a1",
"threadId": "1513f096ab90fdab"
},
{
"id": "151575f958ac69e8",
"threadId": "1513338849950602"
},
{
"id": "1515756737710843",
"threadId": "1515756737710843"
},
{
"id": "1515756735412b45",
"threadId": "1515756735412b45"
},
{
"id": "1515756710eed602",
"threadId": "1515756710eed602"
},
{
"id": "15157567089a24b0",
"threadId": "15157567089a24b0"
},
{
"id": "151574a87fefe71d",
"threadId": "151336e890f46a2c"
}
],
"nextPageToken": "13534757816909071635",
"resultSizeEstimate": 27
}
When there is no nextPageToken in the response you have fetched every result there is.

The solution that I found is storing in an array of the front all the tokens that it brings you to be able to go forward and backward between pages, being the index of the array the pages, if it does not bring you the nextPageToken it is because it is the last one, then you pass the current token (of the page where you are) as parameter, and it brings you the list of emails of that page.

Related

PHP Quickbooks SDK - Batch requests and handling failures

I've building out a small app that connects to a Quickbooks API via an SDK. The SDK provides batch operations to help reduce the number of API requests needed.
However, I'm hoping to make a large amount of requests (ie: bulk deletes, uploads in the 100s/1000s). I've gotten the deletes to work, however, now I'm hoping to integrate Laravel's Queue system so that any items in the $batch that fail (due to these business-rules or other reasons) are sent to a worker who will reattempt them after waiting a minute .
Below is an example of a delete request.
class QuickBooksAPIController extends Controller
{
public function batchDelete(Request $request, $category)
{
$chunks = array_chunk($request->data, 30);
foreach ($chunks as $key => $value) {
$batch[$key] = $this->dataService()->CreateNewBatch();
foreach ($value as $id) {
$item = $this->dataService()->FindById($category, $id);
$batch[$key]->AddEntity($item, $id, "delete");
}
$batch[$key]->Execute();
}
return response()->json(['message' => 'Items Deleted'], 200);
}
}
The documentations are a bit sparse for my scenario though. How can I get the failed batch items on order to try again?
Is using batches even the right choice here? Because I have to hit the API anyway to get the $item... which doesn't make sense to me (I think I'm doing something wrong there).
EDIT:
I intentionally sent out a request with more then 30 items and this is the failure message. Which doesn't have the values that didn't make the cut.
EDIT#2:
Ended up using array_chunk to separate the payload into 30 items (which is the limit of the API). Doing so helps process many requests. I've adjusted my code above to represent my current code.
How can I get the failed batch items on order to try again?
If you look at Intuit's documentation, you can see that the HTTP response the API returns contains this information. Here's the example request they show:
{
"BatchItemRequest": [
{
"bId": "bid1",
"Vendor": {
"DisplayName": "Smith Family Store"
},
"operation": "create"
},
{
"bId": "bid2",
"operation": "delete",
"Invoice": {
"SyncToken": "0",
"Id": "129"
}
},
{
"SalesReceipt": {
"PrivateNote": "A private note.",
"SyncToken": "0",
"domain": "QBO",
"Id": "11",
"sparse": true
},
"bId": "bid3",
"operation": "update"
},
{
"Query": "select * from SalesReceipt where TotalAmt > '300.00'",
"bId": "bid4"
}
]
}
And the corresponding response:
{
"BatchItemResponse": [
{
"Fault": {
"type": "ValidationFault",
"Error": [
{
"Message": "Duplicate Name Exists Error",
"code": "6240",
"Detail": "The name supplied already exists. : Another customer, vendor or employee is already using this \nname. Please use a different name.",
"element": ""
}
]
},
"bId": "bid1"
},
{
"Fault": {
"type": "ValidationFault",
"Error": [
{
"Message": "Object Not Found",
"code": "610",
"Detail": "Object Not Found : Something you're trying to use has been made inactive. Check the fields with accounts, customers, items, vendors or employees.",
"element": ""
}
]
},
"bId": "bid2"
},
{
"Fault": {
"type": "ValidationFault",
"Error": [
{
"Message": "Stale Object Error",
"code": "5010",
"Detail": "Stale Object Error : You and root were working on this at the same time. root finished before you did, so your work was not saved.",
"element": ""
}
]
},
"bId": "bid3"
},
{
"bId": "bid4",
"QueryResponse": {
"SalesReceipt": [
{
"TxnDate": "2015-08-25",
"domain": "QBO",
"CurrencyRef": {
"name": "United States Dollar",
"value": "USD"
},
"PrintStatus": "NotSet",
"PaymentRefNum": "10264",
"TotalAmt": 337.5,
"Line": [
{
"Description": "Custom Design",
"DetailType": "SalesItemLineDetail",
"SalesItemLineDetail": {
"TaxCodeRef": {
"value": "NON"
},
"Qty": 4.5,
"UnitPrice": 75,
"ItemRef": {
"name": "Design",
"value": "4"
}
},
"LineNum": 1,
"Amount": 337.5,
"Id": "1"
},
{
"DetailType": "SubTotalLineDetail",
"Amount": 337.5,
"SubTotalLineDetail": {}
}
],
"ApplyTaxAfterDiscount": false,
"DocNumber": "1003",
"PrivateNote": "A private note.",
"sparse": false,
"DepositToAccountRef": {
"name": "Checking",
"value": "35"
},
"CustomerMemo": {
"value": "Thank you for your business and have a great day!"
},
"Balance": 0,
"CustomerRef": {
"name": "Dylan Sollfrank",
"value": "6"
},
"TxnTaxDetail": {
"TotalTax": 0
},
"SyncToken": "1",
"PaymentMethodRef": {
"name": "Check",
"value": "2"
},
"EmailStatus": "NotSet",
"BillAddr": {
"Lat": "INVALID",
"Long": "INVALID",
"Id": "49",
"Line1": "Dylan Sollfrank"
},
"MetaData": {
"CreateTime": "2015-08-27T14:59:48-07:00",
"LastUpdatedTime": "2016-04-15T09:01:10-07:00"
},
"CustomField": [
{
"DefinitionId": "1",
"Type": "StringType",
"Name": "Crew #"
}
],
"Id": "11"
}
],
"startPosition": 1,
"maxResults": 1
}
}
],
"time": "2016-04-15T09:01:18.141-07:00"
}
Notice the separate response object for each request.
The bId value is a unique value you send in the request, which is then echo'd back to you in the response, so you can match up the requests you send with the responses you get back.
Here's the docs:
https://developer.intuit.com/app/developer/qbo/docs/api/accounting/all-entities/batch#sample-batch-request
Is using batches even the right choice here?
Batches make a lot of sense when you are doing a lot of things all at once.
The way you're trying to use them is... weird. What you should probably be doing is:
Batch 1
- go find all your items
Batch 2
- delete all the items
Your existing code doesn't make sense because you're trying to both find the item and delete the item in the exact same batch HTTP request, which isn't possible via the API.
I intentionally sent out a request with more then 30 items and this is the failure message.
No, it's not. That's a PHP error message - you have an error in your code.
You need to fix the PHP error, and then look at the actual response you're getting back from the API.

JSON Post PHP (TypeForm)

I have never used JSON before so apologies if this is a simple request.
I have a webhook setup that sends me a JSON Post (Example Below) - I want to extract the two answers from this "text":"250252" & {"label":"CE"}
{
"event_id": "1",
"event_type": "form_response",
"form_response": {
"form_id": "VpWTMQ",
"token": "1",
"submitted_at": "2018-05-22T14:11:56Z",
"definition": {
"id": "VpWTMQ",
"title": "SS - Skill Change",
"fields": [
{
"id": "kUbaN0JdLDz8",
"title": "Please enter your ID",
"type": "short_text",
"ref": "9ac66945-899b-448d-859f-70562310ee5d",
"allow_multiple_selections": false,
"allow_other_choice": false
},
{
"id": "JQD4ksDpjlln",
"title": "Please select the skill required",
"type": "multiple_choice",
"ref": "a24e6b58-f388-4ea9-9853-75f69e5ca337",
"allow_multiple_selections": false,
"allow_other_choice": false
}
]
},
"answers": [
{
"type": "text",
"text": "250252",
"field": {
"id": "kUbaN0JdLDz8",
"type": "short_text"
}
},
{
"type": "choice",
"choice": {
"label": "CE"
},
"field": {
"id": "JQD4ksDpjlln",
"type": "multiple_choice"
}
}
]
}
}
I have this currently in my PHP file:
$data = json_decode(file_get_contents('php://input'));
$ID = $data->{"text"};
$Skill = $data->{"label"};
This does not work and all I get is null - Any help would really be appreciated, Thank You.
You need to look at the JSON object you're receiving to know the structure of the object you're receiving after using json_decode, what you're trying to get is in $data->form_response->answers, So you can have a variable for easier access:
$answers = $data->form_response->answers;
remember $answers is an array
So to achieve what you're trying to get, you can do:
$data = json_decode(file_get_contents('php://input'));
$answers = $data->form_response->answers;
$ID = $answers[0]->text;
$Skill = $answers[1]->choice->label;

Accessing array inside array

I'm working on my task right now, which accessing specific array when it is called by front end.
My example data is like this
{
"data": [
{
"name": "Jon Snow",
"id": "01-0001",
},
{
"name": "Robert Stark",
"id": "01-0002"
},
{
"name": "Sansa Stark",
"id": "01-002333"
},
{
"name": "Arya Stark",
"id": "01-00012"
},
{
"name": "Bran Stark",
"id": "01-0003"
},
{
"name": "Rickon Stark",
"id": "01-0005"
}
]
}
* In my front end I have this code *
selectedEmployee: any=null;
setActiveEmployee(employee: any) {
this.selectedEmployee = employee;
let myJSON = JSON.stringify(this.selectedEmployee);
this.perEmpLateEarly();
}
Whenever I choose the employee i get the id of that employee.
So in this, if i choose "id": "01-0001" it will return the first array and it will keep the rest, and if I choose "id": "01-0002" it will return the second one and will keep the rest and so on. How can I do that in Php?
Thanks in advance
You will do a GET/POST HTTP request from frontend, which would look something like this in
your_backend_page.php?id=<ID HERE>
Then the "your_backend_page.php" would look like as follows:
$list = { "data": [ { .... }, { ... }] } // this is the array you have
$idFromFrontEnd = $_GET["id"];
foreach ($list["data"] as $item) { // iterate over all items
if ($item["id"] == $idFromFrontEnd) { // check if id matches
echo json_decode($item); // if matches, print this item
}
}
Please note this approach is okay if you have a small number of items. For a larger list, you might want to have a database, where you can use sql to select.

php parse a Json file [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 6 years ago.
i'm using this API called "pollDaddy",
using php to retrieve json responses ..I've come across a little hiccup..
How do you get the total of each answer?
My json data:
{
"pdResponse": {
"partnerGUID": "3F2504E0-4F89-11D3-9A0C-0305E82C3301",
"userCode": "123456-FErKS5yu15scpSGmvip4JA==",
"demands": {
"demand": {
"result": {
"answers": {
"answer": [{
"text": "Yes",
"id": "23123124",
"total": "1074",
"percent": "89.13"
}, {
"text": "No",
"id": "23123125",
"total": "131",
"percent": "10.87"
}]
}, "id": "690432265"
}, "id": "GetPollResults"
}
}
}
}
First we have to decode the json data. so we use json_decode. Then we select the right element and loop through it to get all the anwers
$data = '{ "pdResponse": { "partnerGUID": "3F2504E0-4F89-11D3-9A0C-0305E82C3301", "userCode": "123456-FErKS5yu15scpSGmvip4JA==", "demands": { "demand": { "result": { "answers": { "answer": [{ "text": "Yes", "id": "23123124", "total": "1074", "percent": "89.13" }, { "text": "No", "id": "23123125", "total": "131", "percent": "10.87" }] }, "id": "690432265" }, "id": "GetPollResults" } } } }';
$response = json_decode($data);
$answers = $response->pdResponse->demands->demand->result->answers->answer;
foreach($answers as $a)
{
echo $a->total;
}

imploding array_keys from Facebook JSON data

Need some help with the sample code provided the facebook. I can't get it to return a series of IDs that I need to run a sql query against.
$friends = '{
"data": [
{
"name": "Paul",
"id": "12000"
},
{
"name": "Bonnie",
"id": "120310"
},
{
"name": "Melissa",
"id": "120944"
},
{
"name": "Simon",
"id": "125930"
},
{
"name": "Anthony",
"id": "120605"
},
{
"name": "David",
"id": "120733"
}
]
}';
$obj = json_decode($friends);
print $obj->{'data'}[0]->{'name'};
I can return the "Paul"
what I want is to return all the id's using implode(array_keys($obj),",")
I am only getting data to return.
What I'd like to do is retrieve all the IDs separated by a comma.
Thanks!
Try implode-ing on the data key with array_map:
function get_id($o) {
return $o->id;
}
implode(array_map('get_id', $obj->data),",")

Categories