How to create array in Guzzle Request? - php

I'm trying to send a post to an API, but the "items should be an array" error is returned.
$response2 = $client2->request('POST', 'https://api.iugu.com/v1/invoices?api_token='.$token, [
'form_params' => [
'email' => $email,
'due_date' => $due_date,
'items' => ['description' =>
'Item Um',
'quantity' => 1,
'price_cents' => 1000
],
'payer' => [
'cpf_cnpj' => $cpf_cnpj,
'name' => $name,
'phone_prefix' => $phone_prefix,
'phone' => $phone,
'email' => $email,
'address' => [
'zip_code' => $zip_code,
'street' => $street,
'number' => $number,
'district' => $district,
'city' => $city,
'state' => $state,
'country' => 'Brasil',
'complement' => $complement
]
]
]
]);
I've tried it in several ways.
['items' => 'description' =>
'Item Um',
'quantity' => 1,
'price_cents' => 1000
],
But none of the ways showed the result I wanted. It's weird, because when I run with PHP and CURL lib this code works like charm.
Any sugestion? Thanks in advance for community!

Each item should be an array with their own description, quantity, and price_cents keys. Wrap each within one more array like so:
'items' => [
[
'description' => 'Item Um',
'quantity' => 1,
'price_cents' => 1000
],
]
You'll get an array of items now:
Array
(
[0] => Array
(
[description] => Item Um
[quantity] => 1
[price_cents] => 1000
)
)

Related

Laravel Lumen Collection - Group By With Sum and preserve the values

