Facebook Messenger Bot - PHP cURL messages - php

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

Related

How to fetch response from a callback URL using php?

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.

Create record in salesforce lightning API curl/php

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.

Slack Slash Command - Getting user icon URL with username (PHP)

I am new at programming Slash commands in Slack. For one of my commands, I have a username and need to retrieve the user icon URL. I am using PHP to code them.
I was planning on using users.profile.get, since the tutorial here shows that one of the fields returned is the user icon URL.
However, I am trying to find examples on how to make a call to this method and have not found any. Could anybody give me a quick example of the call, including how to send the parameters?
This is how far I got:
$slack_profile_url = "https://slack.com/api/users.profile.get";
$fields = urlencode($data);
$slack_call = curl_init($slack_profile_url);
curl_setopt($slack_call, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($slack_call, CURLOPT_POSTFIELDS, $fields);
curl_setopt($slack_call, CURLOPT_CRLF, true);
curl_setopt($slack_call, CURLOPT_RETURNTRANSFER, true);
curl_setopt($slack_call, CURLOPT_HTTPHEADER, array(
"Content-Type: application/x-www-form-urlencoded",
"Content-Length: " . strlen($fields))
);
$profile = curl_exec($slack_call);
curl_close($slack_call);
I basically have $token and $user_name and need to get the profile picture URL. How do I format $token and $username as $data? Is the call correct?
If anybody recommends doing this a different way, I would appreciate any advice as well.
Thank you so much!
To get data into the right format to post to Slack is pretty straight forward. There's two options (POST body or application/x-www-form-urlencoded).
The query string for application/x-www-form-urlencoded is formatted like a get URL string.
https://slack.com/api/users.profile.get?token={token}&user={user}
// Optionally you can add pretty=1 to make it more readable
https://slack.com/api/users.profile.get?token={token}&user={user}&pretty=1
Just request that URL and you will retrieve the data.
The POST body format will use a similar code to what you have above.
$loc = "https://slack.com/api/users.profile.get";
$POST['token'] = "{token}";
$POST['user'] = "{user}";
$ch = curl_init($loc);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $POST);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
if ($error = curl_errno($ch)) { echo $error; }
//close connection
curl_close($ch);
echo $result;

Web push notification error with curl send message

I want to understand what is web-push and how can i use for my projects...
Have found this example https://mobiforge.com/design-development/web-push-notifications
But always getting an error when try to send notification via Firebase Cloud Messaging (FCM is the new version of GCM)
{"multicast_id":6440031216763605980,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}
What it means "InvalidRegistration"? What i'm doing wrong?
My php curl, but i am sure that there is no problem here
$link = "https://gcm-http.googleapis.com/gcm/send";
$header = array();
// $header[] = "Content-length: 0";
$header[] = "Content-type: application/json";
$header[] = "Authorization: key=AIzaSy...";
$contentArray = array(
"collapse_key" => "All",
"registration_ids" => array(
"gAAAAABX06BLKhA4n1yHNlsyzu02wxsDjZf89oxIljwM4ZdLpMZU7ty64TFEYahPQZaTmCeYlJo-WDWnfFHOKXzKURhNtRWmN0OgBgn9hJdmgatSGoiTkt69TeJpiD8F034WOr5HMEG2",
),
"data" => array(
"title" => "This is a Title",
"message" => "This is a GCM Topic Message!"
)
);
$jsonData = json_encode($contentArray);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $link);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
$string = curl_exec($ch);
echo $string;
$data['curl'] = curl_errno($ch);
if(!curl_errno($ch) && !strpos($string, "503"))
$data = array_merge($data, explode("\n", $string));
curl_close($ch);
?><pre><? print_r($data); ?></pre><?
some from Cosole.log
ServiceWorker registration successful with scope: https://.../app/
PushSubscription { endpoint="https://updates.push.ser...rjYvTTapou7WcEDgu3V7IOY", options=PushSubscriptionOptions, getKey=getKey(), ...}
PushSubscription { endpoint="https://updates.push.ser...rjYvTTapou7WcEDgu3V7IOY", options=PushSubscriptionOptions, getKey=getKey(), ...}
gAAAAABX06OYvBIk4q2rRF3AsE6UwRYUpzpZ0jpuiWz6TRrSptb8_cBKjy8Ci-_u5UtAyiGfAYJ_ycYnJjoukSuez7BN6UnSX-GL_EWNAWzEpAVMhCT2wrjYvTTapou7WcEDgu3V7IOY
Please try checking the subscription ID that you used.
As mentioned in Check the response,
If the response shows an invalid registration error, check the subscription ID you used.
As discussed further in making a request to GCM, make sure to use your own API key and subscription ID when you run the cURL command.
For more information, please check the documentation on how to send a request from the command line for GCM to push a message.
It is not working. I have been trying a lot times. here below is how I tried in POSTMan
From my experience, the registration_id you are using seems to be from a subscription on a Firefox browser. But yet you're trying to send it to the Chrome push server.
A Chrome registration_id should look like that:
APA91bGdUldXgd4Eu9MD0qNmGd0K6fu0UvhhNGL9FipYzisrRWbc-qsXpKbxocgSXm7lQuaEOwsJcEWWadNYTyqN8OTMrvNA94shns_BfgFH14wmYw67KZGHsAg74sm1_H7MF2qoyRCwr6AsbTf5n7Cgp7ZqsBZwl8IXGovAuknubr5gaJWBnDc
It's a pretty new technology and earlier versions codes are still available on the google developer platform, so it's not really easy to understand what to do. I'm still experimenting with it.
Check this codelab it's a good example to understand the basics.
I would like to share my answer in this post too.
Check https://stackoverflow.com/a/40447040/4677062 for the same invalid registration id issue.
Its resolved. Works as expected.

Send form values into JSON and php api using QT

I have written an API that I want to accept form values for the HTTP header POST.
Using PHP, I can make use of the API link using the following code:
$data = array(
"authorid" => $_POST['author'],
"filmid" => $_POST['film'],
"content" => "".$_POST['content']."",
"score" => $_POST['score']
);
$post = json_encode($data);
$ch = curl_init('http://www.website.co.uk//v1/review/');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,
array(
'Content-Type: application/json',
'Content-Length: ' . strlen($post))
);
$result = curl_exec($ch);
echo $result;
I am however using the API in a QT application.
What is the best way to store the form values and when they are submitted, send the HTTP header request POST along with the array of data to the link I gave above.
Got no idea how to achieve this!
Thanks,
Luke.
There are tons of questions like this here, just browse through them and find what is closest to your situation. This shows how to do a POST request. Here is another one with JSON serializiation, just google "qt post qnetworkrequest json" and there should be tons of answers.

Categories