Representing non-unique key-value pairs in Python - php

I am doing some work with the Yahoo Gemini API that uses PHP. My current goal is requesting reports through it using Python code.
In PHP, you would create a request using these types of arguments appended to the request:
"fields": [
{ "field": "Ad ID" },
{ "field": "Day" },
{ "alias": "My dummy column", "value": "" },
{ "field": "Impressions" },
{ "field": "Ad Image URL", "alias": "url" }
],
No problem, I type the data and then convert it to a dictionary.
fields_to_include = [('field', 'Campaign ID'), ('field', 'Day'), ('field', 'Impressions'), ('field', 'Clicks'), ('field', 'CTR')]
fields_to_include = dict(fields_to_include)
filters_to_include = [('field', 'Advertiser ID'),('operator','='),('value', str(advertiser_id))]
filters_to_include = dict(filters_to_include)
I get this error:
TypeError: 'dict' object is not callable
All the other answers on this site do not seem to be similar to this. What is going wrong here?

You've previously named a variable 'dict', which has shadowed the dict built-in.
However, that code would not give you what you want; it produces a single dict, which only has one value (because you can't have multiple keys with the same name). What you want is a list of dicts.
I don't understand why you don't hard code it exactly as you did in PHP.
fields_to_include = [
{ "field": "Ad ID" },
{ "field": "Day" },
{ "alias": "My dummy column", "value": "" },
{ "field": "Impressions" },
{ "field": "Ad Image URL", "alias": "url" }
]

Related

PHP able to receive post request with a raw text but its giving error when post same data raw json

I'm posting data to my API endpoint. it's simple JSON data. But I'm getting error 404 when posting data as raw JSON but if I post the same data at the same endpoint as raw text its works.
working as raw text
getting error 404 as raw JSON
<?php
var_dump(http_response_code());
echo "hello";
var_dump($_POST);
echo file_get_contents("php://input");
I have removed all code from the API end point and just trying to print post data.
Sample JSON :
{
"object": "whatsapp_business_account",
"entry": [
{
"id": "456",
"changes": [
{
"value": {
"messaging_product": "whatsapp",
"metadata": {
"display_phone_number": "123456789",
"phone_number_id": 123456789
},
"contacts": [
{
"profile": {
"name": "NAME"
},
"wa_id": 123456789
}
],
"messages": [
{
"from": 123456789,
"id": "wamid.ID",
"timestamp": 123456789,
"text": {
"body": "MESSAGE_BODY"
},
"type": "text"
}
]
},
"field": "messages"
}
]
}
]
}
I have checked JSON and it's a valid JSON. no special character but still unable to solve this issue.
One more thing its working on my local machine under XAMPP but not on Linux shared server.

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.

Google Fit API Cannot add most of the scopes

I am using the Google Fit REST API for our current project. We can add some of the data sources but there are some we cannot add. We already followed the documentations. Some of the request are returning this kind of error message (we even tried in their OAuth playground)
"error": {
"status": "INVALID_ARGUMENT",
"message": "Data type does not match well-known data type with the same name",
"code": 400,
"errors": [
{
"reason": "invalidArgument",
"message": "Data type does not match well-known data type with the same name",
"domain": "global"
}
]
}
What we are trying to add is this data source which we already allow the permission scopes of
https://www.googleapis.com/auth/fitness.activity.read
https://www.googleapis.com/auth/fitness.activity.write
{
"application": {
"name": "PersonalPulse",
"version": "1.0.0"
},
"dataType": {
"name": "com.google.activity.exercise",
"field": [
{
"name": "exercise",
"format": "integer"
},
{
"name": "repetitions",
"format": "integer"
},
{
"name": "resistance type",
"format": "integer"
},
{
"name": "resistance",
"format": "floatPoint"
},
{
"name": "duration",
"format": "integer"
}
]
},
"device": {
"manufacturer": "browser",
"model": "browser",
"type": "unknown",
"uid": "2",
"version": "10"
},
"type": "derived"
}
We followed the instructions based on the documentations here
https://developers.google.com/fit/datatypes/activity#workout
We are using PHP/Laravel framework for the fitness api and cURL for the http requests. If someone got an idea why we got the error please help. Thanks.
You can also try in the google playground here and paste the scopes https://developers.google.com/oauthplayground/
The first problem with your request is that you're passing in the exercise is an integer field, but the documentation says that you need to pass in one of an enumerated set of strings (I don't know why it says int there, but if you click the "Accepted values", you can see those definitely aren't integers...).
However, it would be easier if you didn't specify the fields at all. Simply specify the data type name:
// ...
"dataType": {
"name": "com.google.activity.exercise",
}
// ...
and the correct fields will be filled in on the backend and returned to you.

Decode json in php and create variables

I a trying to decode a json callback.
The json code is posted to callback.php - Here is an example of the json:
{
"order": {
"id": "5RTQNACF",
"created_at": "2012-12-09T21:23:41-08:00",
"status": "completed",
"total_btc": {
"cents": 100000000,
"currency_iso": "BTC"
},
"total_native": {
"cents": 1253,
"currency_iso": "USD"
},
"custom": "order1234",
"receive_address": "1NhwPYPgoPwr5hynRAsto5ZgEcw1LzM3My",
"button": {
"type": "buy_now",
"name": "Alpaca Socks",
"description": "The ultimate in lightweight footwear",
"id": "5d37a3b61914d6d0ad15b5135d80c19f"
},
"transaction": {
"id": "514f18b7a5ea3d630a00000f",
"hash": "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b",
"confirmations": 0
},
"customer": {
"email": "coinbase#example.com",
"shipping_address": [
"John Smith",
"123 Main St.",
"Springfield, OR 97477",
"United States"
]
}
}
}
I can echo the json and get the following response:
{"order""id":null,"created_at":null,"status":"completed","total_btc":{"cents":100000000,"currency_iso":"BTC"},"total_native":{"cents":83433,"currency_iso":"USD"},"custom":"123456789","receive_address":"1A2qsxGHo9KjtWBTnAopTwUiBQf2w6yRNr","button":{"type":"buy_now","name":"Test Item","description":null,"id":null},"transaction":{"id":"52d064b59eeb59985e00002c","hash":"4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b","confirmations":0}}}
However if I try to decode the json using the following:
$array = json_decode($jsonString, true);
echo $array;
I get the following response: "200 Array"
I want to be able turn each json parameter in to a php variable.
You can access the variables within $array, for example by doing:
echo $array['custom']; // prints out "order1234"
You don't want to extract the variables directly into the local lexical scope of your program as that would create security concerns. Just use the data as indicated in the snippet above.

