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.
Related
Im using 2ba its API to receive product information which I later on want to store inside my database. I am trying to create a post request for receiving the data I need. This is the request I want to get to working. And this is my code:
postApiData.php
<?php
/**
* Posts API data based on given parameters at index.php.
*/
// Base url for all api calls.
$baseURL = 'https://api.2ba.nl';
// Version number and protocol.
$versionAndProtocol = '/1/json/';
// All parts together.
$url = $baseURL . $versionAndProtocol . $endPoint;
// Init session for CURL.
$ch = curl_init();
// Init headers. Security for acces data.
$headers = array();
$headers[] = "Authorization: Bearer " . $token->access_token;
// Options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($parameters));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
// Execute request.
$data = curl_exec($ch);
// If there is an error. Show whats wrong.
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
echo "<br>";
echo "Error location: postApiData";
exit();
}
// Ends the CURL session, frees all resources that belongs to the curl (ch).
curl_close($ch);
// String to array.
$data = json_decode($data);
?>
index.php
// Specified url endpoint. This comes after the baseUrl.
$endPoint = 'Product/forGLNAndProductcodes';
// Parameters that are required or/and optional for the endPoint its request.
$parameters = [
'gln' => '2220000075756',
'productcodes' => ['84622270']
];
// Get Supplier info
include("postApiData.php");
print_r($data);
exit();
My API key does for sure work since I have done alot of different GET requests already, also im not getting an access denied error.
The error I get with this code is: The requested URL returned error: 500 Internal Server Error
I also receive a "Bad request" 400 error when I remove the curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($parameters)); part
Is there anyone who knows what im doing wrong?
PS: It's not really possible to try this code yourself unless you have a 2ba account with working key's etc.
Okey I fixed it already...
I had to add some extra headers and change the $parameters values like this:
postApiData.php
// Added this above the authorization.
$headers[] = "Connection: close";
$headers[] = "Accept-Encoding: gzip,deflate";
$headers[] = "Content-Type: application/json";
// Removed the http_build_query part.
curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
index.php
// Encoded in a json way as asked by 2ba request.
$parameters = json_encode($parameters);
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.
I am trying to send a json to a url and get a response back. I am creating the json correctly I believe. However when I try to send it via php curl I do not get a response back. The url I am sending it to does populate a response though.
Here is the php:
<?php
$post = array("prompt" => $question, "functionName" => $func_name, "argumentNames" => $argumentNames, "testCases" => $testCases);
$transfer = json_encode($post);
$ctrl = curl_init();
curl_setopt($ctrl, CURLOPT_URL, "https://sample.com/question/add-question.php");
curl_setopt($ctrl, CURLOPT_POST, TRUE);
curl_setopt($ctrl, CURLOPT_POSTFIELDS, $transfer);
curl_setopt($ctrl, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($ctrl);
curl_close($ctrl);
$response = json_decode($response);
echo $response;
?>
If I were to echo $transfer it would read:
{
"prompt":"Write a function named test that takes 2 argument(s) and adds them. The type of the arguments passed into the function and the value to be returned is int. The arguments for the function should be arg1 and arg2 depending on the number of arguments the function needs.",
"functionName":"test",
"argumentNames":["arg1","arg2"],
"testCases":{"input":["2","2"],
"output":"4"}
}
I would like to echo the response from the url I am sending the json too but instead, I get nothing back. However the url in the curl sequence (https://sample.com/question/add-question.php) does output a json on the webpage:
{"message":"An unknown internal error occured","success":false}
How am I not able to grab this and echo it in my original code snippet? Is it something wrong with my curl method?
Try setting the header to say you are sending JSON...
curl_setopt($ctrl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($transfer))
);
For the HTTPS, you may also need...
curl_setopt($ctrl, CURLOPT_SSL_VERIFYPEER, false);
You also may try...
curl_setopt($ctrl, CURLOPT_FOLLOWLOCATION, 1);
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;
Can someone please tell me where is the error in this code?, I use a mobile iphone application to call a php script tha will send information to apple. Apple then will return a JSON object containing several values in an associative array.
I want to reach the 'status' value but every time I run the code in the phone, the php script sends me the complete apple's returned string. In the XCode debugger the received string looks like:
[DEBUG]... responseString :
{"receipt":{"item_id":"328348691",
"original_transaction_id":"1000000000081203",
"bvrs":"1.0", "product_id":"julia_01",
"purchase_date":"2009-10-05 23:47:00
Etc/GMT", "quantity":"1",
"bid":"com.latin3g.chicasexy1",
"original_purchase_date":"2009-10-05
23:47:00 Etc/GMT",
"transaction_id":"1000000000081203"},
"status":0}
but the only piece I care in the string is the "status" value.
I've already looked inside documentation but can't find the solution. I'm new in php but this getting too long. Here the script:
<?php
//The script takes arguments from phone's GET call
$receipt = json_encode(array("receipt-data" => $_GET["receipt"]));
//Apple's url
$url = "https://sandbox.itunes.apple.com/verifyReceipt";
//USe cURL to create a post request
//initialize cURL
$ch = curl_init();
// set the target url
curl_setopt($ch, CURLOPT_URL,$url);
// howmany parameter to post
curl_setopt($ch, CURLOPT_POST, 1);
// the receipt as parameter
curl_setopt($ch, CURLOPT_POSTFIELDS,$receipt);
$result = curl_exec ($ch);
//Here the code "breaks" and return the complete string (i've tested that)
//and apparently doesn't get to the json_decode function (i think something's wrong there, so code breaks here)
curl_close ($ch);
$response = json_decode($result);
echo $response->{'status'};
?>
Even if I don't put any echo at the end, the script still returns a complete string (odd to me)
Thank's in advance and apollogies if I insist again from another question
Try setting the RETURNTRANSFER option to 1 so you can capture the output from the requested URL as a string. It seems that the default behaviour of cURL is to output the result directly to the browser:
...
$ch = curl_init();
// set the target url
curl_setopt($ch, CURLOPT_URL,$url);
// howmany parameter to post
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // <---- Add this
// the receipt as parameter
curl_setopt($ch, CURLOPT_POSTFIELDS,$receipt);
...