I'm working on Lumen and my collection has duplicate values, example:
collect([
[
'name' => 'John Doe',
'department' => 'Sales',
'phone' => '99999-99999',
'value' => 25.0
],
[
'name' => 'Mary Lisa',
'department' => 'Finance',
'phone' => '88888-88888',
'value' => 5.0
],
[
'name' => 'Mary Lisa',
'department' => 'Finance',
'phone' => '88888-88888',
'value' => 58.0
],
[
'name' => 'Lucas Rodrigues',
'department' => 'Marketing',
'phone' => '22222-22222',
'value' => 90.0
]
])
I would like to sum the value property when the name is the same but preserve other values like (department and phone) and remove duplicates entity, example:
collect([
[
'name' => 'John Doe',
'department' => 'Sales',
'phone' => '99999-99999',
'value' => 25.0
],
[
'name' => 'Mary Lisa',
'department' => 'Finance',
'phone' => '88888-88888',
'value' => 63.0
],
[
'name' => 'Lucas Rodrigues',
'department' => 'Marketing',
'phone' => '22222-22222',
'value' => 90.0
]
])
What's the best way to do this?
Try the following:
$newCollection = collect([]);
$collectctions = collect([
[
'name' => 'John Doe',
'department' => 'Sales',
'phone' => '99999-99999',
'value' => 25.0
],
[
'name' => 'Mary Lisa',
'department' => 'Finance',
'phone' => '88888-88888',
'value' => 5.0
],
[
'name' => 'Mary Lisa',
'department' => 'Finance',
'phone' => '88888-88888',
'value' => 58.0
],
[
'name' => 'Lucas Rodrigues',
'department' => 'Marketing',
'phone' => '22222-22222',
'value' => 90.0
]
]);
foreach ($collectctions as $item) {
if($newCollection->contains('name', $item['name'])){
$index = $newCollection->where('name', $item['name'])->keys()[0];
$newCollection = $newCollection->map(function ($object, $i) use ($index, $item) {
if($i == $index){
$object['value'] += $item['value'];
}
return $object;
});
}
else{
$newCollection->push($item);
}
}
return $newCollection;
This can be achieved using collection functions (https://laravel.com/docs/8.x/collections). In this example I solved it using (groupBy, map, flatten, slice, count and sum).
$data = collect([
[
'name' => 'John Doe',
'department' => 'Sales',
'phone' => '99999-99999',
'value' => 25.0
],
[
'name' => 'Mary Lisa',
'department' => 'Finance',
'phone' => '88888-88888',
'value' => 5.0
],
[
'name' => 'Mary Lisa',
'department' => 'Finance',
'phone' => '88888-88888',
'value' => 58.0
],
[
'name' => 'Lucas Rodrigues',
'department' => 'Marketing',
'phone' => '22222-22222',
'value' => 90.0
]
]);
$data = $data->groupBy('name')->map(function ($item) {
if ($item->count() > 1) {
$item = $item->slice(0, 1)->map(function($subItem) use ($item) {
$subItem['value'] = $item->sum('value');
return $subItem;
});
}
return $item;
})
->flatten(1);
When calling print_r($data->toArray()); we get the following array as result:
Array
(
[0] => Array
(
[name] => John Doe
[department] => Sales
[phone] => 99999-99999
[value] => 25
)
[1] => Array
(
[name] => Mary Lisa
[department] => Finance
[phone] => 88888-88888
[value] => 63
)
[2] => Array
(
[name] => Lucas Rodrigues
[department] => Marketing
[phone] => 22222-22222
[value] => 90
)
)

assertJSON test not working even though response JSON matches

My assertJSON test isn't working and says I get the below error
Here's the test code
$user = Sanctum::actingAs(
User::factory()->create(),
['*']
);
$customer = Customer::first();
$response = $this->getJson('api/customers/' . $customer->slug);
$response->assertStatus(200);
$response->assertJson(
[
'data' => [
'uuid' => $customer->uuid,
'customer_name' => $customer->customer_name,
'email' => $customer->email,
'slug' => $customer->slug,
'street_1' => $customer->street_1,
'street_2' => $customer->street_2,
'city' => $customer->city,
'postcode' => $customer->postcode,
'telephone_number' => $customer->telephone_number,
'county' => $customer->county,
'customer_type' => $customer->customerType,
'archived' => $customer->archived ? 'Yes' : 'No',
]
]
);
And here is the customer resource
public function toArray($request)
{
return [
'uuid' => $this->uuid,
'customer_name' => $this->customer_name,
'email' => $this->email,
'slug' => $this->slug,
'street_1' => $this->street_1,
'street_2' => $this->street_2,
'city' => $this->city,
'postcode' => $this->postcode,
'telephone_number' => $this->telephone_number,
'county' => $this->county,
'customer_type' => $this->customerType,
'archived' => $this->archived ? 'Yes' : 'No',
];
}
The 2 JSON arrays are exactly the same and the other tests are working and everything on the front end is working just fine too.
More of the error

How do I insert meta data to my customers in woocommerce using an object array?

Hi I am trying to use the woocommerce API and do post requests of customer data and adding an internal customer ID.
Here is my data
I have tried to pass this data through a post request
$extension = "/wp-json/wc/v3/customers?";
$method = "POST";
$data = [
'email' => 'johndoe#example.com',
'first_name' => 'John',
'last_name' => 'Doe',
'username' => 'johndoe',
'billing' => [
'first_name' => 'John',
'last_name' => 'Doe',
'company' => '',
'address_1' => '969 Market',
'address_2' => '',
'city' => 'San Francisco',
'state' => 'CA',
'postcode' => '94103',
'country' => 'US',
'email' => 'john.doe#example.com',
'phone' => '(555) 555-5555',
],
'shipping' => [
'first_name' => 'John',
'last_name' => 'Doe',
'company' => '',
'address_1' => '969 Market',
'address_2' => '',
'city' => 'San Francisco',
'state' => 'CA',
'postcode' => '94103',
'country' => 'US'
],
'meta_data' => [
'proceed_id' => '2'
]
];
$response = woo_api_request($extension, $method, $data);
Below is the response when I commented out the meta data. But as you can see there is a meta data array.
{"id":7,"date_created":"2021-01-04T21:50:58","date_created_gmt":"2021-01-04T21:50:58","date_modified":"2021-01-04T21:51:02","date_modified_gmt":"2021-01-04T21:51:02","email":"johndoe#example.com","first_name":"John","last_name":"Doe","role":"customer","username":"johndoe","billing":{"first_name":"John","last_name":"Doe","company":"","address_1":"969 Market","address_2":"","city":"San Francisco","postcode":"94103","country":"US","state":"CA","email":"john.doe#example.com","phone":"(555) 555-5555"},"shipping":{"first_name":"John","last_name":"Doe","company":"","address_1":"969 Market","address_2":"","city":"San Francisco","postcode":"94103","country":"US","state":"CA"},"is_paying_customer":false,"avatar_url":"https:\/\/secure.gravatar.com\/avatar\/fd876f8cd6a58277fc664d47ea10ad19?s=96&d=mm&r=g","meta_data":[],"_links":{"self":[{"href":"https:\/\/localhost.com\/wp-json\/wc\/v3\/customers\/7"}],"collection":[{"href":"https:\/\/localhost.com\/wp-json\/wc\/v3\/customers"}]}}
But when I try to pass the proceed_id I get an error.This is the error
{"code":"rest_invalid_param","message":"Invalid parameter(s): meta_data","data":{"status":400,"params":{"meta_data":"meta_data is not of type array."}}}
Do I need to register the meta data? Or am I missing something else?
UPDATE 1:
I've tried to change the way I structure my meta_data to this:
'meta_data' => [
['key' => "proceed_id"],
['value' => "4"]
]
It seems to be not throwing an error with array type now, but I am getting a notice :
Notice: Undefined index: key in
wp-content/plugins/woocommerce/includes/rest-api/Controllers/Version2/class-wc-rest-customers-v2-controller.php
on line 106
According to the WooCommerce REST API documentation you should provide meta_data as an array. Most likely single PHP array gets converted to JSON object instead of an array.
In cases like this, it can help if you try making a request manually, using Postman or some similar tool.
If I understand documentation correctly, this should work:
'meta_data' => [
['proceed_id' => 4],
]
'meta_data' =>
[
[
'key' => "proceed_id",
'value' => "4"
]
]
This method worked. Since the documentation categorizes meta_data as an array instead of an object. You need to pass it as such.
Found the answer here:
https://github.com/claudiosanches/woocommerce-extra-checkout-fields-for-brazil/issues/56
Full parms :
$data = [
'email' => 'johndoe6#example.com',
'first_name' => 'John',
'last_name' => 'Doe',
'username' => 'johndoe6',
'proceed_id' => '2',
'billing' => [
'first_name' => 'John',
'last_name' => 'Doe',
'company' => '',
'address_1' => '969 Market',
'address_2' => '',
'city' => 'San Francisco',
'state' => 'CA',
'postcode' => '94103',
'country' => 'US',
'email' => 'john.doe#example.com',
'phone' => '(555) 555-5555',
],
'shipping' => [
'first_name' => 'John',
'last_name' => 'Doe',
'company' => '',
'address_1' => '969 Market',
'address_2' => '',
'city' => 'San Francisco',
'state' => 'CA',
'postcode' => '94103',
'country' => 'US'
],
'meta_data' => [
['key' => "proceed_id",
'value' => "4"]
]
];

PHP/JSON array problems when connecting to API

The below code is not rendering the line_items as a JSON array and I have searched/asked around to no avail.
Can anyone give me a hand here?
I've also included the json_encode data of the $orderShippingInfo variable.
Below is the JSON output:
{
"token":"API_KEY_HERE",
"email":"a.pinochet#chilehelicoptertours.com",
"line_items":{
"sku":"12345",
"name":"Product Name",
"title":"Product Title",
"price":"$1.99",
"quantity":"1",
"total_tax":"$0.00"
},
"shipping_lines":{
"title":"UPS",
"price":"$0.00",
"method":"UPS 3 DAY",
"carrier":"UPS"
},
"order_id":"0001",
"profile":"default",
"shipping_address":{
"province":"AZ",
"city":"Testville",
"first_name":"Augusto",
"last_name":"Pinochet",
"zip":"12341",
"province_code":"NY",
"country":"US",
"company":"Company Name, Inc.",
"phone":"1112223333",
"country_code":"US",
"address1":"123 Testing Dr Street",
"address2":"Suite #1"
},
"subtotal_price":"$0.00",
"created_at":"2017-02-02",
"country_code":"US",
"total_discounts":"$0.00",
"total_price":"$0.00"
}
TIA!
<?php
$orderShippingInfo = array(
'token' => 'API_KEY_HERE',
'email' => 'a.pinochet#chilehelicoptertours.com',
'line_items' => array(
'sku'=>'12345',
'name'=>'Product Name',
'title'=>'Product Title',
'price'=> '$1.99',
'quantity' => '1',
'total_tax' => '$0.00',
),
'shipping_lines' => array(
'title' => 'UPS',
'price' => '$0.00',
'method' => 'UPS 3 DAY',
'carrier' => 'UPS',
),
'order_id' => '0001',
'profile' => 'default',
'shipping_address' => array(
'province' => 'AZ',
'city' => 'Testville',
'first_name' => 'Augusto',
'last_name' => 'Pinochet',
'zip' => '12341',
'province_code' => 'NY',
'country' => 'US',
'company' => 'Company Name, Inc.',
'phone' => '1112223333',
'country_code' => 'US',
'address1' => '123 Testing Dr Street',
'address2' => 'Suite #1',
),
'subtotal_price' => '$0.00',
'created_at' => date('Y-m-d'),
'country_code' => 'US',
'total_discounts' => '$0.00',
'total_price' => '$0.00',
);
echo json_encode($orderShippingInfo);
?>
You need to make your array of line items an array of them.
For example:
$orderShippingInfo = array(
'token' => 'API_KEY_HERE',
'email' => 'a.pinochet#chilehelicoptertours.com',
'line_items' => array(
array(
'sku'=>'12345',
'name'=>'Product Name',
'title'=>'Product Title',
'price'=> '$1.99',
'quantity' => '1',
'total_tax' => '$0.00',
)
),
'shipping_lines' => array(
'title' => 'UPS',
'price' => '$0.00',
'method' => 'UPS 3 DAY',
'carrier' => 'UPS',
),
'order_id' => '0001',
'profile' => 'default',
'shipping_address' => array(
'province' => 'AZ',
'city' => 'Testville',
'first_name' => 'Augusto',
'last_name' => 'Pinochet',
'zip' => '12341',
'province_code' => 'NY',
'country' => 'US',
'company' => 'Company Name, Inc.',
'phone' => '1112223333',
'country_code' => 'US',
'address1' => '123 Testing Dr Street',
'address2' => 'Suite #1',
),
'subtotal_price' => '$0.00',
'created_at' => date('Y-m-d'),
'country_code' => 'US',
'total_discounts' => '$0.00',
'total_price' => '$0.00',
);
Then you can add a second line item to the array if you require.
The reason for this is that javascript does not have an associative array concept, so to produce one out of a json_encode() would break javascript.
See this example of what json_encode will do
$xx = ['a','b'];
$yy = ['one'=> 1, 'two'=>2];
print_r($xx);
echo json_encode($xx).PHP_EOL;
print_r($yy);
echo json_encode($yy);
Array
(
[0] => a
[1] => b
)
["a","b"] // note this is a JSON array
Array
(
[one] => 1
[two] => 2
)
{"one":1,"two":2} // note this is a JSON object
If the PHP array is numerically indexed, you get a JSON array
If the PHP array is assoc array it will create an JSON Object
If for some reason you specifically want a JSON String representation to be an array you could just add a [] to the $orderShippingInfo[] = array( like this
$orderShippingInfo[] = array(
'token' => 'API_KEY_HERE',
'email' => 'a.pinochet#chilehelicoptertours.com',
'line_items' => array(
'sku'=>'12345',
'name'=>'Product Name',
'title'=>'Product Title',
'price'=> '$1.99',
. . .
. . .

Merge arrays inside array dynamically which have the same keys

I am using PHP 5.6. I have an array like this:
$array = [
0 => [
'johndrake#gmail.com' => [
'email' => 'johndrake#gmail.com',
'firstname' => 'john',
'lastname' => 'drake',
'food' => 'burger',
],
],
1 => [
'johndrake#gmail.com' => [
'email' => 'johndrake#gmail.com',
'firstname' => 'john',
'lastname' => 'drake',
'drink' => 'coke',
],
],
2 => [
'samwin#gmail.com' => [
'email' => 'samwin#gmail.com',
'firstname' => 'sam',
'lastname' => 'win',
'food' => 'pizza',
],
],
3 => [
'samwin#gmail.com' => [
'email' => 'samwin#gmail.com',
'firstname' => 'sam',
'lastname' => 'win',
'drink' => 'pepsi',
],
],
];
Let's say that "food" and "drink" are categories and they can differ depending on how the questionnaire was setup. So there could in fact be "food", "drink", and "dessert" for example. As you can see, there is an array for each person, for each category. What I would like to do is to merge the arrays by each person so that it will instead show up with the following:
$array = [
0 => [
'johndrake#gmail.com' => [
'email' => 'johndrake#gmail.com',
'firstname' => 'john',
'lastname' => 'drake',
'food' => 'burger',
'drink' => 'coke', // Merged
],
],
1 => [
'samwin#gmail.com' => [
'email' => 'samwin#gmail.com',
'firstname' => 'sam',
'lastname' => 'win',
'food' => 'pizza',
'drink' => 'pepsi', // Merged
],
],
];
I have looked at array_merge as well as array_merge_recursive, however from everything that I've read, you have to specify the arrays in order to merge them, for example it has to be array_merge(array[0], array[1]). As you can see, I can't exactly do this because there could be 2,3 or even 4 arrays per person which have to be merged together.
So how do I dynamically merge the arrays for each person so that it shows all their information together?
This is not exactly as the result you asked for and it feels pretty messy, but it might be something you can work further with :)
$result = [];
foreach ($array as $answers) {
foreach ($answers as $email => $values) {
if (!isset($result[$email])) {
$result[$email] = $values;
continue;
}
$result[$email] = array_merge($result[$email], $values);
}
}
And the result:
$result === [
'johndrake#gmail.com' => [
'email' => 'johndrake#gmail.com',
'firstname' => 'john',
'lastname' => 'drake',
'food' => 'burger',
'drink' => 'coke',
],
'samwin#gmail.com' => [
'email' => 'samwin#gmail.com',
'firstname' => 'sam',
'lastname' => 'win',
'food' => 'pizza',
'drink' => 'pepsi',
],
]
<?php
$originalArray=array (
0 => array ('johndrake#gmail.com' => array ('email' => 'johndrake#gmail.com', 'firstname' => 'john', 'lastname' => 'drake', 'food' => 'burger')),
1 => array ('johndrake#gmail.com' => array ('email' => 'johndrake#gmail.com', 'firstname' => 'john', 'lastname' => 'drake', 'drink' => 'coke')),
2 => array ('samwin#gmail.com' => array ('email' => 'samwin#gmail.com', 'firstname' => 'sam', 'lastname' => 'win', 'food' => 'pizza')),
3 => array ('samwin#gmail.com' => array ('email' => 'samwin#gmail.com', 'firstname' => 'sam' ,'lastname' => 'win', 'drink' => 'pepsi'))
);
$tempArray=array();
$newArray=array();
foreach($originalArray as $key=>$val){
$valKey=key($val);
if(isset($tempArray[$valKey])){
$newArray[]=array_merge($tempArray[$valKey],$val[$valKey]);
}
else{
$tempArray[$valKey]=$val[$valKey];
}
}
echo "<pre>";print_r($newArray);

Categories