Laravel Shopify API returns Required parameter missing or invalid on POST Request - laravel

I am using Osiset's github for laravel + shopify: https://github.com/osiset/laravel-shopify
But I don't seem the get the POST request going, tried all kinds of variantions already hope one of you'll see my mistake!
Code:
$order_array = [
'order' => [
'email' => "foo#example.com",
'line_items' => [
'variant_id' => 6103067132088,
'quantity' => 1
]
]
];
$order_array = json_encode($order_array);
$shop = User::first();
$request = $shop->api()->rest('POST', '/admin/orders.json', ['body' => $order_array]);
dd($request['body']);
if I do a dd() on order_array after the encode it shows:
{"order":{"email":"foo#example.com","line_items":{"variant_id":6103067132088,"quantity":1}}}
And then it returns
array:1 [
"order" => "Required parameter missing or invalid"
]
I've also tried to make 'body' to 'query'...

I finally found the solution!
// Replace rest
$request = $shop->api()->rest('POST', '/admin/orders.json', ['body' => $order_array]);
// With request
$request = $shop->api()->request('POST', '/admin/orders.json', $order_array);

Related

How to run GRAPHQL query using laravel lumen suing concurrent request

i'm running graphql query through array in Laravel postAsyn. any solution for that. below i added graphql query.
$client = new Client([
// Base URI is used with relative requests
'base_uri' => $url,
// You can set any number of default request options.
'timeout' => 300.0,
]);
foreach($arr as $value){
$graphQLquery = '{'.
'"query": "query viewer {'.
'repositories(last: '. $value . ') {'.
'nodes {'.
'name'.
'id'.
'isPrivate'.
'nameWithOwner'.
'}'.
'}'.
'}",'.
'"variables": { "name": "'.$name.'", "id": "1", "isPrivate ": "True", "nameWithOwner": "VimDiesel"}'.
'}';'
}
$params = [
'query' => [
'access_token' => $token,
'query' => $query[0]
]
];
$promises = [
'image' => $client->postAsync('POST', 'graphql', json_encode($params))
];
$responses = Promise\Utils::unwrap($promises);
if anyone have solution for that please add. i need run this all queries concurrent processing. i'm using guzzelhttp.

Guzzle Post Null/Empty Values in Laravel

I've been trying to work with Guzzle and learn my way around it, but I'm a bit confused about using a request in conjunction with empty or null values.
For example:
$response = $client->request('POST',
'https://www.testsite.com/coep/public/api/donations', [
'form_params' => [
'client' => [
'web_id' => NULL,
'name' => 'Test Name',
'address1' => '123 E 45th Avenue',
'address2' => 'Ste. 1',
'city' => 'Nowhere',
'state' => 'CO',
'zip' => '80002'
],
'contact' => [],
'donation' => [
'status_id' => 1,
'amount' => $donation->amount,
'balance' => $donation->balance,
'date' => $donation->date,
'group_id' => $group->id,
],
]
]);
After running a test, I found out that 'web_id' completely disappears from my request if set to NULL. My question is how do I ensure that it is kept around on the request to work with my conditionals?
At this point, if I dd the $request->client, all I get back is everything but the web_id. Thanks!
I ran into this issue yesterday and your question is very well ranked on Google. Shame that it has no answer.
The problem here is that form_params uses http_build_query() under the hood and as stated in this user contributed note, null params are not present in the function's output.
I suggest that you pass this information via a JSON body (by using json as key instead of form_params) or via multipart (by using multipart instead of form_params).
Note: those 2 keys are available as constants, respectively GuzzleHttp\RequestOptions::JSON and GuzzleHttp\RequestOptions::MULTIPART
Try to define anything like form_params, headers or base_uri before creating a client, so:
// set options, data, params BEFORE...
$settings = [
'base_uri' => 'api.test',
'headers' => [
'Accept' => 'application/json',
'Authorization' => 'ajustneedatokenheredontworry'
],
'form_params' => [
'cash' => $request->cash,
'reason' => 'I have a good soul'
]
];
// ...THEN create your client,
$client = new GuzzleClient($settings);
// ...and finally check your response.
$response = $client->request('POST', 'donations');
If you check $request->all() at the controller function that you are calling, you should see that were sent successfully.
For those using laravel, use this:
Http::asJson()

