I'm trying to make a call to a REST-API but it only returns 'BAD_REQUEST Unprocessable JSON'.
I've tried rewriting the input as the example I'm following, but it just gives me the same error.
This is the code I'm using for sending the request:
function callAPI($method, $url, $data)
{
$curl = curl_init();
$username = 'PK10008_e8f77aebdb0a';
$password = 'rwBmthNFK8JTbIL7';
switch($method)
{
case "POST":
curl_setopt($curl, CURLOPT_POST, 1);
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
}
//Options
curl_setopt($curl, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json'
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
$result = curl_exec($curl);
if(!$result)
{
die("Connection Failure");
}
curl_close($curl);
return $result;
}
And this is the code I'm using to create and send the information:
$data_array = array(
'purchase_country'=> 'SE',
'purchase_currency'=> 'SEK',
'locale'=> 'sv-SE',
'order_amount'=> 10,
'order_tax_amount'=> 0,
'order_lines' => array(
'type'=> 'physical',
'reference'=> '19-402',
'name'=> 'Test',
'quantity'=> 1,
'unit_price'=> 10,
'tax_rate'=> 0,
'total_amount'=> 10,
'total_discount_amount'=> 0,
'total_tax_amount'=> 0
)
);
$make_call = callAPI('POST', 'https://api.playground.klarna.com/payments/v1/sessions', json_encode($data_array));
$response = json_decode($make_call, true);
And this is the example:
POST /payments/v1/sessions
Authorization: Basic pwhcueUff0MmwLShJiBE9JHA==
Content-Type: application/json
{
"purchase_country": "SE",
"purchase_currency": "SEK",
"locale": "sv-SE",
"order_amount": 10,
"order_tax_amount": 0,
"order_lines": [{
"type": "physical",
"reference": "19-402",
"name": "Battery Power Pack",
"quantity": 1,
"unit_price": 10,
"tax_rate": 0,
"total_amount": 10,
"total_discount_amount": 0,
"total_tax_amount": 0
}]
}
The result I'm getting is this:
'BAD_REQUEST
Unprocessable JSON
1734c472-c9cb-4022-b469-a8231c7abeec'
But I should be getting some thing like this:
HTTP/1.1 200 OK
Content-Type: application/json
{
"session_id": "068df369-13a7-4d47-a564-62f8408bb760",
"client_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjAwMDAwMDAwMDAtMDAwMDAtMDAwMC0wMDAwMDAwMC0wMDAwIiwidXJsIjoiaHR0cHM6Ly9jcmVkaXQtZXUua2xhcm5hLmNvbSJ9.A_rHWMSXQN2NRNGYTREBTkGwYwtm-sulkSDMvlJL87M",
"payment_method_categories": [{
"identifier": "pay_later"
"name" : "Pay later.",
"asset_urls" : {
"descriptive" : "https://cdn.klarna.com/1.0/shared/image/generic/badge/en_us/pay_later/descriptive/pink.svg",
"standard" : "https://cdn.klarna.com/1.0/shared/image/generic/badge/en_us/pay_later/standard/pink.svg"
}
}]
}
The issue I was having was how json_encode creates encodes arrays. Instead of this: "example":[{
"ex": "ex"
}]
It did this:
"example":{
"ex": "ex"
}
Which in turn made the json unreadable to the end API
Related
Following a successful response from an API Request to M-PESA where the following JSON code is printed:
{ "MerchantRequestID":"2690XXXXXXX", "CheckoutRequestID":"xx_XX_2779308581984", "ResponseCode": "0", "ResponseDescription":"Success. Request accepted for processing", "CustomerMessage":"Success. Request accepted for processing" }
I would like to access the data sent to my callback url: https://xxxxxxxxxxxxxxxxx.ngrok.io/processL/transact.php . Despite expecting the code to change accordingly upon cancellation or payment, nothing happens although when I inspect the response on the ngrok local tunnel online interface, I see my expected results only that I do not know how to acquire and generate some action with them. Below is the code making the API Request and the results which I expect to be sent to my call back url but in vain.
<!-- transact.php -->
<?php
if (isset($_POST['submit'])) {
$Passkey = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$Amount= $_POST['amt'];
$BusinessShortCode = '174379';
$PartyA =$_POST['phone'];
$AccountReference =$_POST['name'];
$TransactionDesc = 'test';
$Timestamp =date('YmdHis');
$Password = base64_encode($BusinessShortCode.$Passkey.$Timestamp);
$headers=['Content-Type:application/json; charset=utf8'];
$initiate_url='https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest';
$callBackURL ='https://xxxxxxxxxxxxxxxxx.ngrok.io/processL/transact.php';
function accessToken() {
$ConsumerKey = 'ubYsxxxxxxxxxxxxx';
$ConsumerSecret = 'xxxxxxxxxxxxx';
$credentials = base64_encode($ConsumerKey.":".$ConsumerSecret);
$url = "https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Authorization: Basic ".$credentials,"Content-Type:application/json"));
curl_setopt($curl, CURLOPT_HEADER, false);
// curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$curl_response = curl_exec($curl);
$access_token=json_decode($curl_response);
curl_close($curl);
return $access_token->access_token;
}
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $initiate_url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json','Authorization:Bearer '.accessToken()));
$curl_post_data = array(
'BusinessShortCode' =>$BusinessShortCode,
'Password' => $Password,
'Timestamp' => $Timestamp,
'TransactionType' => 'CustomerPayBillOnline',
'Amount' => $Amount,
'PartyA' => $PartyA,
'PartyB' => $BusinessShortCode,
'PhoneNumber' => $PartyA,
'CallBackURL' => $callBackURL,
'AccountReference' => $AccountReference,
'TransactionDesc' => $TransactionDesc
);
$data_string = json_encode($curl_post_data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
$curl_response = curl_exec($curl);
print_r($curl_response."<br>");
}
Upon acceptance of payment:
{
"Body": {
"stkCallback": {
"MerchantRequestID": "xxxxxxxxxxxxx",
"CheckoutRequestID": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"ResultCode": 0,
"ResultDesc": "The service request is processed successfully.",
"CallbackMetadata": {
"Item": [
{
"Name": "Amount",
"Value": 1
},
{
"Name": "MpesaReceiptNumber",
"Value": "xxxxxxxxxxxxx"
},
{
"Name": "Balance"
},
{
"Name": "TransactionDate",
"Value": 20210927101413
},
{
"Name": "PhoneNumber",
"Value": xxxxxxxxxxxxx
}
]
}
}
}
};
When payment is cancelled:
{
"Body": {
"stkCallback": {
"MerchantRequestID": "xxxxxxxxxxxxx",
"CheckoutRequestID": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"ResultCode": 1032,
"ResultDesc": "Request cancelled by user"
}
}
};
I need some guidance.
The documentation for json_decode() is your friend. If you pass true as the second argument then it returns your JSON data as associative arrays.
$access_token=json_decode($curl_response, true);
// Check the response value
$result = $access_token['Body']['stkCallback']['ResultCode'] ?? null;
if ($result == 0) {
// Success
}
still trying to get my head around API's and connections.
I am trying to do a buy order to Binance but keep getting a 400 response. I know it's been an issue for some others but I just can't seem to suss out where I am going wrong. So hoping someone can help me out.
It's only issues with POST's, all the GET requests are working fine, and so to the signature and timestamp... or at least I am getting responses for my account so I assume so.
The first CURL is just for the serverTime, but the second CURL is for a buy/sell order.
This is the response I am getting now...
"Object ( [code] => -1102 [msg] => Mandatory parameter 'side' was not
sent, was empty/null, or malformed. )"
If I type the in the string manually it works just fine, but for one reason or another when I pass $qs it presents the above fault. I echoed $qs to the screen and copied that instead of passing $qs and it worked when I put in the new timestamp. I am stumped...
"symbol=TRXUSDC&side=SELL&type=LIMIT&timeInForce=GTC&quantity=63000.00000000&price=0.02550000&recvWindow=1000000×tamp=1550922237310"
any advice?
$header = array('X-MBX-APIKEY:' . KEY);
$url = BINANCE . 'api/v1/time';
$curl = curl_init();
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($curl, CURLOPT_TIMEOUT, 60);
curl_setopt($curl, CURLOPT_ENCODING, "");
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($curl, CURLOPT_URL,$url);
$response = curl_exec($curl);
if (FALSE === $response){
echo curl_error($curl), curl_errno($curl);
}
$serverTime = json_decode($response);
curl_close($curl);
$url = BINANCE . "api/v3/order";
$signature = NULL;
$queryString = NULL;
$query = array(
"symbol" => "TRXUSDC",
"side" => "SELL",
"type" => "LIMIT",
"timeInForce" => "GTC",
"quantity" => number_format(63000.00000000,8,'.',''),
"price" => number_format(0.02550000,8,'.',''),
"recvWindow" => 1000000,
"timestamp" => $serverTime->serverTime);
$qs = htmlentities(http_build_query(array_unique($query)));
$query['signature'] = hash_hmac('SHA256', $qs, SECRET );
$curl = curl_init();
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($curl, CURLOPT_TIMEOUT, 60);
curl_setopt($curl, CURLOPT_ENCODING, "application/x-www-form-urlencoded");
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl,CURLOPT_FAILONERROR,FALSE);
curl_setopt($curl, CURLOPT_VERBOSE, TRUE);
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS,$qs);
curl_setopt($curl, CURLOPT_URL, $url);
$response = curl_exec($curl);
if (FALSE === $response){
echo curl_error($curl).':'.curl_errno($curl);
}
$obj = json_decode($response);
curl_close($curl);
I tried this code and var_dump $qs
symbol=BTCUSDT&side=BUY&...
so I think you must remove amp;
Based on Binance spot api docs:
It is recommended to use a small recvWindow of 5000 or less! The max cannot go beyond 60,000!
so edit your query params with:
"symbol=TRXUSDC&side=SELL&type=LIMIT&timeInForce=GTC&quantity=63000.00000000&price=0.02550000&recvWindow=60000×tamp=1550922237310"
Also you can check your other query params with exchange info that you can get with https://api.binance.com/api/v3/exchangeInfo that we have for your symbol:
{
"symbol": "TRXUSDC",
"status": "TRADING",
"baseAsset": "TRX",
"baseAssetPrecision": 8,
"quoteAsset": "USDC",
"quotePrecision": 8,
"quoteAssetPrecision": 8,
"baseCommissionPrecision": 8,
"quoteCommissionPrecision": 8,
"orderTypes": [
"LIMIT",
"LIMIT_MAKER",
"MARKET",
"STOP_LOSS_LIMIT",
"TAKE_PROFIT_LIMIT"
],
"icebergAllowed": true,
"ocoAllowed": true,
"quoteOrderQtyMarketAllowed": true,
"isSpotTradingAllowed": true,
"isMarginTradingAllowed": false,
"filters": [
{
"filterType": "PRICE_FILTER",
"minPrice": "0.00001000",
"maxPrice": "1000.00000000",
"tickSize": "0.00001000"
},
{
"filterType": "PERCENT_PRICE",
"multiplierUp": "5",
"multiplierDown": "0.2",
"avgPriceMins": 5
},
{
"filterType": "LOT_SIZE",
"minQty": "0.10000000",
"maxQty": "9000000.00000000",
"stepSize": "0.10000000"
},
{
"filterType": "MIN_NOTIONAL",
"minNotional": "10.00000000",
"applyToMarket": true,
"avgPriceMins": 5
},
{
"filterType": "ICEBERG_PARTS",
"limit": 10
},
{
"filterType": "MARKET_LOT_SIZE",
"minQty": "0.00000000",
"maxQty": "659177.02430556",
"stepSize": "0.00000000"
},
{
"filterType": "MAX_NUM_ORDERS",
"maxNumOrders": 200
},
{
"filterType": "MAX_NUM_ALGO_ORDERS",
"maxNumAlgoOrders": 5
}
],
"permissions": [
"SPOT"
]
}
for other possible reasons check spot api docs in the link https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md
I tested the code and saw a few glitches in it :
$qs = htmlentities(http_build_query(array_unique($query)));
gave me an error ({"code":-1102,"msg":"Mandatory parameter 'side' was not sent, was empty/null, or malformed."}), so i replaced it with:
$qs = http_build_query(array_unique($query));
After that you created your signature, but never added it to you request. So do the following :
$signature = hash_hmac('sha256', $qs, $apiSecret);
$qs .= "&signature=" . $signature;
Also update your 'recvWindow' to a max of 60000 (I suggest 50000 or less (see the answer of #Tofiq Samali)) and you are ready to go!
I want to use API of the constant contact and want to insert user Email Ids using PHP script while user register to the website.
I using following code for this.
$data['addresses'][0]['address_type'] = 'BUSINESS';
$data['addresses'][0]['city'] = 'Belleville';
$data['addresses'][0]['country_code'] = 'CA';
$data['addresses'][0]['line1'] = '47 Shawmut Ave.';
$data['addresses'][0]['line2'] = 'Suite 404';
$data['addresses'][0]['postal_code'] = '"K8b 5W6';
$data['addresses'][0]['state_code'] = 'ON';
$data['lists'][0]['id'] = "1554397204";
$data['cell_phone'] = "555-555-5555";
$data['company_name'] = "System Optimzations";
$data['confirmed'] = false;
$data['email_addresses'][0]['email_address'] = "username112#example.com";
$data['fax'] = "555-555-5555";
$data['first_name'] = "Manvendra";
$data['home_phone'] = "555-555-5555";
$data['job_title'] = "Systems Analyst 3";
$data['last_name'] = "Rajpurohit";
$data['prefix_name'] = "Mr.Martone";
$data['work_phone'] = "555-555-5555";
$jsonstring = json_encode($data);
// echo '<pre>'; print_r($data);
$posturl = "https://api.constantcontact.com/v2/contacts?action_by=ACTION_BY_OWNER&api_key=*******";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $posturl);
//curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
// curl_setopt($ch, CURLOPT_USERPWD, $authstr);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonstring);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:application/json",'Authorization: Bearer *****
','Content-Length: ' . strlen($jsonstring)));
curl_setopt($ch, CURLOPT_HEADER, false); // Do not return headers
//curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0); // If you set this to 0, it will take you to a page with the http response
$response = curl_exec($ch);
if (FALSE === $response)
throw new Exception(curl_error($ch), curl_errno($ch));
echo '<pre>'; print_r($response); die;
curl_close($ch);
When I run this script then its showing following error.
[{"error_key":"json.payload.empty","error_message":"JSON payload cannot be empty."}]
Please help me that how can I resolve this error.
The actual problem is validation error,which is:-
[{"error_key":"json.max.length.violation","error_message":"#/prefix_name: Value exceeds maximum length of 4."}]
So what i did is changed:-
$data['prefix_name'] = "Mr.Martone";
To:-
$data['prefix_name'] = "tone"; // length need to be 4 or less only
And used this CURL request and data saved successfully.
<?php
$data['addresses'][0]['address_type'] = 'BUSINESS';
$data['addresses'][0]['city'] = 'Belleville';
$data['addresses'][0]['country_code'] = 'CA';
$data['addresses'][0]['line1'] = '47 Shawmut Ave.';
$data['addresses'][0]['line2'] = 'Suite 404';
$data['addresses'][0]['postal_code'] = '"K8b 5W6';
$data['addresses'][0]['state_code'] = 'ON';
$data['lists'][0]['id'] = "1554397204";
$data['cell_phone'] = "555-555-5555";
$data['company_name'] = "System Optimzations";
$data['confirmed'] = false;
$data['email_addresses'][0]['email_address'] = "username112#example.com";
$data['fax'] = "555-555-5555";
$data['first_name'] = "Manvendra";
$data['home_phone'] = "555-555-5555";
$data['job_title'] = "Systems Analyst 3";
$data['last_name'] = "Rajpurohit";
$data['prefix_name'] = "tone";
$data['work_phone'] = "555-555-5555";
$jsonstring = json_encode($data);
//echo '<pre>'; print_r($data);
$posturl = "https://api.constantcontact.com/v2/contacts?action_by=ACTION_BY_OWNER&api_key=*******";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $posturl);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonstring);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:application/json",'Authorization: Bearer ******')); //check change here
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);// this need to be 1
$response = curl_exec($ch);
if (FALSE === $response)
throw new Exception(curl_error($ch), curl_errno($ch));
echo '<pre>'; print_r($response); die;
curl_close($ch);
Output i got is:-
{
"id": "1519826644",
"status": "ACTIVE",
"fax": "555-555-5555",
"addresses": [{
"id": "9ac8fd40-c2b2-11e7-aa57-d4ae5284344f",
"line1": "47 Shawmut Ave.",
"line2": "Suite 404",
"line3": "",
"city": "Belleville",
"address_type": "BUSINESS",
"state_code": "ON",
"state": "Ontario",
"country_code": "ca",
"postal_code": "\"K8b",
"sub_postal_code": "5W6"
}],
"notes": [],
"confirmed": false,
"lists": [{
"id": "1554397204",
"status": "ACTIVE"
}],
"source": "API",
"email_addresses": [{
"id": "9a914b70-c2b2-11e7-aa57-d4ae5284344f",
"status": "ACTIVE",
"confirm_status": "NO_CONFIRMATION_REQUIRED",
"opt_in_source": "ACTION_BY_OWNER",
"opt_in_date": "2017-11-06T05:23:21.000Z",
"email_address": "username23333#example.com"
}],
"prefix_name": "tone",
"first_name": "Manvendra",
"middle_name": "",
"last_name": "Rajpurohit",
"job_title": "Systems Analyst 3",
"company_name": "System Optimzations",
"home_phone": "555-555-5555",
"work_phone": "555-555-5555",
"cell_phone": "555-555-5555",
"custom_fields": [],
"created_date": "2017-11-06T05:23:20.000Z",
"modified_date": "2017-11-06T05:23:20.000Z",
"source_details": "Web Devloping"
}
I'm trying to implement the Bing Spell Check API v7. This is my current function:
# spell check
function bing_spell_check($q, $lang) {
$param = array();
$param['appName'] = PRO_NAME;
$param['text'] = $q;
$param['setLang'] = $lang;
$url = 'https://api.cognitive.microsoft.com/bing/v7.0/SpellCheck?'.http_build_query($param);
$process = curl_init();
curl_setopt($process, CURLOPT_URL, $url);
curl_setopt($process, CURLOPT_TIMEOUT, 10);
curl_setopt($process, CURLOPT_RETURNTRANSFER, true);
curl_setopt($process, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($process, CURLOPT_HTTPHEADER,
array(
'Accept: application/ld+json',
'Ocp-Apim-Subscription-Key: '.PRO_BING_KEY_SPELL
)
);
$response = curl_exec($process);
return $response;
}
The problem is that this example:
print_r(bing_spell_check('en', 'whts yur name?'));
Returns:
{
"#context":{
"#vocab":"http:\/\/bingapis.com\/v7\/schemas\/",
"s":"http:\/\/schema.org\/",
"#base":"https:\/\/api.cognitive.microsoft.com\/api\/v7\/"
},
"#type":"SpellCheck",
"flaggedTokens":[
]
}
Which means it has not found any errors. I ran the very same test in Bing's test tool, and I received this structure instead:
{
"_type": "SpellCheck",
"FlaggedTokens": [
{
"Offset": 0,
"Token": "whts",
"Type": "UnknownToken",
"Suggestions": [
{
"suggestion": "what's",
"Score": 0.909352914464075
},
{
"suggestion": "whats",
"Score": 0.810588859407343
},
{
"suggestion": "what is",
"Score": 0.680176771139565
}
]
},
{
"Offset": 5,
"Token": "yur",
"Type": "UnknownToken",
"Suggestions": [
{
"suggestion": "your",
"Score": 0.909352914464075
}
]
}
]
}
Am I missing something. Any ideas? Thanks!
It is quite simple, you just mixed up your function parameters. You have
function bing_spell_check($q, $lang) {}
and
bing_spell_check('en', 'whts yur name?');
That is where the problem starts, $q is now en and $lang is now whts yur name?. Thus when you create your $param array you have the language and the text mixed up (which will cause the Spell Check API to silently fail). You can simply fix this by changing the parameter order:
function bing_spell_check($lang, $q) {}
Now your code
<?php
define(PRO_BING_KEY_SPELL, 'XXX');
define(PRO_NAME, 'XXX');
function bing_spell_check($lang, $q) {
$param = array();
$param['appName'] = PRO_NAME;
$param['text'] = $q;
$param['setLang'] = $lang;
$url = 'https://api.cognitive.microsoft.com/bing/v7.0/spellcheck?'.http_build_query($param);
$process = curl_init();
curl_setopt($process, CURLOPT_URL, $url);
curl_setopt($process, CURLOPT_TIMEOUT, 10);
curl_setopt($process, CURLOPT_RETURNTRANSFER, true);
curl_setopt($process, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($process, CURLOPT_HTTPHEADER,
array(
'Accept: application/ld+json',
'Ocp-Apim-Subscription-Key: '.PRO_BING_KEY_SPELL
)
);
$response = curl_exec($process);
return $response;
}
print_r(bing_spell_check('en', 'whts yur name?'));
?>
results in
{
"#context": {
"#vocab": "http:\/\/bingapis.com\/v7\/schemas\/",
"s": "http:\/\/schema.org\/",
"#base": "https:\/\/api.cognitive.microsoft.com\/api\/v7\/"
},
"#type": "SpellCheck",
"flaggedTokens": [{
"offset": 0,
"token": "whts",
"type": "UnknownToken",
"suggestions": [{
"suggestion": "what's",
"score": 0.909352914464075
}, {
"suggestion": "whats",
"score": 0.810588859407343
}, {
"suggestion": "what is",
"score": 0.680176771139565
}]
}, {
"offset": 5,
"token": "yur",
"type": "UnknownToken",
"suggestions": [{
"suggestion": "your",
"score": 0.909352914464075
}]
}]
}
I need to decode a JSON fragment so that I can start manipulating JSON, but json_decode returns null, when I try to read using curl.
PHP code:
$username='xx';
$password='xx';
$headers = array(
'Content-Type:application/json',
'accept: application/json',
'Authorization: Basic '. base64_encode($username.":".$password),
'x-myobapi-exotoken: xx'
);
$url = "http://example.com";
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_USERPWD, $username.":".$password);
curl_setopt($ch, CURLOPT_URL, $url);
$output = curl_exec($ch);
echo '<pre>';
echo $output; //works fine till here
echo "<br><br>Break <br>";
//all the commented part has been tried
//$my_array = json_decode(str_replace ('\"','"', $output), true);
//var_dump($my_array);
// print_r(json_decode(substr($output,3))); //tried already
$obj = json_decode($output);
var_dump($obj);//gives NULL
print $obj->{'firstname'};
curl_close($ch);
The output was as follows in Google Chrome :
Output:
HTTP/1.1 200 OK
Content-Length: 675
Content-Type: application/json; charset=utf-8
Server: Microsoft-HTTPAPI/2.0
Link: ; rel="describedBy"; method="PUT",; rel="describedBy"; method="POST"
Date: Tue, 12 Aug 2014 07:30:48 GMT
{
"jobtitle": null,
"firstname": "XYZ",
"lastname": "XYZ",
"fullname": "XYZ XYZ",
"directphonenumber": null,
"mobilephonenumber": null,
"email": null,
"postaladdress": {
"line1": "",
"line2": "",
"line3": "",
"line4": "",
"line5": ""
},
"postalcode": "",
"deliveryaddress": {
"line1": "",
"line2": "",
"line3": "",
"line4": "",
"line5": "",
"line6": ""
},
"advertsourceid": 0,
"active": true,
"optoutemarketing": false,
"salespersonid": 10,
"defaultcompanyid": null,
"extrafields": [],
"id": 129,
"href": "http://example.com"
}
Break
NULL
Reply
Forward
The comments in the PHP code will show everything that I've tried and all the available solutions already.
CURLOPT_HEADER option use false, because header is coming with response
curl_setopt($ch, CURLOPT_HEADER, false);
Your $output variable contains header, you should use the following option:
curl_setopt($ch, CURLOPT_HEADER, false);
or get headers length and remove it from output (so only body remains):
$info = curl_getinfo($ch);
$result = substr($output, $info['header_size']);