I have created a slash command for Slack and I need to send JSON data to Slack. This is the code I am using but the response is treated as plain text by Slack.
$data = "payload=" . json_encode(array(
"content-type" => "application/json",
"text" => "a message",
"response_type" => "ephemeral",
"username" => "user",
"icon_emoji" => ":icon:"
),JSON_UNESCAPED_SLASHES);
echo $data;
Am I missing something?
It seems I wasn't building my JSON file according to SLACK conventions.
It should not have the payload parameter which is only used for incoming web hooks.
The PHP page should include this line:
header('Content-Type: application/json');
The slash command response should be built as follows:
$data = json_encode(array(
"content-type" => "application/json",
"text" => "a message",
"response_type" => "ephemeral",
"username" => "user",
"icon_emoji" => ":icon:"
),JSON_UNESCAPED_SLASHES);
echo $data;
Related
I'm implementing third party API in Laravel where I have to send some data along with fileData with base64.
Like this:
To post the data I'm sending like this:
$requestUrl = $this->baseUrl . $endpoint;
$content = [
'associatedType' => 'property',
'associatedId' => 'XXXXXXX81',
'typeId' => 'DET',
'name' => '304-Smithson-Road-Details.pdf',
"isPrivate" => false,
'fileData' => 'data:application/pdf;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=='
];
$response = Http::withHeaders([
"api-version" => config("apiVersion"),
"customer" => config("customer"),
"Accept" => "application/json-patch+json",
"Authorization" => "Bearer {$this->token}"
])->send($method, $requestUrl, [
"body" => json_encode($content)
])->collect()->toArray();
return $response;
After executing the above code I'm getting null response and file is not uploaded.
Is there any mistake in HTTP request code?
I want to insert data in zoho crm using api v2. first make an array then i encoded json .Request url https://www.zohoapis.com/crm/v2/Contacts.
But i got this error.
Code:
$authtoken = ***********;
$fields={"data":["{\"Last_Name\":\"Test John insert\",\"Email\":\"testjhon#jhon.com\"}"]};
$zoho_url = "https://www.zohoapis.com/crm/v2/Contacts";
Error:
{"data":[{"code":"INVALID_DATA","details":{"expected_data_type":"jsonobject","index":0},"message":"invalid data","status":"error"}]}
Working example:
$fields = json_encode(
array(
"data" => array([
"Company" => "abc",
"Last_Name" => "Tom",
"City" => "Egham"
],
[
"Company" => "abc",
"Last_Name" => "Jerry",
"City" => "Egham"
])
)
);
Send headers this way :
$headers = array(
'Content-Type: application/json',
'Content-Length: ' . strlen($fields),
sprintf('Authorization: Zoho-oauthtoken %s', $oauth)
);
Use this json array:
$fields = "{\"data\":[{\"Last_Name\": \"Test\",\"First_Name\": \"TESTING\",\"Email\": \"demo#w3scloud.com\"}],\"trigger\":[\"approval\",\"workflow\"]}";
send this way :
[{ "data": \[ { "Company":"company name", "Last_Name":"your last name", "Phone":"123456789", "First_Name": "your first name", "Email":"first#gmail.com" } \], “triggger”:\[“workflow”,”approval”,”blueprint”\] }]
click here to view image (request and response via postman)
hope this will help you.
I've noticed that Zoho seems to want an extra pair of brackets around the data. And you might try encoding the data array to a JSON-string before sending it to cURL.
$fields = json_encode([
["data" => ["Last_Name" => "Test John insert","Email" => "testjhon#jhon.com"]],
]);
As #Ghost mentioned, you may also need to change the content-type. According to the PHP docs, passing an array to CURLOPT_POSTFIELDS will set the content-type to multipart/form-data; what you probably want is application/json.
CURLOPT_HTTPHEADER => array(
"Authorization: ".$authtoken,
"Content-Type: application/json"
),
You must send the json file to zoho api, and all be works.:
$fields=["data"=> ['Last_Name'=>'Test John insert','Email'=>'testjhon#jhon.com']];
$fields = json_encode($fields);
I'm trying to covert a curl to guzzle request, here is the curl request.
curl https://{subdomain}.zendesk.com/api/v2/tickets.json \
-d '{"ticket": {"subject": "My printer is on fire!", "comment": { "body": "The smoke is very colorful." }}}' \
-H "Content-Type: application/json" -v -u {email_address}:{password} -X POST
here is the JSON portion:
{
"ticket": {
"requester": {
"name": "The Customer",
"email": "thecustomer#domain.com"
},
"subject": "My printer is on fire!",
"comment": {
"body": "The smoke is very colorful."
}
}
}
Here is my broken PHP code.
$client = new GuzzleHttp\Client();
$res = $client->post('https://midnetworkshelp.zendesk.com/api/v2/tickets/tickets.json', [
'query' => [
'ticket' => ['subject' => 'My print is on Fire'], [
'comment' => [
'body' => 'The smoke is very colorful'] ], 'auth' => ['email', 'Password']]);
echo $res->getBody();
I keep getting access unauthorized for the user, however when I fire the curl command it works fine.
Any idea on what I'm possibly missing here?
Thank you
Ref:
http://curl.haxx.se/docs/manpage.html
http://guzzle.readthedocs.org/en/latest/clients.html
https://github.com/guzzle/log-subscriber
http://guzzle.readthedocs.org/en/latest/clients.html#json
Your biggest issue is that you are not converting your curl request properly.
-d = data that is being posted. In other words this is the body of your request.
-u = the username:pw that is being used to authenticate your request.
-H = extra headers that you want to use within your request.
-v = verbose output.
-X = specifies the request method.
I would recommend instanciating your client as follows:
$client = new GuzzleHttp\Client([
'base_url' => ['https://{subdomain}.zendesk.com/api/{version}/', [
'subdomain' => '<some subdomain name>',
'version' => 'v2',
],
'defaults' => [
'auth' => [ $username, $password],
'headers' => ['Content-Type' => 'application/json'], //only if all requests will be with json
],
'debug' => true, // only for debugging purposes
]);
This will:
Ensure that multiple subsequent requests made to the api will have the authentication information. Saving you from having to add it to each and every request.
Ensure that multipl subsequent (actually all) requests made with this client will contain the specified header. Saving you from having to add it to each and every request.
Provides some degree of future proofing (moving subdomain and api version into editable fields).
If you choose to log your request and response objects you can also do:
// You can use any PSR3 compliant logger in space of "null".
// Log the full request and response messages using echo() calls.
$client->getEmitter()->attach(new GuzzleHttp\Subscriber\Log\LogSubscriber(null, GuzzleHttp\Subscriber\Log\Formatter::DEBUG);
Your request will then simply become:
$json = '{"ticket": {"subject": "My printer is on fire!", "comment": { "body": "The smoke is very colorful." }}}';
$url = 'tickets/tickets.json';
$request = $client->createRequest('POST', $url, [
'body' => $json,
]);
$response = $client->send($request);
or
$json = '{"ticket": {"subject": "My printer is on fire!", "comment": { "body": "The smoke is very colorful." }}}';
$url = 'tickets/tickets.json';
$result = $client->post(, [
'body' => $json,
]);
Edit:
After futher reading Ref 4 more thouroughly it should be possible to do the following:
$url = 'tickets/tickets.json';
$client = new GuzzleHttp\Client([
'base_url' => ['https://{subdomain}.zendesk.com/api/{version}/', [
'subdomain' => '<some subdomain name>',
'version' => 'v2',
],
'defaults' => [
'auth' => [ $username, $password],
],
'debug' => true, // only for debugging purposes
]);
$result = $client->post($url, [
'json' => $json, // Any PHP type that can be operated on by PHP’s json_encode() function.
]);
You shouldn't be using the query parameter, as you need to send the raw json as the body of the request (Not in parameters like you are doing.) Check here for information on how to accomplish this. Also, be sure to try to enable debugging to figure out why a request isn't posting like you want. (You can compare both curl and guzzles debug output to verify they match).
Im trying to build an app that uses the simplenote api but I am having trouble with the authentication part. I am getting a 400 error(bad request).
Im guessing this issue is not related to the simplenote api, it's rather my understanding of the documentation.
Here is what the api is saying:
HTTP POST to the following URL:
https://simple-note.appspot.com/api/login
The body of the request should contain this, but base64-encoded:
email=[email-address]&password=[password]
To be clear, you will concatenate email= with the user’s email address (trimmed),
&password=, and the user’s password; then base64 the resulting string and send it as
the HTTP request body. (Do not encode this request using the standard variable
encoding used for POSTed web forms. We basically ignore the Content+Type header
for this request, but text/plain makes the most sense here.)
And here is my code so far:
$url = 'https://simple-note.appspot.com/api/login';
$data = array('email' => base64_encode($email), 'password' => base64_encode($password));
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data),
),
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
var_dump($result);
I think what they mean is:
$data = base64_encode(http_build_query(array(
"email" => $email,
"password" => $password
));
So base64 encode the resulting string, not the individual parts.
As for making the request. I can recommend you take a look at cURL, it's much faster than file_get_contents.
I'm trying to test out the SugarCRM REST API, running latest version of CE (6.0.1). It seems that whenever I do a query, the API returns "null", nothing else. If I omit the parameters, then the API returns the API description (which the documentation says it should).
I'm trying to perform a login, passing as parameter the method (login), input_type and response_type (json) and rest_data (JSON encoded parameters). The following code does the query:
$api_target = "http://example.com/sugarcrm/service/v2/rest.php";
$parameters = json_encode(array(
"user_auth" => array(
"user_name" => "admin",
"password" => md5("adminpassword"),
),
"application_name" => "Test",
"name_value_list" => array(),
));
$postData = http_build_query(array(
"method" => "login",
"input_type" => "json",
"response_type" => "json",
"rest_data" => $parameters
));
echo $parameters . "\n";
echo $postData . "\n";
echo file_get_contents($api_target, false,
stream_context_create(array(
"http" => array(
"method" => "POST",
"header" => "Content-Type: application/x-www-form-urlencoded\r\n",
"content" => $postData
)
))) . "\n";
I've tried different variations of parameters and using username instead of user_name, and all provide the same result, just a response "null" and that's it.
Try setting input_type and response_type to JSON (capitals). If it doesn't work, go to Sugar installation, edit config.php entry under logger => level and make it debug instead of fatal and see if it says about any errors.