How to set file post properly PhpUnit

I'm trying to set a test to upload a file.
In the controller I need to check if everyting is ok (form validation).
The problem is the response gives me an error $request->dataFile->getClientOriginalExtension() , (vendor/symfony/http-foundation/File/UploadedFile.php)
Looks like the dataFile, or request or.... I dont know how to set it.
/**
#test
#group formPostFile
*/
public function formPostFile()
{
$test_file_path = base_path().'/httpdocs/test/Excel.xlsx';
$this->assertTrue(file_exists($test_file_path), $test_file_path.' Test file does not exist');
$_FILE = [
'filename' => [
'name' => $test_file_path,
'type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'size' => 10336,
'tmp_name' => $test_file_path,
'error' => 0
]
];
$data = [
'id' => '2',
'dataFile' => $_FILE
];
$response = $this->post('/excel', $data);
dd($response->getContent());
}
Utilise the Symfony/Illuminate class UploadedFile
$file = new UploadedFile(
$test_file_path,
$test_file_path,
filesize($test_file_path),
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
null,
true
);
LastParameter is testMode and should be true, i believe this will work out in your code, utilise it in a similar fashion as the array you already have like so.
$data = [
'id' => '2',
'dataFile' => $file
];

Can’t submit data to API Platform

I have a controller through which I send data to my local environment of the api platform (which is running fine)
/**
* Creates a new Location entity.
*
*/
public function createAction(Request $request)
{
$this->get("suvya_breadcrumbs.factory")->update('New Hub');
$form = $this->createForm(HubType::class);
$form->handleRequest($request);
$new_url = $this->generateUrl('new_hub');
$redirect_url = $this->generateUrl('home');
if ($form->isSubmitted() && $form->isValid()) {
$client = new Client([
'base_uri' => 'http://127.0.0.1:8000',
]);
$response = $client->request('POST', '/hubs', [
'form_params'=> $form->getData(),
'headers' => [
'Accept' => 'application/ld+json',
'Content-Type'=> 'application/json',
'Authorization'=> 'eyJhbGciOiJSUzI1NiJ9.eyJyb2xlcyI6WyJST0xFX1VTRVIiXSwidXNlcm5hbWUiOiJhZG1pbiIsImlhdCI6MTUxNzg3NjE1NCwiZXhwIjoxNTE3ODc5NzU0fQ.gIG9lueJJZxzkOl8qblhHWwiJvW97m4gz1-1mYeM9SgMzMW35Wh6XamOOYiISDN99yJ6Ovo-wKk6whpE5UGMDVw_wGek003Dd6r-Y7Ql3kVLHksn2JFzhAN3GwlXFcOI4MIjmq5qBhkzv21pHymO0yn1SlzWBwb0O7WygywefMu5p09zGuvAiP9I2ShyQLZhjj8bB_odf3dI-Ql0ZbRmn_JDkDoPcm5U11i-3S1oMikBmFq0WtTcWo7vezt3QdA3bY4_bgaISINAiYRR-_cvjpBSqFSE6n1ZYtHvKFn-98wXXsBGxEAoZw6iQL4iRgOI8F_uaiCo0eRHC7q0_xQ_V_W0-5XDIQXWDwoiVaUXnjO6xo2Fldp7PLO1ueJz1e4wiOy2-TunZdc8UCtw2BdFIQtWatPLi_v_rsNvF2H-6hwa9UOKEi9Z4tH4KkuATbXAxxfkCbSOyY1SAWP0riooPQi_AI2J7L2Ly86eAuKo1Hix3EuEogo19GSyBz_cCWczyERQWM9gikuUs8E22SIAdxTl8ZLFaXgiZIibDvb8pqcN8izFjywWbF2CkyWC58WxrVd6Bfmfnm7k9T6oZqwIZ-TQR-SbRnUHN1hpWUjFCk-tHhgvh7osHXmxe3grzA8M3LPBpQGQiTeqBZFMjF4Tx8zW2tuiEn6TwhV14Lj24Vc'
]
]);
die();
}
return $this->render('SuvyaFabricsCloudBundle:Common:basic.html.twig', array(
'form' => $form->createView(),
'page_title'=> 'Hub aanmaken',
'action_path' => $new_url,
'cancel_path'=> $redirect_url,
'submit_button_title' => 'Opslaan',
));
}
But unfortunately i'm getting an error in my dev.log of the api environment:
[2018-02-06 02:32:37] request.INFO: Matched route "api_hubs_post_collection". {"route":"api_hubs_post_collection","route_parameters":{"_controller":"api_platform.action.post_collection","_format":null,"_api_resource_class":"AppBundle\\Entity\\Hub","_api_collection_operation_name":"post","_route":"api_hubs_post_collection"},"request_uri":"http://127.0.0.1:8000/hubs","method":"POST"} []
[2018-02-06 02:32:37] request.CRITICAL: Uncaught PHP Exception Symfony\Component\Serializer\Exception\UnexpectedValueException: "Syntax error" at /Users/myname/Sites/suvyalogistics-api/vendor/symfony/symfony/src/Symfony/Component/Serializer/Encoder/JsonDecode.php line 78 {"exception":"[object] (Symfony\\Component\\Serializer\\Exception\\UnexpectedValueException(code: 0): Syntax error at /Users/myname/Sites/suvyalogistics-api/vendor/symfony/symfony/src/Symfony/Component/Serializer/Encoder/JsonDecode.php:78)"} []
The output of form->getData():
array (size=4)
'postalCode' => string 'sdfdsf' (length=6)
'streetName' => string 'sdfsdf' (length=6)
'doorNumber' => string 'sdfsfd' (length=6)
'city' => string 'sdfsfd' (length=6)
Running the endpoint at the api platform with the same values goes fine as well.
Does anyone of you has an idea why this goes wrong?
You're sending a payload encoded in application/x-www-form-urlencoded (HTML form like) to the API Platform API, while, according to the headers you've set, it excepts data encoded in JSON.
To encode the data of the form in JSON, you can use the following Guzzle snippet:
$client = new Client([
'base_uri' => 'http://127.0.0.1:8000',
]);
$response = $client->request('POST', '/hubs', [
'json' => $form->getData(),
'headers' => [
'Accept' => 'application/ld+json',
'Authorization'=> '...'
]
]);
Alternatively, you can configure API Platform to accept form data, but I would not recommend going this way (it's better to only deal with JSON API-side).

Guzzle 6 Async request return Argument 1 passed must be of the type array, string given,

I'm trying to make an asynchronous POST call, but guzzle call returns the following error:
" ErrorException in Request.php line 220:
Argument 1 passed to Symfony\Component\HttpFoundation\Request::__construct() must be of the type array, string given, called in C:\Program Files ...\app\Http\Controllers\ConfirmAccountController.php on line 87 and defined "
In ConfirmAccountController:
$client = new Client(['base_uri' => 'correct_api_address']);
$request = new Request('POST', 'testpromoboiler/updateUser', [
'query' => ['token' => $user->sdg_token ,
'address' => $user->address ,
]
]);
$promise = $client->sendAsync($request)->then(function ($response) {
echo 'I completed! ' . $response->getBody();
});
$promise->wait();
Why I get this error?
I have done two other synchronous calls and everything went well.
Thanks
That code instantiates Laravel frameworks Request class.
Use guzzles request method instead:
$request = $client->request('POST', 'testpromoboiler/updateUser', [
'query' => ['token' => $user->sdg_token ,
'address' => $user->address ,
]
]);

Resources