I have the following json, I'm sending through AJAX, but in the server side the json_decode returning an empty array. I'm sending different values as well, and in that case it's working fine. I check int this link, and this is a valid JSON.
[
{
"name": "bettype",
"value": "All"
},
{
"name": "bookies",
"value": "Interwetten"
},
{
"name": "sporttype",
"value": "Soccer"
},
{
"name": "team1",
"value": "Braunschweig"
},
{
"name": "team2",
"value": "Bayern Munich"
},
{
"name": "league",
"value": "Germany DFB Cup (90`)"
}
]
UPDATED:
this is the server side code:
var_dump((stripslashes($_GET['data']));
var_dump(json_decode(stripslashes($_GET['data'])));
and this is the output:
string(244) "[{"name":"bettype","value":"All"},{"name":"bookies","value":"Interwetten"},{"name":"sporttype","value":"Soccer"},{"name":"team1","value":"Braunschweig"},{"name":"team2","value":"Bayern Munich"},{"name":"league","value":"Germany DFB Cup (90�)"}]" NULL
It works fine for me.
http://sandbox.phpcode.eu/g/80941.php
Check your browser configuration/charset and try again
Related
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.
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.
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;
I'm trying to create a game API thing that requires this decoded, but I'm not sure how (this is just for a certain user, so the values wont be the same)
[
{
"Id": 382779,
"Name": "DarkAge Ninjas"
},
{
"Id": 377291,
"Name": "Emerald Knights of the Seventh Sanctum"
},
{
"Id": 271454,
"Name": "Knights of RedCliff"
},
{
"Id": 288278,
"Name": "Knights of the Splintered Skies "
},
{
"Id": 375307,
"Name": "Korblox's Empire"
},
{
"Id": 387867,
"Name": "Ne'Kotikoz"
},
{
"Id": 696519,
"Name": "Orinthians"
},
{
"Id": 27770,
"Name": "Retexture Artists Official Channel"
},
{
"Id": 585932,
"Name": "Retexturing Apprentices "
},
{
"Id": 7,
"Name": "Roblox"
},
{
"Id": 679727,
"Name": "ROBLOX Community Staff and Forum Users"
},
{
"Id": 127081,
"Name": "Roblox Wiki"
}
]
How can I decode this in PHP so It has a list like
DarkAge Ninjas
Emerald Knights of the Seventh Sanctum
Knights of RedCliff
etc, and have the Id decoded separately so I can make a clickable link out of it :/
You will need json_decode to turn json into php array
$api_json = '[
{ "Id": 382779, "Name": "DarkAge Ninjas" },
{ "Id": 377291, "Name": "Emerald Knights of the Seventh anctum" }
...
]';
$api_data = json_decode($api_json, true);
//Now you can loop over the array and print the `Name`
foreach($api_data as $d) {
echo $d['Name'];
}
above code will output
DarkAge Ninjas
Emerald Knights of the Seventh Sanctum
Knights of RedCliff
...
To make link with ids just add this in above loop
echo ''. $d['Name'].'';
as Ed Cottrell suggested, Read the manual: json_decode to know more
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.