Slack Incoming Webhooks returns Payload was not valid JSON and the documentation doesn't seem to make a whole lot of sense.
public function index() {
$message = [
"pretext" => "There's been a sale on Example Cart",
"title" => "Sales Order #123456 on Example Cart",
"title_link" => "http://www.example.com/admin/index.php?route=sale/order/info&order_id=123456",
"text" => "There's been a new sale on the Example website. Click the order above to check it out.",
];
$send = self::slack($message);
dd($send); // die and dump curl result
}
public static function slack($message, $room = "test-messages", $color = "#ED7100", $icon = ":mailbox:") {
foreach ($message as $key => $value):
$message[$key] = str_replace(["<", ">", "&"], ["<", ">", "&"], $value);
endforeach;
$fallback = $message["pretext"] . " - " . $message["title"] . " - " . $message["title_link"];
$attachments = [
"fallback" => $fallback,
"pretext" => $message["pretext"],
"title" => $message["title"],
"title_link" => $message["title_link"],
"text" => $message["text"],
"color" => $color,
];
$payload = [
"channel" => "#{$room}",
"channel" => "#bossman",
"icon_emoji" => $icon,
"username" => "webhook-tests",
"attachments" => [$attachments]
];
$data = "payload=" . json_encode($payload);
$ch = curl_init("https://hooks.slack.com/services/endpoint");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
When I lint the JSON in any of the online linters it returns as valid JSON.
What is Slack looking for that's not in the documentation?
It looks like your POST data is being sent with payload= at the front instead of as the key.
This gist sends the data like so:
$data = json_encode($payload);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('payload' => $data));
Related
I'm trying to pass some arguments in Curl but I realize that when I use test data (simple strings), I can get the result (payId and payUrl) but when I use variables instead of test data, I get nothing back.
What's the best way to troubleshoot this type of issue? It's my first time using Curl so I'm creating this function based on articles I found here.
For instance, if I replace "name" with $clientName, I won't get any return from the API.
function generatePayment($sendId, $clientCPF, $clientName, $clientEmail, $clientCep, $clientPhone, $amount){
// CONFIG
$urlCallBack = "http://192.168.0.79/sistema/admin/shipList.php?transactionStatus=success";
$urlError = "http://192.168.0.79/sistema/admin/shipList.php?transactionStatus=failed";
$debug = true;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'urlhere');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{\n\t\"reference\": \"my-order-ref-0001\",\n\t\"client\": {\n \t\"cpf\": \"43164853858\",\n \t\"name\": \"John Doe\",\n \t\"email\": \"johndoe#example.com\",\n \t\"birthdate\": \"1982-01-14\",\n \t\"cep\": \"18053190\",\n \t\"phone\": \"15987452584\"\n\t},\n\t\"items\": [\n \t{\n \t\"reference\": \"my-item-ref-0001\",\n \t\"description\": \"Apple iMac 21.5-inch\",\n \t\"quantity\": \"1\",\n \t\"amount\": 149900\n \t},\n \t{\n \t\"reference\": \"my-item-ref-0002\",\n \t\"description\": \"Apple iPhone 11 Pro\",\n \t\"quantity\": 1,\n \t\"amount\": 99900\n \t}\n\t],\n \"coupon\": {\n \"code\": \"10DESCONTO\",\n \"value\": 1000,\n \"issuer\": \"merchant_api\"\n },\n\t\"shipping\": {\n \"amount\": 1000\n\t},\n\t\"redirect\": {\n \t \"success\": \"https://example.com/sp_callback?success\",\n \t \"failed\": \"https://example.com/sp_callback?failed\"\n\t}\n}");
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: Bearer '.$_POST['token'];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
} else {
if ($debug){
echo "<BR><BR><BR> DATA PASSED TO FUNCTION <BR>";
echo "<br>sendId ===> ".$sendId;
echo "<br>clientCPF ===> ".$clientCPF;
echo "<br>clientName ===> ".$clientName;
echo "<br>clientEmail ===> ".$clientEmail;
echo "<br>clientCep ===> ".$clientCep;
echo "<br>clientPhone ===> ".$clientPhone;
echo "<br>amount ===> ".$amount;
$decode = json_decode($result,true);
echo "<BR><BR> DATA RECEIVED FROM API <BR>";
echo '<br> payId generated by API ==> '.$payId = $decode['data']['order_id'];
echo '<br> PayURL generated by API ==>'.$payUrl = $decode['data']['url_checkout'];
} else {
$decode = json_decode($result,true);
$transactionId = $decode['data']['order_id'];
$payUrl = $decode['data']['url_checkout'];
$_SESSION['transactionUrl'] = $decode['data']['url_checkout'];
$_SESSION['transactionId'] = $transactionId;
$_SESSION['sendId'] = $sendId;
}
}
curl_close($ch);
// END GENERATE PAYMENT
}
Any help is appreciated on how to troubleshoot.
Updating Code using JSON
//INITIALIZE
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://sandbox.splipay.com/api/orders');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
// POST
$post = array(
"items" => array (
"description" => "Test",
"quantity" => 1,
"amount" => 10
),
"redirect" => array (
"success" => "www.success",
"failed" => "www.success"
)
);
$post = json_encode($post);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
// HEADERS
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: Bearer '.$_POST['token'];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
//EXECUTE
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
} else {
$arr = json_decode($result);
echo "<br><br>Return from VAR_DUMP";
var_dump ($arr);
echo "<BR><BR>INFO RETURN<BR>";
$info = curl_getinfo($ch);
var_dump ($info);
// $_POST['token'] = $arr['access_token'];
}
curl_close($ch);
As per documentation, these are the only values I need to pass to the API and I'd get the following response (example):
{
"success": true,
"data": {
"order_id": 57,
"url_checkout": "https://sandbox.splipay.com/payment/4openRe7Az/kzPdyP7bQr?expires=1583164527&signature=e1caae419137903f930f5a5b3d4c72608a61c0fdd36c70803d4a92c15556a4c5"
}
}
After moving to a JSON format and reviewing the API requirements, I was able to fix this. Once in JSON, it was easier to identify that there was issue with the multi dimensional array. I rewrote the code and it's working now. Thanks everyone
JSON
$post = array(
"reference" => "my-order-ref-0001",
"client" => array (
"cpf" => "43164853858",
"name" => "John Doe",
"email" => "johndoe#example.com",
"birthdate" => "1982-01-14",
"cep" => "18053190",
"phone" => "15987452584"
),
"items" => array (
array (
"reference" => "my-item-ref-0001",
"description" => "Test",
"quantity" => 1,
"amount" => 10
),
),
"coupon" => array(
"code" => "10DESCONTO",
"value" => 1000,
"issuer" => "merchant_api"
),
"shipping" => array (
"amount"=> 1000
),
"redirect" => array (
"success" => "www.success",
"failed" => "www.success"
)
);
All i know is company name and its country. Can anyone provide a sample php code. On Running this code I get an error property not found, "organisation email contact".
<?php
$service_url = 'https://www.googleapis.com/freebase/v1/search';
$params = array(
'query' => 'Emirates',
'key' => "My-Key",
'filter' => '(all type:/business/business_operation)',
"output" => '(/organization/email_contact )',
// "result" => array(
// "/organization/organization/email" => [],
// "name" => "Freebase Staff",
// "id" => "/business/business_operation"
// )
);
$url = $service_url . '?' . http_build_query($params);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = json_decode(curl_exec($ch), true);
curl_close($ch);
print "<pre>";print_r($response);print "</pre>";
?>
Try changing the output field parameter value:
"output" => '(/organization/email_contact )' to "output" =>
'(all/organization/email_contact)'
I'm sending a text push from the php API code successfully, but I wonder how to send the JSON also from the PHP API
My problem is that when I send JSON from the PHP API code it received like like a "message" type.
When i send the same JSON code from the parse control panel it works fine
I so some hint to send "uri" key in the data, but it didn't help.
What am I missing?
Thanks.
this is the PHP code that i'm using
<?php
$APPLICATION_ID = "gggggggggggggggg";
$REST_API_KEY = "xxxxxxxxxxxxxxxxxxx";
//$MESSAGE = "your-alert-message";
if (!empty($_POST)) {
$errors = array();
foreach (array('app' => 'APPLICATION_ID', 'api' => 'REST_API_KEY', 'body' => 'MESSAGE') as $key => $var) {
if (empty($_POST[$key])) {
$errors[$var] = true;
} else {
$$var = $_POST[$key];
}
}
if (!$errors) {
$url = 'https://api.parse.com/1/push';
if(strstr($MESSAGE,"{")){ //json
$data['data_type']='json';
//$MESSAGE = json_decode($MESSAGE);
}
//, 'uri' => $MESSAGE
$data = array(
'channel' => 'test1',
'type' => 'android',
'expiry' => 1451606400,
'data_type' => 'json',
'data' =>array(
'alert'=> "the link2",
'uri' => $MESSAGE
),
'uri' => $MESSAGE
);
//var_dump( $data );die;
//if(strstr($MESSAGE,"{")) //json
//$data['data_type']='json';
$_data = json_encode($data);
//var_dump( $_data );die;
$headers = array(
'X-Parse-Application-Id: ' . $APPLICATION_ID,
'X-Parse-REST-API-Key: ' . $REST_API_KEY,
'Content-Type: application/json',
'Content-Length: ' . strlen($_data)
);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $_data);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
// curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($curl);
}
}
?>
In the parse.com website there is a tool that you can send PUSH and in this tool you can send push with 2 types: plain text, or JSON.
it's look like that
When I try to send push with this parse.com tool in both types it works fine and I get the push properly
But, when I try to send to push from my PHP API code as a "JSON" I always got it as a "plain text"
What am I'm doing wrong ?
It depends on your JSON structure for example i want to send this:
{
"data": {
"date": "2015-12-09",
"message": "and when you open this we will show you a message.",
"title": "6 Notice Click On It :)))",
"url": ""
},
"is_background": false
}
and in your php you should send like this:
$data = array(
'where' => '{}', // send to all users
// 'channels' => '{my_channel_name}',
'data' => array(
'is_background'=>false,
'data'=>array(
'date'=>'2015-12-09',
'message'=>'and when you open this we will show you a message',
'title'=>' Notice Click On It',
'url'=>''
),
),
);
In my gcm android app I am sending 2 types of messages from application server.I got the idea about what is collapse key, but Idont know how to use.These are the two types of messages.
1.
$message = array(
"price" => "signal",
"type" => $user_type,
"date" => $date1,
"name" => $signal_name,
"buy" => $price,
"stop" => $stop,
"tv" => $trig_value,
"tp" => $profit,
"res" => $result,
);
second one
$message = array(
"price" => "instru",
"price1" => $trade1,
"price2" => "$trade2",
"price3" => "$trade3",
"price4" => "$trade4",
"price5" => "$date"
);
What I need is the last messages send for both of the message types persist in gcm server.How can I do that.I am giving the gcm class also .Please help.
GCM.php
<?php
class GCM {
//put your code here
// constructor
function __construct() {
}
/**
* Sending Push Notification
*/
public function send_notification($registatoin_ids, $message) {
// include config
include_once './config.php';
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $message,
);
$headers = array(
'Authorization: key='.GOOGLE_API_KEY,
'Content-Type: application/json'
);
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Disabling SSL Certificate support temporarly
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
// Execute post
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
// Close connection
curl_close($ch);
echo $result;
}
}
?>
You should add the collapse_key parameter to your JSON.
The JSON should look like this :
For example, for the first type :
{
"registration_ids":["...", "..."],
"collapse_key": "type1",
"data": {
"price" => "...",
"type" => "...",
...
},
}
For the second type, give a different value to collapse_key.
Based on your code and my limited knowledge of PHP, you need something like this :
$fields = array(
'collapse_key' => $collapse_key,
'registration_ids' => $registatoin_ids,
'data' => $message,
);
And the $collapse_key should be initialized based on the type of data you have in $message.
example.com URL
I am calling this url but getting jsonCallback({"ERROR": "6"});. I cannot understand what this is. I have searched many times for the error but could not find out anything helpful.
This is a website by calling this url I will get price list. When I am calling this from the website itself I am getting the data properly. but whenever I a m going to copy the http request and paste it to url it is showing error.
Below are my CURL request :
<?php
class CURL {
var $callback = false;
function setCallback($func_name) {
$this->callback = $func_name;
}
function doRequest($method, $url, $vars) {
$headers=array();
$headerVar=0;
$headers[$headerVar]='Content-Type: text/javascript; charset=UTF-8';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
//curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');
if ($method == 'POST') {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);
}
$data = curl_exec($ch);
curl_close($ch);
echo '<br><br>'.curl_error().'-----'.curl_error();
return $data;
if ($data) {
if ($this->callback)
{
$callback = $this->callback;
$this->callback = false;
return call_user_func($callback, $data);
} else {
return $data;
}
} else {
return curl_error($ch);
}
}
function get($url) {
return $this->doRequest('GET', $url, 'NULL');
}
function post($url, $vars) {
return $this->doRequest('POST', $url, $vars);
}
}
function stringParameter($array) {
$post_items=array();
foreach ( $array as $key => $value) {
$post_items[] = $key . '=' . $value;
}
//create the final string to be posted using implode()
$post_string = implode ('&', $post_items);
return $post_string;
}
function build_http_query( $query ){
$query_array = array();
foreach( $query as $key => $key_value ){
if($key_value != ''){
$query_array[] = urlencode($key) . '=' . urlencode( $key_value );
}else {
$query_array[] = urlencode($key) . '=' . $key_value ;
}
}
return htmlspecialchars(implode( '&', $query_array ));
}
list($usec, $sec) = explode(" ", microtime());
$time13 = sprintf('%d%03d', $sec, $usec/1000);
$data =
array(
"brand" => "PERODUA",
"model" => "VIVA 1.0",
"gender" => "Male",
"md_age" => '35',
"marital_status" => "Married",
"car_age" => '8',
"ncd" => '0',
"data" =>
array(
"car_data" => array(
"make"=>"PERODUA",
"model"=>"VIVA 1.0",
"year_of_manufacture"=>"2004",
"offpeak"=>"yes"
),
"drivers_data" => array(
"driver_1"=> array(
"gender" => "Male",
"marital_status" => "Married",
"date_of_birth" => "22/3/1978",
"year_driving_license" => "1999",
"ncd" => "0",
"occupation" => "ZADM: Indoor Office/Exec/Admin Staff",
"relationship" => " "
)
),
"discount_data" => array(
"certificate_of_merit" => false
),
"claims_data" => array(
"have_claims" => "no",
"claims_number" => "0",
"claims_amount" => "0"
),
"product_data" => array(
"plan" => null,
"price" => null,
"policy_start"=> "1/5/2013",
"policy_end"=> "30/4/2014",
"ncd"=> false,
"excess"=> null
)
)
);
$encode = build_http_query($data);
$url = 'https://example.com/price?callback=jsonCallback&'.$encode;
$obj = new CURL();
echo $ppp = $obj->get($url);
?>
Am I am wrong in sending the data in the url as it is written in json?
Try to use build_http_query but http_build_query instead
The {"ERROR": "6"} message is a custom error message return by https://axasingaporemotor.appspot.com/price
You will need to contact the owner of that URL in order to understand what they mean by error 6.