I have a shopping cart and once the action placeorder.php is hit, i have set-up a webhook to post to discord.
The cart uses session arrays to store the cart information.
the session array is set as below on the product.php page when the "add to card" button is pressed
$_SESSION['cart'] = array($product_id => $quantity);
The product IDs are pulled from a mysql DB.
With 2x items added to the cart, the array is as follows:
["cart"]=>
array(2) {
[1]=> int(5)
[4]=> int(3)
}
If I echo the array it comes out as
foreach ($products as $product){
echo $product[name];
echo $products_in_cart[$product['id']];
}
Output: camera5laptop3
$products_in_cart[$product['id'] is simply grabbing the quantity ordered.
The JSON Structure
I am trying to make it so that every product name in the cart appears on a new line (\n) under the "Ordered Products" field. and the same for the quanity.
This would be through a foreach but since the json structure is within json_encode() I am struggling.
The below set-up currently only shows the last $product['name'] and $products_in_cart[$product['id'] in the array
$msg = json_encode([
// Message
"content" => "",
// Username
//"username" => "",
// Avatar URL.
// Uncomment to use custom avatar instead of bot's pic
//"avatar_url" => "",
// text-to-speech
"tts" => false,
// file_upload
// "file" => "",
// Embeds Array
"embeds" => [
[
// Title
"title" => "New Order",
// Embed Type, do not change.
"type" => "rich",
// Description
"description" => "New order, go sort it",
// Link in title
//"url" => "",
// Timestamp, only ISO8601
"timestamp" => $timestamp,
// Left border color, in HEX
"color" => hexdec( "3366ff" ),
// Footer text
"footer" => [
"text" => "Sent from thestash.store",
"icon_url" => ""
],
// Embed image
"image" => [
"url" => ""
],
// thumbnail
//"thumbnail" => [
// "url" => ""
//],
// Author name & url
"author" => [
"name" => "TEST3",
"url" => ""
],
// Custom fields
"fields" => [
// Field 1
[
"name" => "Ordered Products",
"value" => $product['name'],
"inline" => true
],
// Field 2
// Field 1
[
"name" => "Quantity",
"value" => $products_in_cart[$product['id']],
"inline" => true
],
[
"name" => "Order Total $",
"value" => $subtotal,
],
[
"name" => "Customer Alias",
"value" => $_SESSION['alias'],
"inline" => true
],
[
"name" => "Customer Number",
"value" => $_SESSION['number'],
"inline" => true
],
[
"name" => "Affiliation",
"value" => $_SESSION['affiliation'],
"inline" => true
],
// etc
]
]
]
], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE );
Current Output on discord:
Attempting to output as (manuall set in JSON)
print_r($msg);
{
"content": "",
"tts": false,
"embeds": [
{
"title": "New Order",
"type": "rich",
"description": "New order, go sort it",
"timestamp": "2023-01-13T11:57:22+00:00",
"color": 3368703,
"footer": {
"text": "Sent from thestash.store",
"icon_url": ""
},
"image": {
"url": ""
},
"author": {
"name": "TEST3",
"url": "https://thestash.store"
},
"fields": [
{
"name": "Ordered Products",
"value": "laptop",
"inline": true
},
{
"name": "Quantity",
"value": 3,
"inline": true
},
{
"name": "Order Total $",
"value": 96000
},
{
"name": "Customer Alias",
"value": "quigg",
"inline": true
},
{
"name": "Customer Number",
"value": "1239871237378127",
"inline": true
},
{
"name": "Affiliation",
"value": "yes",
"inline": true
}
]
}
]
}
Attempting to have the JSON format as follows. Where each $product[name] and $products_in_cart[$product['id']] is on a new line. Currently the last $product[name] and $products_in_cart[$product['id']] show
{
"content": "",
"tts": false,
"embeds": [
{
"title": "New Order",
"type": "rich",
"description": "New order, go sort it",
"timestamp": "2023-01-13T11:57:22+00:00",
"color": 3368703,
"footer": {
"text": "Sent from thestash.store",
"icon_url": ""
},
"image": {
"url": ""
},
"author": {
"name": "TEST3",
"url": "https://thestash.store"
},
"fields": [
{
"name": "Ordered Products",
"value": "camera\nlaptop",
"inline": true
},
{
"name": "Quantity",
"value": "5\n3",
"inline": true
},
{
"name": "Order Total $",
"value": 96000
},
{
"name": "Customer Alias",
"value": "quigg",
"inline": true
},
{
"name": "Customer Number",
"value": "1239871237378127",
"inline": true
},
{
"name": "Affiliation",
"value": "yes",
"inline": true
}
]
}
]
}
So it's just a case of adding extra things into two strings, separated by newlines. So just loop over the products array to create two strings, one for the name and one for the quantity, and put those into variables. Then, you can just use those variables in the right places in your Fields array.
Heres the general idea:
$names = "";
$quantities = "";
foreach ($products as $product){
$names .= ($names != "" ? "\n" : "").$product["name"];
$quantities .= ($quantities != "" ? "\n" : "").$products_in_cart[$product['id']];
}
Then in the bit where you build the array:
...
"fields" => [
[
"name" => "Ordered Products",
"value" => $names,
"inline" => true
],
[
"name" => "Quantity",
"value" => $quantities,
"inline" => true
],
...
Related
I have fetch value from database and returning its array in json format. This is my code to get values. First array is working fine. But i need to add static array after every index in array. This is my code
$value = $this->TestModel->get_user_details($userIds);
this function returns array in json format e.g.
[
{
"user_id": "1",
"name": "test 1",
},
{
"user_id": "2",
"name": "test 2",
},
{
"user_id": "3",
"name": "test 3",
},
]
now i need to add below static json array with every item of array. This is e.g
$test1= array("student_list"=> array(array("stu_id"=>1, "name"=> "abc") , array("stu_id"=>2, "name"=> "xyz")),
"class"=> "12th",
"average_score"=>"5",
"results"=>array(array("result_date"=>"2012-12-13","city"=>"city 1"),array("result_date"=>"2015-10-13","city"=>"city 2")));
I have tried it with array_push and array_merge but it add this at the end end of array.
I need this Response
[
{
"user_id": "1",
"name": "test 1",
"student_list": [
{
"stu_id": 1,
"name": "abc",
},
{
"stu_id": 2,
"name": "xyz",
}
],
"class": "12th",
"average_score": "5",
"results": [
{
"result_date": "2012-12-13",
"city": "City 1",
},
{
"result_date": "2012-10-13",
"city": "City 2",
}
]
},
{
"user_id": "2",
"name": "test 2",
"student_list": [
{
"stu_id": 3,
"name": "asd",
},
{
"stu_id": 4,
"name": "ghj",
}
],
"class": "10th",
"average_score": "5",
"results": [
{
"result_date": "2011-12-13",
"city": "City 3",
},
{
"result_date": "2011-10-13",
"city": "City 4",
}
]
},
]
If you want to add $test1 to to every element you your array you should merge each element, like so:
$value = $this->TestModel->get_user_details($userIds);
$test1 = array(
"student_list" => array(array("stu_id" => 1, "name" => "abc"), array("stu_id" => 2, "name" => "xyz")),
"class" => "12th",
"average_score" => "5",
"results" => array(array("result_date" => "2012-12-13", "city" => "city 1"), array("result_date" => "2015-10-13", "city" => "city 2"))
);
$decoded = json_decode($value, true);
for ($i = 0; $i < count($decoded); $i++) {
$decoded[$i] = array_merge($decoded[$i], $test1);
}
$value = json_encode($decoded);
I have this code as I am trying to implement a json code using foreach loop
foreach ($single_google as $row) {
$data['step'][] = array(
"#type" => "HowToStep",
"url" => "https://example.com/kitchen#step1",
"name" => "Prepare the surfaces",
"itemListElement" => array(),
"image" => [
"#type" => "ImageObject",
"url" => "https://example.com/photos/1x1/photo-step1.jpg",
"height" => "406",
"width" => "305"
],
);
$all_step_google = json_decode($row["steps"]);
foreach ($all_step_google as $single_step_google) {
$data['itemListElement'][] = array(
"#type" => "HowToDirection",
"text" => "testing",
);
}
}
print_r(json_encode($data));
at the end of the coding, trying to run it I got this
{
"#type": "HowToStep",
"url": "https://example.com/kitchen#step1",
"name": "Prepare the surfaces",
"itemListElement": [],
"image": {
"#type": "ImageObject",
"url": "https://example.com/photos/1x1/photo-step1.jpg",
"height": "406",
"width": "305"
}
}
],
"itemListElement": [
{
"#type": "HowToDirection",
"text": "test."
}
instead of this which I needed actually.
{
"#type": "HowToStep",
"url": "https://example.com/kitchen#step1",
"name": "Prepare the surfaces",
"itemListElement": [
{
"#type": "HowToDirection",
"text": "Test"
}
],
"image": {
"#type": "ImageObject",
"url": "https://example.com/photos/1x1/photo-step1.jpg",
"height": "406",
"width": "305"
}
}
],
I want the "itemListElement" => array(), to print before the "image" => [] but it kept printing after the foreach loop. Please help me, am getting lost.
You use $data['itemListElement'][] = array(... on your second loop so that will assign new key to your data master array instead, the right code should be like this
............
foreach ($all_step_google as $key => $single_step_google) {
$data['step'][$key]['itemListElement'][] = array(
"#type" => "HowToDirection",
"text" => "testing",
);
}
............
I am trying to add a customer(Podio item) to my Podio app. This customer is being added programmatically from within a php application. There are several fields present on the customer: Name, Address, Email, Title, Phone Number, and an array of Tags. When a tag is added the color changes to highlight it.
In previous iterations I have been successful adding a different tag(newsletter_subscribed) using the ID of the tag value that I want highlighted. Now when I try to add another tag(hospital, clinic, or urgent_care) it is throwing a PodioBadRequestError. The error cited is that the ID being used is and invalid type(integer).
I got the values of the tag ID's by looking at the JSON returned when an existing customer created manually within my Podio customer application. When I look at the ID fields in the JSON they are most definitely integers, I have tried strings as well. Everything I try throws the 400 Bad Request on the ID that I am trying to add.
I cannot for the life of me figure out why it is throwing the error when I add the tag ID's.
Below is the way that the application is put together:
This is the code that builds and sends the request:
public function addToPodio()
{
$address = $this->Address . ", " .
$this->Address2 . ", " .
$this->City . ", " .
$this->State . " " .
$this->Zip;
$item = [
'fields' => [
'name' => $this->PrimaryContactFirstName,
'last-name' => $this->PrimaryContactLastName,
'email-address' => ['type' => 'work', 'value' => $this->PrimaryContactEmail],
'phone-number' => ['type' => 'work', 'value' => $this->PrimaryContactPhone],
'address' => $address,
'organization' => [$this->CompanyName],
'tags-2' => []
],
];
if ($this->Newsletter && defined('PODIO_NEWSLETTER_TAG_ID')){
$item['fields']['tags-2'][] = PODIO_NEWSLETTER_TAG_ID;
}
if($this->OrganizationType && defined('PODIO_ORGANIZATION_TYPE_ID')){
if($this->OrganizationType == "Clinic"){
$item['fields']['tags-2'][] = PODIO_ORGANIZATION_TYPE_CLINIC_TAG_ID;
}
else if($this->OrganizationType == "Hospital"){
$item['fields']['tags-2'][] = PODIO_ORGANIZATION_TYPE_HOSPITAL_TAG_ID;
}
try {
//This is where the request is being made
$customer = PodioItem::create(PODIO_CUSTOMER_APP_ID, $item);
$this->PodioId = $customer->item_id;
$this->write();
} catch (Exception $e) {
error_log('We encountered an error adding your item to Podio' . $e);
return 'An error occurred while updating Podio. Please try again. If the error...';
}
This is the PHP $item that is being passed to the request that gets sent to the Podio API:
Array
(
[fields] => Array
(
[name] => Joe
[last-name] => Test
[phone-number] => Array
(
[type] => work
[value] => 8675309
)
[address] => 123 Main Road, , East Test, NY 12345
[organization] => Array
(
[0] => Another Test
)
[tags-2] => Array
(
[0] => 16
[1] => 96
)
)
)
This is the config file with the all of the constants, secrets tokens and ID's needed to connect to the Podio API, authenticate and all of that stuff. Obfuscated Example below:
define('PODIO_CUSTOMER_APP_ID', 'xxxxx-obfuscated-xxxxx');
define('PODIO_CUSTOMER_APP_TOKEN', 'xxxxx-obfuscated-xxxxx');
define('PODIO_CLIENT_SECRET', 'xxxxx-obfuscated-xxxxx');
define('PODIO_CLIENT_ID', 'xxxxx-obfuscated-xxxxx');
define('PODIO_ORGANIZATION_TYPE_ID', 'xxxxx-obfuscated-xxxx');
define('PODIO_NEWSLETTER_TAG_ID', 'xxxxx-obfuscated-xxxxx');
define('PODIO_ORGANIZATION_TYPE_CLINIC_TAG_ID', 'xxxxx-obfuscated-xxxxx');
Podio::setup(PODIO_CLIENT_ID, PODIO_CLIENT_SECRET, [
'session_manager' => Injector::inst()->get(PodioSession::class),
'curl_options' => array(),
]);
Below is the JSON that I used to get the values of the ID's. I got this from a postman request to the API. The basic form of the request without all of the authentication present looked like:
podio.com/MY_PODIO_ACCOUNT_NAME/app/APPLICATION_ID/item/ITEM_ID
Please note: I removed many of the main fields like Address and Organization for brevity's sake, so it won't match completely the PHP request object above.
{
"id": 0000,
"item_id": 00000,
"revision": 0,
"app": null,
"app_item_id": 00000,
"app_item_id_formatted": "PODIO_Field_ID:00000",
"external_id": null,
"title": "TEST ITEM",
"fields": [
{
"id": 0000,
"field_id": 0000,
"type": "text",
"external_id": "name",
"label": "First Name",
"values": [
{
"value": "Joe"
}
],
"config": {
"settings": {
"format": "plain",
"size": "small"
},
"mapping": "contact_name",
"label": "First Name"
},
"humanized_value": "Joe"
},
{
"id": 0000,
"field_id": 0000,
"type": "text",
"external_id": "last-name",
"label": "Last Name",
"values": [
{
"value": "<p>Test<br /></p>"
}
],
"config": {
"settings": {
"format": "html",
"size": "large"
},
"mapping": null,
"label": "Last Name"
},
"humanized_value": "Test"
},
{
"id": 0000,
"field_id": 0000,
"type": "phone",
"external_id": "phone-number",
"label": "Phone Number",
"values": [
{
"type": "work",
"value": "867-5309"
}
],
"config": {
"settings": {
"call_link_scheme": "callto",
"possible_types": [
"mobile",
"work",
"home",
"main",
"work_fax",
"private_fax",
"other"
]
},
"mapping": "contact_phone",
"label": "Phone Number"
},
"humanized_value": "8675309"
},
{
"id": 11111,
"field_id": 11111,
"type": "category",
"external_id": "tags-2",
"label": "Tags",
"values": [
{
"value": {
"status": "active",
"text": "Clinic",
"id": 16,
"color": "DCEBD8"
}
},
{
"value": {
"status": "active",
"text": "Newlsetter_subscribed",
"id": 96,
"color": "DCEBD8"
}
}
],
"config": {
"settings": {
"multiple": true,
"options": [
{
"status": "active",
"text": "Mktng:test1/2020",
"id": 150,
"color": "DCEBD8"
},
{
"status": "active",
"text": "Mktng:Test2/2020",
"id": 3,
"color": "DCEBD8"
},
{
"status": "active",
"text": "SampleTest",
"id": 48,
"color": "DCEBD8"
},
{
"status": "deleted",
"text": "Test Center",
"id": 139,
"color": "DCEBD8"
},
{
"status": "deleted",
"text": "Sample Center",
"id": 99,
"color": "DCEBD8"
},
{
"status": "deleted",
"text": "Testing Center",
"id": 140,
"color": "DCEBD8"
}
],
"display": "inline"
},
"mapping": null,
"label": "Tags"
},
"humanized_value": "Clinic; Newsletter;"
}
this JSON continues for pages and pages, I only included the relevant fields for my question.
It looks like the error is being thrown because of the organization value, not the tags value.
For a category field, an array of integer indices is correct.
[tags-2] => [ 16, 96 ]
For an app field, you need to provide an array of integer item ID's.
[organization] => [ 12345 ]
But your code above is sending an array of strings:
[organization] => [ "Another Test" ]
That won't work.
I add a new contact API - send POST, according to the example below.
https://intranet_name.bitrix24.com/rest/crm.contact.add?auth=authentication_code&fields[NAME]=Maria&fields[SECOND_NAME]=Anna&fields[LAST_NAME]=Nowacka
It adds correctly, works.
I can not deal with the addition of the PHONE array, how to do it?
<script type="text/javascript">
BX24.callMethod(
"crm.contact.add",
{
fields:
{
"NAME": "John",
"SECOND_NAME": "Lancelot",
"LAST_NAME": "Doe",
"OPENED": "Y",
"ASSIGNED_BY_ID": 1,
"TYPE_ID": "CLIENT",
"SOURCE_ID": "SELF",
"PHOTO": { "fileData": document.getElementById('photo') },
"PHONE": [ { "VALUE": "555888", "VALUE_TYPE": "WORK" } ]
},
params: { "REGISTER_SONET_EVENT": "Y" }
},
function(result)
{
if(result.error())
console.error(result.error());
else
console.info("Created a new contact; ID=" + result.data());
}
);
OAuth 2.0 Protocol API documentation
I changed to uURL, it works.
You had to add a square bracket.
$data = array(
"fields" => array(
"NAME" => "Nowy2",
"LAST_NAME" => "Testowy1",
"ADDRESS" => "NowodÄ…browska 45",
"ADDRESS_POSTAL_CODE" => "54-345",
"ADDRESS_CITY" => "Warszawa",
"ADDRESS_COUNTRY" => "Polska",
"TYPE_ID" => "CLIENT",
"PHONE" => array([
"VALUE" => 994556765,
"VALUE_TYPE" => "WORK"]
)
)
);
I'm trying to set a custom field of type Multiselect via JIRA rest API using php. For reason I'm getting the following error:
{"errorMessages":[],"errors":{"Functionality Impacted":"expected 'value' property to be a string"}}
I have the following code for setting the custom field:
public function requestRemedy($summary, $description, $priority, $goliveDate,$startTime,
$endTime,$clientImpact,$impactedFunctionality,$fundTransfers ,$fieldAffected, $remedyChangeType,
$changeReason,$remedyImpact, $urgency,$riskLevel,$nameRequestor,$emailRequestor)
{
$json = Array ( "fields" => Array (
"project" => Array
( "id" => 10051 ),
"summary" => $summary,
"description" =>$description,
"issuetype" => Array ( "name" => "Remedy Change Management" ),
"priority" => Array("id" => $priority),
"customfield_13774" => $goliveDate,
"customfield_14408" => "$startTime",
"customfield_14409" => "$endTime",
"customfield_14412" => "$clientImpact",
"customfield_14908" =>Array ( 0 => Array(
"value" => ($impactedFunctionality),
)),
"customfield_14414" => Array("id" =>$fundTransfers),
// "customfield_14415" =>Array("id" => $businessOnline,"child" =>Array("id" => $businessDependency) ),
"customfield_14602" => Array("id" =>$fieldAffected),
"customfield_14422" => Array("id" =>$remedyChangeType),
"customfield_14423" => Array("id" =>$changeReason),
"customfield_14424" => Array("id" =>$remedyImpact),
"customfield_14425" => Array("id" =>$urgency),
"customfield_14426" => Array("id" =>$riskLevel),
"customfield_14700"=>$nameRequestor,
"customfield_14702"=>$emailRequestor
)
);
return $json;
}
After adding some dummy data to test the final structure of json, I get the following result:
{
"fields": {
"project": {
"id": 10051
},
"summary": "Test",
"description": "Human DeSC",
"issuetype": {
"name": "Remedy Change Management"
},
"priority": {
"id": "2"
},
"customfield_13774": "2016-11-08",
"customfield_14408": "2016-11-01T07:35:00.000+0200",
"customfield_14409": "2016-11-01T08:35:00.000+0200",
"customfield_14412": "cLIENT iMPACT",
"customfield_14908": [{
"value": ["Savings Accounts", "Current Accounts", "Call Deposits"]
}],
"customfield_14414": {
"id": "13647"
},
"customfield_14602": {
"id": "14022"
},
"customfield_14422": {
"id": "13712"
},
"customfield_14423": {
"id": "13718"
},
"customfield_14424": {
"id": "13722"
},
"customfield_14425": {
"id": "13726"
},
"customfield_14426": {
"id": "13730"
},
"customfield_14700": "Pastor Dan",
"customfield_14702": "email#time.com"
}
}
Which means the issue is here:
"customfield_14908": [{
"value": ["Savings Accounts", "Current Accounts", "Call Deposits"]
}],
the expected structure is:
"customfield_10008": [ {"value": "Savings Accounts" }, {"value": "Current Accounts" }, {"value": "Call Deposits" }]
Now I'm not sure how to build this using an associative array
The custom field I'm trying to set is customfield_14908. What I'm finding weird is that I used similar code for setting a multiselect field on JIRA version 7.2.1 and it works well, but not working on JIRA version 7.0.