How to use Google Cloud Healthcare API HttpBody class? - php

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.

Related

What am I doing wrong with this Selling Partner API library from github?

I'm using the Merchant Fulfillment portion of the Amazon Selling Partner API found at https://github.com/jlevers/selling-partner-api/
I have other portions working... namely orders coming down and reports going up. But I am using the same techniques and the Merchant Fulfillment API is not working. The response I get back indicates that it's not received the data I am sending it.
What am I doing wrong?
// North America Live
$NA = [
'url' => 'https://sellingpartnerapi-na.amazon.com',
'region' => 'us-east-1',
];
// North America Sandbox
// $NA = [
// 'url' => 'https://sandbox.sellingpartnerapi-na.amazon.com',
// 'region' => 'us-east-1',
// ];
$config = new SellingPartnerApi\Configuration([
"lwaClientId" => $lwaClientId,
"lwaClientSecret" => $lwaClientSecret,
"lwaRefreshToken" => $lwaRefreshToken,
"awsAccessKeyId" => $awsAccessKeyId,
"awsSecretAccessKey" => $awsSecretAccessKey,
"endpoint" => $NA // or another endpoint from lib/Endpoint.php
]);
$apiInstance = new SellingPartnerApi\Api\MerchantFulfillmentApi($config);
$body = new \SellingPartnerApi\Model\MerchantFulfillment\GetEligibleShipmentServicesRequest(
[
"shipment_request_details" =>
[
"amazon_order_id" => "XXX-XXXXXXXX-XXXXXXXX",
"item_list" =>
[
"order_item_id" => "XXXXXXXXXXXXXXX",
"quantity" => 1,
],
"ship_from_address" =>
[
"name" => "XXXXXXX",
"address_line1" => "XXXXXXXXXX",
"email" => "XXXXX#XXXXX.COM",
"city" => "XXXXXXXXX",
"postal_code" => "XXXXXX",
"country_code" => "US",
"phone" => "XXXXXXXXXXXX",
],
"weight" =>
[
"value" => 7,
"unit" => "oz",
],
"shipping_service_options" =>
[
"delivery_experience" => "DeliveryConfirmationWithSignature",
"carrier_will_pick_up" => true,
]
]
]
);
try {
$result = $apiInstance->getEligibleShipmentServices($body);
d($result);
} catch (Exception $e) {
echo "<PRE>";
echo 'Exception when calling MerchantFulfillmentV0Api->getEligibleShipmentServices: <BR>', wordwrap($e->getMessage(),80,"<br>\n",TRUE), PHP_EOL;
echo "</PRE>";
}
The $response I get back is:
Exception when calling MerchantFulfillmentV0Api->getEligibleShipmentServices:
[400] {
"errors": [
{
"code": "InvalidInput",
"message": "5
validation errors detected: Value \u0027\u0027 at
\u0027shipmentRequestDetails.shipFromAddress.email\u0027 failed to satisfy
constraint: Member must satisfy regular expression pattern: .+#.+; Value
\u0027\u0027 at \u0027shipmentRequestDetails.amazonOrderId\u0027 failed to
satisfy constraint: Member must satisfy regular expression pattern:
[0-9A-Z]{3}-[0-9]{7}-[0-9]{7}; Value \u0027\u0027 at
\u0027shipmentRequestDetails.weight.unit\u0027 failed to satisfy constraint:
Member must satisfy enum value set: [g, ounces, oz, grams]; Value null at
\u0027shipmentRequestDetails.weight.value\u0027 failed to satisfy constraint:
Member must not be null; Value \u0027[]\u0027 at
\u0027shipmentRequestDetails.itemList\u0027 failed to satisfy constraint: Member
must have length greater than or equal to 1",
"details": ""
}
]
}
In the Shipping Service options.... this needs to be set false.
"carrier_will_pick_up" => true,
If its set to true then it will not work. I think it has something to do with sending a request for pickup to the carrier.... and it seems counter-intuitive to set it to false... but thats what made it work!

How we can insert header and footer in google docs with google docs api using PHP code

I want to insert header and footer in my google docs with google docs api in PHP code. I am doing it like this-
$requests = new Google_Service_Docs_Request(array(
'createHeader' => [
'type' => 'TITLE',
'sectionBreakLocation' => [
'index' => 0
],
],
)),
$batchUpdateRequest = new Google_Service_Docs_BatchUpdateDocumentRequest(array(
'requests' => $requests
));
$response = $service->documents->batchUpdate($documentId, $batchUpdateRequest);
but, i am getting this error-
PHP Fatal error: Uncaught Google\Service\Exception: {
"error": {
"code": 400,
"message": "Invalid value at 'requests[5].create_header.type' (type.googleapis.com/google.apps.docs.v1.HeaderFooterType), \"TITLE\"",
"errors": [
{
"message": "Invalid value at 'requests[5].create_header.type' (type.googleapis.com/google.apps.docs.v1.HeaderFooterType), \"TITLE\"",
"reason": "invalid"
}
],
"status": "INVALID_ARGUMENT",
"details": [
{
"#type": "type.googleapis.com/google.rpc.BadRequest",
"fieldViolations": [
{
"field": "requests[5].create_header.type",
"description": "Invalid value at 'requests[5].create_header.type' (type.googleapis.com/google.apps.docs.v1.HeaderFooterType), \"TITLE\""
}
]
}
]
}
}
Please help me out with this, That how we can insert texts in header and footer in google docs using PHP.
In your script, how about the following modification?
Create header:
I thought that the reason of the error message of Invalid value at 'requests[5].create_header.type' (type.googleapis.com/google.apps.docs.v1.HeaderFooterType), \"TITLE\"" is due to 'type' => 'TITLE',. But when I saw your script, $requests is required to be an array. So how about the following modification?
From:
$requests = new Google_Service_Docs_Request(array(
'createHeader' => [
'type' => 'TITLE',
'sectionBreakLocation' => [
'index' => 0
],
],
)),
$batchUpdateRequest = new Google_Service_Docs_BatchUpdateDocumentRequest(array(
'requests' => $requests
));
To:
$requests = new Google_Service_Docs_Request(array(
'createHeader' => [
'type' => 'DEFAULT',
'sectionBreakLocation' => [
'index' => 0
],
],
));
$batchUpdateRequest = new Google_Service_Docs_BatchUpdateDocumentRequest(array(
'requests' => array($requests)
));
Create footer:
In this case, please replace createHeader to createFooter in the above $requests.
Note:
As additional information, when you want to use the first page header and footer, you can use the following request.
$requests = new Google_Service_Docs_Request(array(
'updateDocumentStyle' => [
'documentStyle' => [
'useFirstPageHeaderFooter' => true,
],
'fields' => 'useFirstPageHeaderFooter',
],
));
References:
CreateHeaderRequest
CreateFooterRequest

