Related
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
Take for example the following piece of code from WooCommerce API Documentation. What I am trying to do is add some if conditions within the array. For example, I want the payment_details array to be a part of $data based on some if condition. Is this possible? How?
<?php
$data = [
'order' => [
'payment_details' => [
'method_id' => 'bacs',
'method_title' => 'Direct Bank Transfer',
'paid' => true
],
'billing_address' => [
'first_name' => 'John',
'last_name' => 'Doe',
'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_address' => [
'first_name' => 'John',
'last_name' => 'Doe',
'address_1' => '969 Market',
'address_2' => '',
'city' => 'San Francisco',
'state' => 'CA',
'postcode' => '94103',
'country' => 'US'
],
'customer_id' => 2,
'line_items' => [
[
'product_id' => 546,
'quantity' => 2
],
[
'product_id' => 613,
'quantity' => 1,
'variations' => [
'pa_color' => 'Black'
]
]
],
'shipping_lines' => [
[
'method_id' => 'flat_rate',
'method_title' => 'Flat Rate',
'total' => 10
]
]
]
];
print_r($woocommerce->post('orders', $data));
?>
The point is, instead of defining the entire array again, I want to put an if condition here:
'order' => [
if ($payment = 'xyz') {
'payment_details' => [
'method_id' => 'bacs',
'method_title' => 'Direct Bank Transfer',
'paid' => true
],
}
else {
'payment_details' => [
'method_id' => 'monopoly',
'method_title' => 'Monopoly',
'paid' => true
],
}
Is it possible to concatenate the array using dot equals? .=
Thanks.
"payment_details" is already part of $data.
To get to it use:
$paymentDetails = $data['order']['payment_details'];
Then you can display it with:
echo $paymentDetails['method_title'];
If you want to use if conditions:
if ($paymentDetails['method_title'] === 'Monopoly money') {
echo 'That will not work';
}
To change the payment details:
$data['order']['payment_details']['method_title'] = 'Changed';
or
$data['order']['payment_details'] = ['method_title' => 'something', 'method_id' => 5, 'paid' => false];
You can define the payment_details in advance and use it in the $data array.
if ($payment = 'xyz') {
$payment_details = array ( 'method_id' => 'bacs',
'method_title' => 'Direct Bank Transfer',
'paid' => true);
}else{
$payment_details = array ( 'method_id' => 'monopoly',
'method_title' => 'Monopoly',
'paid' => true);
}
$data = array (
'order' => array(
'payment_details' => $payment_details,
......
......
)
);
print_r($woocommerce->post('orders', $data));
Answering my own question. This is what I was looking for.
$orderData = [];
if ($payment == 'Monopoly') {
$orderData['order']['payment_details'] = [];
$orderData['order']['payment_details']['method_id'] = 'Monopoly';
$orderData['order']['payment_details']['method_title'] = 'Monopoly';
$orderData['order']['payment_details']['paid'] = true;
$orderData['order']['status'] = 'completed';
}
else {
$orderData['order']['status'] = 'pending';
}
This is the Json code
{"data":{"user":{"first_name":"xx","last_name":"xx","email":"xx","countryOfResidence":"GB","country":"LK","nationality":"LK"},"billing_address":{"line1":"xx","city":"xx","postal_code":"xx","country":"LK"},"shipping_address":{"first_name":"xx","last_name":"xx","line1":"xx","city":"xx","postal_code":"xx","country":"LK"},"phone":{"type":"Mobile","number":"xx","countryCode":"94"},"marketing_optin":true,"shipping_address_validation":false,"poma_flow":false,"prox_flow":false,"testParams":{},"content_identifier":"LK:en:2.0.287:signupTerms.signupC","card":{"type":"MASTERCARD","number":"xx","security_code":"xx","expiry_month":"xx","expiry_year":"xx"},"skipInitiateAuth":true},"meta":{"token":"xx","calc":"xx","csci":"xx","locale":{"country":"LK","language":"en"},"state":"ui_checkout_guest","app_name":"xoonboardingnodeweb"}}
This is the PHP code I want to write the code in a correct way and make it work.
I want to know where my fault is. Can anyone correct this file from​ me?
Please help with this example clearly.
$link = "https://www.paypal.com/webscr?cmd=_express-checkout&token=EC-7Y207450BE832821N#/checkout/guest";
$post = "";
$s = _curl($link, json_encode($post), $cookie);
$post = json_encode($array);
$array = json_decode($json_string, true);
$link = "https://www.paypal.com/webapps/xoonboarding/api/onboard/guest";
$post = [
'data' => [
'user' => [
'first_name' => 'xx',
'last_name' => 'xx',
'email' => 'xx',
'countryOfResidence' => 'GB',
'country' => 'LK',
'nationality' => 'lk',
],
'billing_address' => [
'line1' => 'xx',
'city' => 'xx',
'postal_code' => 'xx',
'country' => 'lk',
],
'shipping_address' => [
'first_name' => 'xx',
'last_name' => 'xx',
'line1' => 'xx',
'city' => 'xx',
'postal_code' => 'xx',
'country' => 'lk',
],
'phone' => [
'type' => 'Mobile',
'number' => 'xx',
'countryCode' => '94',
],
'marketing_optin' => true,
'shipping_address_validation' => false,
'poma_flow' => false,
'prox_flow' => false,
'testParams' => [],
'content_identifier' => "LK:en:2.0.287:signupTerms.signupC",
'card' => [
'type' => 'xx',
'number' => xx,
'security_code' => xx,
'expiry_month' => xx,
'expiry_year' => xx,
],
'skipInitiateAuth' => true
],
'meta' => [
'token' => xx,
'calc' => xx,
'csci' => xx,
'locale' => [
'country' => 'LK',
'language' => 'en',
],
'state' => 'ui_checkout_guest',
'app_name' => 'xoonboardingnodeweb',
]
];
$s = _curl($link, json_encode($post), $cookie);
You can use a JSON Formatter to easily visualize the structure of your JSON, and transpose it in PHP. Or you can just create a PHP variable thanks to json_decode with you JSON code giving in example.
$link = "https://www.paypal.com/webapps/xoonboarding/api/onboard/guest";
$data = [
'data' => [
'user' => [
'first_name' => 'xx',
'last_name' => 'xx',
'email' => 'xx',
'countryOfResidence' => 'GB',
'country' => 'LK',
'nationality' => 'lk',
],
'billing_address' => [
'line1' => 'xx',
'city' => 'xx',
'postal_code' => 'xx',
'country' => 'lk',
],
'shipping_address' => [
'first_name' => 'xx',
'last_name' => 'xx',
'line1' => 'xx',
'city' => 'xx',
'postal_code' => 'xx',
'country' => 'lk',
],
'phone' => [
'type' => 'Mobile',
'number' => 'xx',
'countryCode' => '94',
],
'marketing_optin' => true,
'shipping_address_validation' => false,
'poma_flow' => false,
'prox_flow' => false,
'testParams' => [],
'content_identifier' => "LK:en:2.0.287:signupTerms.signupC",
'card' => [
'type' => 'xx',
'number' => 'xx',
'security_code' => 'xx',
'expiry_month' => 'xx',
'expiry_year' => 'xx',
],
'skipInitiateAuth' => true
],
'meta' => [
'token' => 'xx',
'calc' => 'xx',
'csci' => 'xx',
'locale' => [
'country' => 'LK',
'language' => 'en',
],
'state' => 'ui_checkout_guest',
'app_name' => 'xoonboardingnodeweb',
]
];
$json = json_encode($data, true);
$ch = curl_init($link);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json', 'Content-Length: ' . strlen($json)]);
$result = curl_exec($ch);
I have seen examples of people sending JSON data in an array. An using cURL to send the data. Problem is most of them are something like
$data = array('first_name' => 'Thomas', 'last_name' => 'Woods')
My question is, if I have something like below that isnt as dry cut. Example:
"products": [
{
"product_id": "B00I9KDFK0",
"quantity": 1,
"seller_selection_criteria": [
{
"condition_in": ["New"],
"international": false,
"handling_days_max": 5
}
]
}
],
So how would I put that info into an Array?
More Info: Ive tried the following with no luck
<?php
// Your ID and token
// The data to send to the API
$postData = array(
'client_token' => 'XXXXXXXXXXXXXXXXXXXXXX',
'retailer' => 'amazon',
'products' => array('product_id' => '0923568964', 'quantity' => '1', 'seller_selection_criteria' => array('condition_in' => 'New', 'international' => 'false', 'handling_days_max' => '5')),
'max_price' => '1300',
'shipping_address' => array('first_name' => 'Thomas', 'last_name' => 'XXXXX', 'address_line1' => 'XXXXXX Loop', 'address_line2' => '', 'zip_code' => 'XXXXX', 'city' => 'XXXX', 'state' => 'MS', 'country' => 'US', 'phone_number' => 'XXXXXX'),
'is_gift' => 'false',
'gift_message' => "",
'shipping_method' => 'cheapest',
'payment_method' => array('name_on_card' => 'XXXXXXXX', 'number' => 'XXXXXXXXXXXX', 'security_code' => 'XXX', 'expiration_month' => 'XX', 'expiration_year' => 'XXXX', 'use_gift' => 'false'),
'billing_address' => array('first_name' => 'Thomas', 'last_name' => 'XXXXXX', 'address_line1' => 'XXXXXXXXX', 'address_line2' => '', 'zip_code' => 'XXXXXX', 'city' => 'XXXXXXXX', 'state' => 'MS', 'country' => 'US', 'phone_number' => 'XXXXXXXX'),
'retailer_credentials' => array('email' => 'XXXXXXXX', 'password' => 'XXXXXXXXX')
);
// Setup cURL
$ch = curl_init('https://api.zinc.io/v0/order');
curl_setopt_array($ch, array(
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_POSTFIELDS => json_encode($postData)
));
// Send the request
$response = curl_exec($ch);
// Check for errors
if($response === FALSE){
die(curl_error($ch));
}
// Decode the response
$responseData = json_decode($response, TRUE);
// Print the date from the response
echo $responseData['published'];
echo $response;
?>
There error im getting is:
{"_type":"error","_request_id":"5663c16b75f682d920000758","code":"invalid_request","message":"Validation failed on the request.","data":{"validator_errors":[{"value":[],"path":"products","message":"'' is not a permitted value for 'products' field."}]},"host":"zincapi-5","offers_urls":[],"screenshot_urls":[],"_created_at":"2015-12-06T05:02:35.567Z"}
Here is the code from the Echo of Json_echo
{"client_token":"xxxxxxxxxxxxxxxxxxxxxxx","retailer":"amazon","products":{"product_id":"0923568964","quantity":1,"seller_selection_criteria":{"condition_in":"New","international":false,"handling_days_max":5}},"max_price":"1300","shipping_address":{"first_name":"Thomas","last_name":"xxxxxx","address_line1":"xxxxx","address_line2":"","zip_code":"xxxx","city":"xxxxx","state":"MS","country":"US","phone_number":"xxxxxx"},"is_gift":"false","gift_message":"","shipping_method":"cheapest","payment_method":{"name_on_card":"xxxxxxxxxx","number":"xxxxxxxxxxxxx","security_code":"xxxx","expiration_month":"xx","expiration_year":"xxxx","use_gift":false},"billing_address":{"first_name":"Thomas","last_name":"xxxxx","address_line1":"xxxxxxx","address_line2":"","zip_code":"xxxx","city":"xxxxxx","state":"MS","country":"US","phone_number":"xxxxxx"},"retailer_credentials":{"email":"xxxxxxxxxx","password":"xxxxxxxxxx"}}
You should be able to use json_encode() which will put it into a properly formatted array.
After reading your response and the error you were getting back from the API you are making the request to, I think the error has to do with the format of your request.
If you look at their API documentation you'll see that it's expecting an array of products. You are only sending one, but it will need to be in an array format.
Here is what it is expecting:
"products": [
{
"product_id": "0923568964",
"quantity": 1,
"seller_selection_criteria": [
{
"condition_in": ["New"],
"international": false,
"handling_days_max": 5
}
]
}
],
So, to change this, you'll need to update the products key of your array to:
'products' => array(array('product_id' => '0923568964', 'quantity' => '1','seller_selection_criteria' => array('condition_in' => 'New', 'international' =>'false', 'handling_days_max' => '5'))),
If you noticed, I put an array declaration around the array of your product details. If you had a second product, you'd put a comma after your first array of product details and add a second.
I have this code: http://pastebin.com/iFwyKM7G
Inside an event-observer class which executes after the customer registered. It creates an order automatically and it works for simple products. However I cannot figure out for the life of me how to make it work with Bundled product!
How can I make this work with a bundled product?
I DID IT!
I changed my code to the following:
$customer = Mage::getSingleton('customer/customer')->load($observer->getCustomer()->getId());
$session = Mage::getSingleton('adminhtml/session_quote');
$order_create_model = Mage::getSingleton('adminhtml/sales_order_create');
Mage::log($customer->debug(), null, 'toszodj_meg.log');
//$transaction = Mage::getModel('core/resource_transaction');
$storeId = $customer->getStoreId();
Mage::log($customer->getDefaultBillingAddress()->debug(), null, 'toszodj_meg.log');
$reservedOrderId = Mage::getSingleton('eav/config')->getEntityType('order')->fetchNewIncrementId($storeId);
$session->setCustomerId((int) $customer->getId());
$session->setStoreId((int) $storeId);
$orderData = array(
'session' => array(
'customer_id' => $customer->getId(),
'store_id' => $storeId,
),
'payment' => array(
'method' => 'banktransfer',
'po_number' => (string) '-',
),
// 123456 denotes the product's ID value
'add_products' =>array(
'2' => array(
'qty' => 1,
'bundle_option' => array(
2 => 2,
1 => 1,
),
'bundle_option_qty' => array(
2 => 1,
1 => 1,
),
),
),
'order' => array(
'currency' => 'EUR',
'account' => array(
'group_id' => $customer->getGroupId(),
'email' => (string) $customer->getEmail(),
),
'comment' => array('customer_note' => 'API ORDER'),
'send_confirmation' => 1,
'shipping_method' => 'flatrate_flatrate',
'billing_address' => array(
'customer_address_id' => $customer->getDefaultBillingAddress()->getEntityId(),
'prefix' => $customer->getDefaultBillingAddress()->getPrefix(),
'firstname' => $customer->getDefaultBillingAddress()->getFirstname(),
'middlename' => $customer->getDefaultBillingAddress()->getMiddlename(),
'lastname' => $customer->getDefaultBillingAddress()->getLastname(),
'suffix' => $customer->getDefaultBillingAddress()->getSuffix(),
'company' => $customer->getDefaultBillingAddress()->getCompany(),
'street' => $customer->getDefaultBillingAddress()->getStreet(),
'city' => $customer->getDefaultBillingAddress()->getCity(),
'country_id' => $customer->getDefaultBillingAddress()->getCountryId(),
'region' => $customer->getDefaultBillingAddress()->getRegion(),
'region_id' => $customer->getDefaultBillingAddress()->getRegionId(),
'postcode' => $customer->getDefaultBillingAddress()->getPostcode(),
'telephone' => $customer->getDefaultBillingAddress()->getTelephone(),
'fax' => $customer->getDefaultBillingAddress()->getFax(),
),
'shipping_address' => array(
'customer_address_id' => $customer->getDefaultShippingAddress()->getEntityId(),
'prefix' => $customer->getDefaultShippingAddress()->getPrefix(),
'firstname' => $customer->getDefaultShippingAddress()->getFirstname(),
'middlename' => $customer->getDefaultShippingAddress()->getMiddlename(),
'lastname' => $customer->getDefaultShippingAddress()->getLastname(),
'suffix' => $customer->getDefaultShippingAddress()->getSuffix(),
'company' => $customer->getDefaultShippingAddress()->getCompany(),
'street' => $customer->getDefaultShippingAddress()->getStreet(),
'city' => $customer->getDefaultShippingAddress()->getCity(),
'country_id' => $customer->getDefaultShippingAddress()->getCountryId(),
'region' => $customer->getDefaultShippingAddress()->getRegion(),
'region_id' => $customer->getDefaultShippingAddress()->getRegionId(),
'postcode' => $customer->getDefaultShippingAddress()->getPostcode(),
'telephone' => $customer->getDefaultShippingAddress()->getTelephone(),
'fax' => $customer->getDefaultShippingAddress()->getFax(),
),
),
);
$order_create_model->importPostData($orderData['order']);
$order_create_model->getBillingAddress();
$order_create_model->setShippingAsBilling(true);
$order_create_model->addProducts($orderData['add_products']);
$order_create_model->collectShippingRates();
$order_create_model->getQuote()->getPayment()->addData($orderData['payment']);
$order_create_model
->initRuleData()
->saveQuote();
$order_create_model->getQuote()->getPayment()->addData($orderData['payment']);
$order_create_model->setPaymentData($orderData['payment']);
$order_create_model
->importPostData($orderData['order'])
->createOrder();
$session->clear();
Mage::unregister('rule_data');
Mage::log('Order Successfull', null, 'siker_bammer.log');
And it works! thought the customer doesn't get notified. which iam trying to figure out now.