Facebook - Get & Display me/og.likes in Video application

Have built an video app that publish user actions towards Facebook.
In this app i have implemented an "Favorite" function that i have hooked up towards a basic open graph action "og.like"
I want to be able to display video's that user liked and apply my own styling to that.
Basically i want to display "Title" "Url" & "Image"
So i use the PHP-SDK towards authored user with active access token and execute
$response = $facebook->api(
'me/og.likes',
'GET'
);
// handle the response
How do i now sort out my correct fields and display them ?
Am not hardcore at either php or javascript but will be able to sort this out if i just can get a little push in the right direction. Like just showing the raw data
Update
Finally a little progress, adding
print_r ($response);
Will write out the raw data, Now i know that am on the right way.
Array returned
{
"data": [
{
"id": "123",
"from": {
"name": "Mathias",
"id": "APP_ID"
},
"start_time": "X",
"end_time": "X",
"publish_time": "X",
"application": {
"name": "APP_Name",
"namespace": "",
"id": "321"
},
"data": {
"object": {
"id": "139",
"url": "Url to like",
"type": "video.tv_show",
"title": "title"
}
},
"type": "og.likes",
"no_feed_story": false,
"likes": {
"count": 0,
"can_like": true,
"user_likes": false
},
"comments": {
"count": 0,
"can_comment": true,
"comment_order": "chronological"
}
},
And then the next..
From every app "like" i would like to display Url ,Title & Image
From what i understand so far my main problem is that this is nested arrays, Did try with single level arrays and there i did manage to display correct data just by
echo $response[name];
So how do i digg in and loop this around, All tips are welcome,
{
"id": "139",
"url": "url",
"type": "video.tv_show",
"title": "titke",
"image": [
{
"url": "image_URL",
"secure_url": "image_URL",
"type": "image/jpg",
"width": 1024,
"height": 576
}
Here's an example:
<?php foreach ( $response['data'] as $data ): ?>
<?php $Object = $data['data']['object']; ?>
<?php echo $Object['title']; ?><br />
<?php endforeach; ?>

Categories