I am trying to use the REST lightning API for salesforce. So far I can have it connect succesfully and get info on some things, however I am struggling to get it to actually create new records. Below is the code, I have excluding my connection code and getting my Bearer token, as both those work fine and don't impact the second half of creating a record.
<?php
$url = $instance_url.'/services/data/v20.0/sobjects/Account/';
$headers = array(
'Content-Type: application/json'
);
$data = array(
'Name' => "AccountHEX"
);
$ch2 = curl_init();
curl_setopt($ch2,CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch2,CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch2,CURLOPT_RETURNTRANSFER, true);
$head = 'Authorization: Bearer '.$access_token;
curl_setopt($ch2, CURLOPT_HTTPHEADER, array($head));
//execute post
$result = null;
$result = curl_exec($ch2);
echo $result;
?>
The result I get seems to be just the info on the account object:
{
"objectDescribe":{
"activateable":false,
"createable":true,
"custom":false,
"customSetting":false,
"deletable":true,
"deprecatedAndHidden":false,
"feedEnabled":true,
"keyPrefix":"001",
"label":"Account",
"labelPlural":"Accounts",
"layoutable":true,
"mergeable":true,
"name":"Account",
"queryable":true,
"replicateable":true,
"retrieveable":true,
"searchable":true,
"triggerable":true,
"undeletable":true,
"updateable":true,
"urls":{
"rowTemplate":"/services/data/v20.0/sobjects/Account/{ID}",
"describe":"/services/data/v20.0/sobjects/Account/describe",
"sobject":"/services/data/v20.0/sobjects/Account"
}
},
"recentItems":[
]
}
So it is treating it more as a query rather than a creation. I have tried a couple different $data arrangments. Incluidng just doing name right away, and putting it inside the fields array.
Trying to do this bassed on this:
https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/dome_sobject_create.htm
Any ideas how to get it to create the record?
What you're receiving is the Account sObject describe, which is the return value for a GET request. You need to make a POST request to create the sObject.
Your body data does not need to be nested in a fields key. Your JSON should look like the example from the documentation,
{
"Name" : "Express Logistics and Transport"
}
with all fields at the top level.
Lastly, API v20.0 is extremely old. I would recommend declaring the latest API version in your endpoint URL, v46.0. Using old API versions can result in unexpected behavior and in certain fields being unavailable to you.
Related
I want to build a WhatsApp bot, for that, we are using Gupshup WhatsApp bot API, for integration they asked to give a callback URL, so created index.php in cPanel of one domain(https://sample_url/WhatsappBot/index.php), and gave the URL (https://sample_url/WhatsappBot/). As per their API documentation, they will pass a response to that URL, so I want to fetch that. Here is the remaining part of API documentation API documentation2, API documentation3, API documentation4. So I created one curl.php named file, that code is given below.
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://sample_url/WhatsappBot/');
// curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$headers = array();
$headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch))
{
echo 'Error:' . curl_error($ch) ."\n";
}
else
{
$result_value = json_decode($result,true,JSON_PRETTY_PRINT);
echo $result_value;
// var_dump($result_value);
}
curl_close($ch);
?>
they provided a collection of API for reference, but I am getting the wrong result. In their collection API have the result,
Collection API result
but I am getting this,
myresult
What is the wrong in this code? Can anyone please help me...
Your Callback URL should contain a program that receive a POST data as JSON, Go ahead to decode the JSON data, using the data received, proceed with what ever logic you plan to execute.
//this should be in your call back URL index.php
$post_data_expected = file_get_contents("php://input");
$decoded_data = json_decode($post_data_expected, true);
You can your POSTMAN to always test your callback URL to see it behaves the way you expects.
How can I send a pageview event via Measurement Protocol to a GA4 property with PHP?
This is how I'm doing, but inside my Google Analytics 4 property I can't see any traffic.
$data = array(
'api_secret' => 'XXXX-YYYYY',
'measurement_id' => 'G-12345678',
'client_id' => gen_uuid(), // generates a random id
'events' => array(
'name' => 'page_view',
'params' => array(),
)
);
$url = 'https://www.google-analytics.com/mp/collect';
$content = http_build_query($data);
$content = utf8_encode($content);
$ch = curl_init();
curl_setopt($ch,CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-type: application/x-www-form-urlencoded'));
curl_setopt($ch,CURLOPT_HTTP_VERSION,CURL_HTTP_VERSION_1_1);
curl_setopt($ch,CURLOPT_POST, TRUE);
curl_setopt($ch,CURLOPT_POSTFIELDS, $content);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
curl_close($ch);
I'm working on registering pageviews to track API usage right now, here's what I've found:
XTOTHEL is right about setting the content type to content/json above. In addition to specifying the content type you also have to send JSON data as the CURLOPT_POSTFIELDS data.
Also per their specification the api_secret and measurement_id need to be part of the URI: https://developers.google.com/analytics/devguides/collection/protocol/ga4/sending-events?client_type=gtag#required_parameters
Lastly, you can use debug mode to validate your responses and figure out what's going on now by simply changing the URL to google-analytics.com/debug/mp/collect
Here's the code I'm working with right now:
//retrieve or generate GA tracking id
if (empty($_COOKIE['_cid'])) {
setcookie('_cid', vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex(random_bytes(16)), 4)));
}
$data = '{"client_id":"'.$_COOKIE['_cid'].'","events":[{"name":"load_endpoint","params":{"page_location":"'.$request->fullUrl().'"}}]}';
echo '<pre>';
print_r($data);
$measurement_id = 'G-xxxxx';
$api_secret = 'xxxx';
$url = 'https://www.google-analytics.com/debug/mp/collect?api_secret='.$api_secret.'&measurement_id='.$measurement_id;
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
This works to a certain extent. Currently it's registering the page view as a custom event instead of an actual pageview though. I'm still trying to figure out how to get them to come through as page views.
Follow up
After a little more debugging I figured out page views are actually working, they just weren't showing up in some of the views. The fix for that was to add page_title into the params:
$data = '
{
"client_id": "'.$_COOKIE['_cid'].'",
"events": [
{
"name": "page_view",
"params": {
"page_location": "'.$request->fullUrl().'",
"page_title": "'.$request->path().'"
}
}
]
}
';
A few extra notes for whoever comes next:
Debug mode did return some useful validation errors for invalid top-level parameters (client_id, events) - but it didn't return errors for anything inside of the "params" for events. IE - i put "page_asdtitle" instead of "page_title" and it accepted it just fine.
None of the tests I sent through actually showed up in the debug panel while using debug mode. I suspect this is because of the data propagation delay, it's probably not loading realtime data.
Using a JSON validator can help. Make sure you use objects and arrays where GA tells you to.
If you get stuck figuring out why your PHP code doesn't work, write the code as a browser event in JavaScript and run it in your browser. There's tons of examples on how to do that. From there, you can use Dev Tools -> Network to inspect the request. If you right click on the google analytics request to the 'collect' endpoint you'll see an option to Copy Request as CURL. Put that into a text editor and compare it to what your PHP code is sending.
To ACTUALLY test this without the massive propagation delay you can login to Google Analytics, go to Reports -> Realtime, and you should see your data show up within 30-60 seconds if it's working. Realtime data will NOT show up if you're using the /debug/ endpoint though.
I would like to create new categories in CS-Cart through its API.
So far I have this code (running it through browser, just for testing):
$cfg = get_config(); //connection to DB
$product_data = array();
$product_data["category"] = "Category Test API";
$product_data["company_id"] = 1;
$product_data["status"] = "A";
//CURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_USERPWD, 'USER EMAIL'.":".'YOUR API:KEY');
curl_setopt($ch, CURLOPT_URL, $cfg["cscart_store_url"]."api/categories/");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json'
)
);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($product_data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
if( !curl_error($ch) ) {
echo "no error";
curl_close($ch);
return json_decode($server_output, TRUE);
}
else {
echo "error found!!!";
print_r("Error: ".curl_error($ch));
return 0;
}
There is a documentation here: https://docs.cs-cart.com/latest/developer_guide/api/entities/categories.html.
But I still couldn't make it work although I did not get any errors from curl_exec.
Your json is well encoded, your header have the Content-Type, i think your problem is your cscart_store_url who have a wrong url or your USERPWD isn't good (I believe you didnt put USER EMAIL in your auth
As long as I understood, cs-cart API has some required values in order to make an INSERT API call. Thus, the categories should be already be created inside cs-cart dashboard and match them somehow in the PHP script
On the other hand, if you want to UPDAtE a product for example, you could UPDAte only the specified values you send to API call, without the need of sending all the required API values.
Last but not least, there are more than one Authorizations methods to make the call. I used CURL in order to do the API call and there is a parameter CURLOPT_HTTPHEADER which I have added the below code:
...
CURLOPT_HTTPHEADER => array(
"Authorization: Basic XXXxxxxXXXXxxxXXXlzLmNvbS5ncjpKejMXXXxxxxXN0Y2MDQxenprbEXXXxxXXXE3Mg==",
"Content-Type: application/json",
"cache-control: no-cache"
),
...
Where Authorization is: Basic base64(user#example.com:API_KEY_taken_from_cscart)
Applying all the above the code and the API worked!
thanks everyone for the help and comments
I've been fiddling around with Facebook Messenger Platform for the past couple days and have run into an issue. PHP has been the primary language.
Successfully, I've been able to implement a couple API's into the system, through plain text. (See image below)
This is what the system looks like:
$input = json_decode(file_get_contents('php://input'), true);
$senderId = $input['entry'][0]['messaging'][0]['sender']['id'];
$message = $input['entry'][0]['messaging'][0]['message']['text'];
$answer = "I don't understand that. Is that another language? Type 'hi' to get started.";
if($message == "hi") {
$answer = "Yo!";
}
All of this comes from the Facebook Messenger Getting Started if you're not familiar.
What I'm attempting to do now is pass an image through cURL onto JSON. This is something I'm unfamiliar with, but have found two great sources to help me with this task. POSTing JSON Data With PHP cURL and Create nested list from Multidimensional Array.
Here is the result:
if($message == "test") {
$data = array("message" => array("attachement" => array('"type" => "image"'),"payload" => array('"url" => "http://example.com"')));
$data_string = json_encode($data);
$ch = curl_init('https://graph.facebook.com/v2.6/me/messages?access_token=TOKEN_GOES_HERE');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$answer = curl_exec($ch);
}
Here is the response I receive:
I know for sure, that the parameters are not properly being picked up by cURL. Though, my limited knowledge on cuRL, suggests otherwise. My question is, how could I still achieve this? I want to be able to pass an image through JSON into messenger, using PHP.
I think your post request works fine, but due to the error, you didn't pass the whole json data.
Below is how a image generic message looks like, where did you put the recipient in your data?
{
"recipient":{
"id":"USER_ID"
},
"message":{
"attachment":{
"type":"image",
"payload":{
"url":"https://petersapparel.com/img/shirt.png"
}
}
}
}
reference: https://developers.facebook.com/docs/messenger-platform/send-api-reference#guidelines
HI there can you please tell me that what are connector-guid, user-guid and api key in below given code and how to get them for any website?
<pre>
<?php
$userGuid = "8f65f01f-c6bc-42a4-914d-879efd159abd";
$apiKey = "private";
// Issues a query request to import.io
function query($connectorGuid, $input, $userGuid, $apiKey) {
$url = "https://query.import.io/store/connector/" . $connectorGuid . "/_query?_user=" . urlencode($userGuid) . "&_apikey=" . urlencode($apiKey);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type: application/json",
"import-io-client: import.io PHP client",
"import-io-client-version: 2.0.0"
));
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(array("input" => $input)));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result);
}
// Query for tile Curs Banca Comerciala Feroviara
$result = query("7d00ba0e-947c-403f-b33b-886a7ee2a300", array(
"webpage/url" => "http://www.bfer.ro/ro/curs-valutar/",
), $userGuid, $apiKey, false);
var_dump($result);
?>
User-guid is a your import.io user unique identificator. You might see it at your user's settings' page.
Connector-guid is a unique identifier for each connector in general sence, it might be a connector, a crawler, an extractor. It's issued for each api connector automatically. You might get it for each api piece. See the data page. Below is an example of crawler with the connector-guid (in a white box):
API key is your unique key to all your api. It's renewable (you might generate a new one). Just enter your account page, get to the API key line and input your password to unlock api key. Read more here how to get an api key.
Unlocked api key:
Not sure but here is what i think. I think connectorGuid is some random key used to create the link to the web api.
The apiKey is obviously the api key.
userGuid again is some identification of records
All web apis are not the same so you cant get api details of any website