Issue saving card for customer

I would like to store credit card information for a customer in our QuickBooks account
using the PHP Payments SDK - the following is what I am trying to achieve this but I get an invalid arguments error:
$client = new PaymentClient([
'access_token' => $accessTokenValue,
'environment' => "sandbox" ]);
$array = [
"number" => "4408041234567893",
"expMonth" => "12",
"expYear" => "2026",
"name" => "Test User",
"address" => [
"streetAddress" => "1245 Hana Rd",
"city" => "Richmond",
"region" => "VA",
"country" => "US",
"postalCode" => "44112"
],
"customerid" => "94"
];
$create = CardOperations::createCard($array);
$response = $client->charge($create);
I have not had any luck reaching out to support, any way this can be done, I appreciate the help.
Error received:
Uncaught TypeError: Argument 1 passed to
QuickBooksOnline\Payments\Operations\CardOperations::createCard() must
be an instance of QuickBooksOnline\Payments\Modules\Card, array given
UPDATE using recommended code:
Uncaught ArgumentCountError: Too few arguments to function
QuickBooksOnline\Payments\Operations\CardOperations::createCard(), 1
passed
As per your error it seems the required Card data should be an instance of the class
QuickBooksOnline\Payments\Modules\Card
But you're passing array to it. As per the documentation could you please check this below code , hopefully it will work.
$client = new PaymentClient([
'access_token' => $accessTokenValue,
'environment' => "sandbox"
]);
$cardData = [
"number" => "4408041234567893",
"expMonth" => "12",
"expYear" => "2026",
"name" => "Test User",
"address" => [
"streetAddress" => "1245 Hana Rd",
"city" => "Richmond",
"region" => "VA",
"country" => "US",
"postalCode" => "44112"
],
"customerid" => "94"
];
$chargeData = [
"amount" => "10.55",
"currency" => "USD",
"card" => $cardData,
"context" => [
"mobile" => "false",
"isEcommerce" => "true"
]
];
$customerId = "94";
$charge = ChargeOperations::buildFrom($chargeData);
$chargeResponse = $client->charge($charge);
$clientId = rand();
$card = CardOperations::buildFrom($cardData);
$createCardresponse = $client->createCard($card, $clientId, rand() . "abd");
//or alternatively $createCardresponse = $client->createCard($card, $customerId, rand() . "abd");

How to pass an object as parameter in unit test? (laravel)

I have a data object below that I tried to test using postman. I just don't know how to make this possible also in laravel's unit testing. I have visited this link but it doesn't helped in my case.
{
"user_id": 1,
"name": "juan",
"address": [
"state": "Auckland",
"country": "New Zealand",
],
"school": [
{
"school_name": "Kristin School",
"year": 2016
},
{
"school_name": "ACG Parnell College",
"year": 2018
},
],
// and more...
}
How can we pass such an object above in unit testing? Is there any way to achieve this?
$response = $this->post('/logbooks/user', ['Authorization': 'Bearer' + $token]);
First to know that such tests are not a "unit test" type.
Note that the code will run and you should be alert to changes that running the code may entail (updating data in the database, contacting external providers).
Of course, all of this can be mocked, and it is recommended that you read about it carefully.
class FooTest extends TestCase {
public function testBar()
{
$response = $this->post('/api/v1/yourapi',
[
"user_id" => 1,
"name" => "juan",
"address" => [
"state" => "Auckland",
"country" => "New Zealand"
],
"school" => [
[
"school_name" => "Kristin School",
"year" => 2016
],
[
"school_name" => "ACG Parnell College",
"year" => 2018
]
]
]);
$response->assertStatus(200);
$response->assertJsonStructure([...]);
$response->assert....();
}
}
As I wrote in the comment below, the JSON you attached was invalid.
You treated the array as an object, adding unnecessary commas.
It is recommended to use an array that the IDE knows to recognize
As you can find in the Laravel docs for HTTP tests, you can send a php array as follows:
$payload = [
"user_id" => 1,
"name" => "juan",
"address" => [
"state" => "Auckland",
"country" => "New Zealand",
],
];
$response = $this->postJson(
'/logbooks/user', $payload, ['Authorization': 'Bearer' + $token]
);
It takes your php $payload array and encodes it as JSON and sends it.
If you have an object you can cast it with $myArray = (array) $myObject.

How to create this JSON in PHP?

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

Categories