Sorry for the bad title, but I don't know how to create following JSON in PHP:
{
"id":"1",
"method":"getData",
"params":{
"options":{
"element":{
"id":"1a_ext",
"type":1,
"keyType":"externalkey"
},
"moreInfo":true,
"userFields":[
"id",
"name",
"longname",
"externalkey"
]
}
},
"jsonrpc":"2.0"
}
I don't know to do the part after "params" (how do I "put" options "into" params) - for the other parts I know what I have to do:
public static function getData(){
$json = array(
"id" => self::id(),
"method" => "getData",
"params" => array(
"id" => self::$userid,
"type" => self::$type
),
"jsonrpc" => "2.0"
);
$json = json_encode($json, true);
return self::request($json);
}
I would really appreciate your help, thanks!
You directly can assign to the params keys like
$json['params']['options'] = $your_options;
Full version of your code as an example
public static function getData(){
$json = array(
"id" => self::id(),
"method" => "getData",
"params" => array(
"id" => self::$userid,
"type" => self::$type
),
"jsonrpc" => "2.0"
);
# add something to param index
$json['params']['options'] = $your_options;
$json = json_encode($json, true);
return self::request($json);
}
You can create the this in array format in PHP and then JSON encode:
$arr = [
'id' => 1,
'method' => 'getData',
'params' => [
'options' => [
'element' => [
'id' => '1a_ext',
'type' => 1,
'keyType' => 'externalKey'
],
'moreInfo' => true,
'userFields' => [
'id',
'name',
'longname',
'externalKey'
]
]
],
'jsonrpc' => '2.0'
];
$json = json_encode($arr);
Instead of spoonfeeding, i would like to help related, Whenever if you find difficulties to create an array representation of a JSON then you should use var_export(array, true) the second parameter must be true to return the variable representation instead of outputting it
<?php
$json_str = '{
"id": "1",
"method": "getData",
"params": {
"options": {
"element": {"id": "1a_ext", "type": 1, "keyType": "externalkey"},
"moreInfo": true,
"userFields": ["id", "name", "longname", "externalkey"]
}
},
"jsonrpc": "2.0"
}';
$json_arr = var_export(json_decode($json_str, true), true);
print_r($json_arr);
check the output here https://paiza.io/projects/eUZZDsTsSFSM4m9WMl05Ow
$json_arr is an array representation for your JSON, now you can dynamic the array values
Related
I'm having a hard time using a method setData() of the HttpBody class. I'm passing the parameter to the method as an object, but I recieve an error message.
How do I pass the parameter:
public function create(string $resource, $body)
{
$client = $this->googleClient();
$service = new CloudHealthcare($client);
$parent = "projects/my_project_id/locations/my_location/datasets/my_dataset/fhirStores/repository";
$httpBody = new HttpBody();
$httpBody->setContentType('application/fhir+json;charset=utf-8');
$httpBody->setData([
"resourceType" => "Patient",
"id" => "23434",
"meta" => [
"versionId" => "12",
"lastUpdated" => "2014-08-18T15:43:30Z"
],
"text" => [
"status" => "generated",
"div" => "<!-- Snipped for Brevity -->"
],
"extension" => [
[
"url" => "http://example.org/consent#trials",
"valueCode" => "renal"
]
],
"identifier" => [
[
"use" => "usual",
"label" => "MRN",
"system" => "http://www.goodhealth.org/identifiers/mrn",
"value" => "123456"
]
],
"name" => [
[
"family" => [
"Levin"
],
"given" => [
"Henry"
],
"suffix" => [
"The 7th"
]
]
],
"gender" => [
"text" => "Male"
],
"birthDate" => "1932-09-24",
"active" => true
]);
$data = $service->projects_locations_datasets_fhirStores_fhir->create($parent, $resource, $httpBody);
return $data;
}
Following the error message I get.
The error says I didn't pass the resourceType field, but it was passed:
Google\Service\Exception: {
"issue": [
{
"code": "structure",
"details": {
"text": "unparseable_resource"
},
"diagnostics": "missing required field \"resourceType\"",
"expression": [
""
],
"severity": "error"
}
],
"resourceType": "OperationOutcome"
} in file /usr/share/nginx/vendor/google/apiclient/src/Http/REST.php on line 128
How should I pass the parameter to receive the success message?
Tkanks!
I haven't tried the PHP client libraries specifically, but for most languages you don't want to use the HttpBody class - it's an indication that the method accepts something in the body of the request that is just text from the perspective of the method signature. I would try passing the JSON string directly.
I can't figure out how unit testing works.
I have controller which returns a JSON response
Controller.php
public function getDiscount(Request $request)
{
if (isset($request) && !empty($request)) {
return response()->json($this->discount->calculateDiscount($request->json()->all()))->getOriginalContent();
}
}
With postman, this is the result of this route:
Post by client:
{
"customer-id": "3",
"items": [
{
"product-id": "A101",
"quantity": "2",
"unit-price": "9.75",
"total": "19.50"
},
{
"product-id": "A102",
"quantity": "1",
"unit-price": "49.50",
"total": "49.50"
}
],
"total": "69.00"
}
Response by API
{
"applied_discounts": [
{
"id": 3,
"name": "Tools Discount",
"description": "Seems like you really like Tools, here's one for free!"
}
],
"discounted_items": [
{
"product-id": "A101",
"quantity": "2",
"unit-price": "9.75",
"total": "19.50",
"discounted_price": 15.6
}
],
"discounted_price": 65.1,
"original_price": "69.00"
}
Now when I try to make unit test, this is what I came up with:
public function testToolsDiscount()
{
$this->json('POST', '/discount',
[
'customer-id' => '3',
'items' => [
[
'product-id' => 'A101',
'quantity' => '2',
'unit-price' => '9.75',
'total' => '19.50'
],
[
'product-id' => 'A102',
'quantity' => '1',
'unit-price' => '49.50',
'total' => '49.50'
]
],
'total' => '69.00'
])
->seeJson(
[
'applied_discounts' => [
[
'id' => 3,
]
],
]);
}
However when I run it, this is the error I get
DiscountTest::testToolsDiscount Invalid JSON was returned from the
route. Perhaps an exception was thrown?
What am I doing wrong?
Make sure your route matches the specified '/discount' with any prefix it may have.
Define the proper route,
I recommend using action() Helper function to add url, the main benefits of this function is when you change some text or prefix in route,
Let say you change from /discount to /discounts in these case you don't need to change the route everywhere.
action('ControllerName#actionName');
It's possible your post-body needs to be an actual JSON string, rather than an associative array. It's also possible that the json() method requires a fully-qualified URL instead of a relative path. If either is the case, this solution may not actually expose the problem, you'll just have to try them and see. Otherwise, try this, it should at least offer some clues as to what's going wrong. Add the following to your unit-test class and dd() the results.
/**
* #param string $uri
* #param string $method
* #param array $body
* #param array $headers
* #param array $files
* #param array $cookies
* #return array
*/
public function callRoute(
$uri,
$method = 'GET',
array $body = [],
array $headers = [],
array $files = [],
array $cookies = []
) {
foreach ($cookies as $name => $cookie) {
$this->app->resolving(\App\Http\Middleware\EncryptCookies::class, function (\App\Http\Middleware\EncryptCookies $cookie) use ($name) {
$cookie->disableFor($name);
});
}
$uri = trim($uri, '/');
$uriParts = parse_url($uri);
//This value may be based on the APP_URL value in your .env, I'm not really sure.
$root = !array_get($uriParts, 'host') ? trim(app(\Illuminate\Http\Request::class)->root(), '/').'/' : '';
$uri = "$root$uri";
$server = $this->transformHeadersToServerVars($headers);
$response = $this->call($method, $uri, $body, $cookies, $files, $server);
$headers = $response->headers->all();
$code = $response->getStatusCode();
$json = $content = $response->getContent();
$json = json_decode($json, true);
$content = ($json && json_last_error() == JSON_ERROR_NONE) ? $json : $content;
return compact('code', 'headers', 'content');
}
I'd be willing to bet the following will expose an error message and stack trace. You'll likely have to follow it up with some other dd() statements in your target controller, or wherever else your logic lives after that error points you in the right direction:
$body = [
'customer-id' => '3',
'items' => [
[
'product-id' => 'A101',
'quantity' => '2',
'unit-price' => '9.75',
'total' => '19.50'
],
[
'product-id' => 'A102',
'quantity' => '1',
'unit-price' => '49.50',
'total' => '49.50'
]
],
'total' => '69.00'
];
$response = $this->callRoute('POST', '/discount', $body)['content'];
dd($response);
I am trying to highlight my results in elastic search-php , I tried a lot with my knowledge and searching in google, but no luck , the same query is working perfectly in Sense. my query in Sense is
GET /bank/account/_search
{
"query" : {
"match_phrase" : {
"address" : "mill"
}
},
"highlight": {
"pre_tags" : ["<tag1>"],
"post_tags" : ["</tag1>"],
"fields" : {
"address" : {}
}
}
}
with above query i get exact result what i needed, this is the result i got
highlight": {
"address": [
"990 <tag1>Mill</tag1> Road"
]
}
i tried the same query using php i am not get the highlighted results my php query is
<?php
require 'vendor/autoload.php';
$client=new Elasticsearch\Client();
$indexParams = [
'index' => 'bank',
'type' => 'account',
'body' => [
'query' => [
'match' => [
"address" => "mill"
],
],
'highlight' => [
"pre_tags" => "<tag1>",
"post_tags" => "</tag1>",
'fields' => [
'address' => new \stdClass()
]
],
]
];
$results = $client->search($indexParams);
try {
$response = $client->search($indexParams);
} catch (Exception $e) {
var_dump($e->getMessage());
}
echo '<pre>',print_r($response),'</pre>';
?>
the result i aam getting is
[highlight] => Array
(
[address] => Array
(
[0] => 715 Mill Avenue
)
)
i got the answer for above question, i am sending parameters in the form of json and JSON encode the result, when i encode the result in JSON at that pre tags are came in highlight query.
my solution is
"highlight": {
"address": [
"817 Campus </span>Road</span>"
]
}
i am trying to create an inline bot for telegram with php. I have followed the steps with the BotFather. I have created the bot, taken the token, setinline and set the placeholder message. I have set the webhook and it's working. But when i type the bot in the message i do get nothing and if I send the message, just nothing happen. The webhook is working, I have tried it with normal messages.
This is my code, after a while I just give up and get it from a blog, edited it a bit.
$content = file_get_contents("php://input");
$update = json_decode($content, true);
$chatID = $update["message"]["chat"]["id"];
//sendMessage(print_r($update,true), $chatID);
if (isset($update["inline_query"])) {
$inlineQuery = $update["inline_query"];
$queryId = $inlineQuery["id"];
$queryText = $inlineQuery["query"];
if (isset($queryText) && $queryText !== "") {
apiRequestJson("answerInlineQuery", [
"inline_query_id" => $queryId,
"results" => ($queryText),
"cache_time" => 86400,
]);
}
else {
apiRequestJson("answerInlineQuery", [
"inline_query_id" => $queryId,
"results" => [
[
"type" => "article",
"id" => "0",
"title" => "TEST",
"message_text" => "TEST",
],
]
]);
}
}
The bot still show me nothing.
I think i just skipped a step.
The results need to have the key message_text inside the input_message_content.Therefore a result could look like this:
$results = array(
array(
"type" => "article",
"id" => "1",
"title" => "Title",
"description" => "Description",
"input_message_content" => array(
"message_text" => "<code>Message 1</code>",
"parse_mode" => "HTML"
)
)
);
$postData = array(
"inline_query_id" => $inlineQuery["id"],
"results" => json_encode($results),
"cache_time" => 0
);
I have integrated the Wepay payment gateway. But I have facing a problem to pass json object to wepay. It always shows a incorrect json format. Please look at the below code.
$forca_a = array(
'debit_opt_in'=>true
);
$forca = json_encode($forca_a,JSON_FORCE_OBJECT);
$wepay_create_array = array(
'name' =>"xxxx",
'description' => "xxxxxxxxx xxxx",
'callback_uri' => "xxxxxxx",
'country' => "CA",
'currencies' => array('CAD'),
'country_options' => $forca,
'rbits'=> array(
array(
'receive_time'=>strtotime("now"),
'type' =>'website_uri',
'source' => 'partner_database',
'properties'=> array('uri'=>xxxxx)
)
)
);
If I won't pass the country_options, its seems to working but If I pass this parameter, it always give me an error says "Incorrect JSON format".
I sent an email to wepay help center. They told me that, you are passing the string "country_options":"{"debit_opt_in":true}" <--- this is a string Instead of "country_options":{"debit_opt_in":true} <--- this is a JSON object. So I'm confused. I have no idea how do I pass the JSON object. There is only way and is json_encode($object).
hey use below code to get proper json
<?php
$forca_a = array(
'debit_opt_in'=>true
);
// $forca = json_encode($forca_a);
$wepay_create_array = array(
'name' =>"xxxx",
'description' => "xxxxxxxxx xxxx",
'callback_uri' => "xxxxxxx",
'country' => "CA",
'currencies' => array('CAD'),
'country_options' => $forca_a,
'rbits'=> array(
array(
'receive_time'=>strtotime("now"),
'type' =>'website_uri',
'source' => 'partner_database',
'properties'=> array('uri'=>'xxxxx')
)
)
);
print_r(json_encode($wepay_create_array));
?>
this code will give following json output
{
"name": "xxxx",
"description": "xxxxxxxxx xxxx",
"callback_uri": "xxxxxxx",
"country": "CA",
"currencies": ["CAD"],
"country_options": {
"debit_opt_in": true
},
"rbits": [{
"receive_time": 1461561030,
"type": "website_uri",
"source": "partner_database",
"properties": {
"uri": "xxxxx"
}
}]
}
You have no need to make:
$forca = json_encode($forca_a,JSON_FORCE_OBJECT);
before you put it to $wepay_create_array.
Before sending request, i think, you make json_encode($wepay_create_array), and yes, after that you will have 'string' for country_options key.