I am trying to achieve send command to discord and I need to execute it.For example if I have some for example ticket bot on my channel,as User I can execute command /ticket "my ticket", I wanna to do the same, but execute command like this thru API, ideally CURL.
Have an idea how to achieve this? Thanks a lot
using php/curl, but have no idea how to execute specific slash command at specific channel:
I
$settings = [
"name" => "blep",
"type" => 1,
"description" => "Send a random adorable animal photo",
];
$json = json_encode($settings);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://discord.com/api/webhooks/1076853235412906165/B1kzN6vwTzd-9idrd8Kyv8p4");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
$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);
}
curl_close($ch);
dd($result);
Related
He or she who answers this question will have a very special place in my heart. I'm trying to update many records at once using Curl with PHP on elasticsearch 7.13. It seems that no matter what I do, I get the error "The bulk request must be terminated by a newline". I have tried many, many renditions of this code. Is there perhaps a way to overload what PHP CURL is doing to force it to use binary data? I believe it is stripping the newline characters, but if I change to plain text submission it won't be accepted by elasticsearch.
public function bulkUpdate(){
$query_json_store = '';
foreach($this->records['hits']['hits'] as $person){
$entry1 = [
"update"=>[
"_id"=> $person['_id'],
"type"=> "doc",
"_index"=> "human_data",
]
];
$entry2 = [
"doc"=>[
"scanned"=> true
]
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'localhost:9200/human_data/doc/_bulk');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, '\n'.json_encode($params)).'\n';
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$headers = array();
$headers[] = 'Content-Type: application/x-ndjson';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
\Log::info($result);
}
}
I'm getting error : Missing or incorrectly formatted payload
I'm generating device token from Apple DeviceCheck API in swift language with real device and also passing Transaction ID to this php api.
jwt token generating successfully with this code but further code not working with apple query bit api.
This is my server side code in php :
<?php
require_once "vendor/autoload.php";
use Zenstruck\JWT\Token;
use Zenstruck\JWT\Signer\OpenSSL\ECDSA\ES256;
use \Ramsey\Uuid\Uuid;
$deviceToken = (isset($_POST["deviceToken"]) ? $_POST["deviceToken"] : null);
$transId = (isset($_POST["transId"]) ? $_POST["transId"] : null);
function generateJWT($teamId, $keyId, $privateKeyFilePath) {
$payload = [
"iss" => $teamId,
"iat" => time()
];
$header = [
"kid" => $keyId
];
$token = new Token($payload, $header);
return (string)$token->sign(new ES256(), $privateKeyFilePath);
}
$teamId = "#####";// I'm passing My team id
$keyId = "#####"; // I'm passing my key id
$privateKeyFilePath = "AuthKey_4AU5LJV3.p8";
$jwt = generateJWT($teamId, $keyId, $privateKeyFilePath);
function postReq($url, $jwt, $bodyArray) {
$header = [
"Authorization: Bearer ". $jwt
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $bodyArray); //Post Fields
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
// curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
// curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$server_output = curl_exec($ch);
//$info = curl_getinfo($ch);
// print_r($info);
//echo 'http code: ' . $info['http_code'] . '<br />';
//echo curl_error($ch);
curl_close($ch);
return $server_output;
}
$body = [
"device_token" => $deviceToken,
"transaction_id" => $transId,
"timestamp" => ceil(microtime(true)*1000)
];
$myjsonis = postReq("https://api.development.devicecheck.apple.com/v1/query_two_bits", $jwt, $body);
echo $myjsonis;
?>
Where is problem in this code? Or any other solution in php code.
Is there anything that I'm missing.
I just checked the Docs. They don't want POST fields like a form, they want a JSON body instead. Here's a snippet of code that you should be able to tweak to do what you require:
$data = array("name" => "delboy1978uk", "age" => "41");
$data_string = json_encode($data);
$ch = curl_init('http://api.local/rest/users');
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))
);
$result = curl_exec($ch);
Actually, looking again at your code, it could be as simple as running json_encode() on your array.
I am trying to call an api called Wave I have used cURL before but never with GRAPHQL queries. I am wondering what is wrong with the below when using cURL. I get an error Bad Request Below is an exmple of my code.
This is what the API cURL is
curl -X POST "https://reef.waveapps.com/graphql/public" \
-H "Authorization: Bearer <ACCESS_TOKEN>" \
-H "Content-Type: application/json" \
-d '{ "query": "query { user { id defaultEmail } }" }'
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://reef.waveapps.com/graphql/public');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, '{ "query": "query { user { id defaultEmail } }');
curl_setopt($ch, CURLOPT_POST, 1);
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: Bearer 1212121';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
var_dump($result);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
Any help would be helpful.
For those wanting to query a GraphQL service WITHOUT a third party library, I basically took Brian's code and tested against a GraphCMS service I had already written Node.js code for. So I knew the url, authorization token, and query all worked.
<?php
$endpoint = "https://api-euwest.graphcms.com/v1/[[your id number here]]/master";//this is provided by graphcms
$authToken = "[[your auth token]]";//this is provided by graphcms
$qry = '{"query":"query {products(where:{status:PUBLISHED}){title,img,description,costPrice,sellPrice,quantity,sku,categories {name},brand {name}}}"}';
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: Bearer '.$authToken;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, $qry);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
var_dump($result);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
?>
All worked fine.
The auth token is a big long character string provided by GraphCMS and only needs to be passed in the header. So no real tricky authentication process - as long as you have the token.
I can recommend using https://github.com/softonic/graphql-client, it has worked great for us.
A way easier way to go about doing this is by using an API platform. I often use Postman, the platform have the functionality to give you the PHP cURL code for a GraphQL request in the GraphQl tools part of the application.
You can create your own client passing whatever middleware you'd like:
$clientWithMiddleware = \MyGuzzleClientWithMiddlware::build();
$graphQLClient = new \Softonic\GraphQL\Client(
$clientWithMiddleware,
new \Softonic\GraphQL\ResponseBuilder()
);
For an example how to build a Guzzle client with middleware you can check this out:
https://github.com/softonic/guzzle-oauth2-middleware/blob/master/src/ClientBuilder.php
If there is no authentication
You can use file_get_contents instead of curl
$url = http://myapi/graphql?query={me{name}}
$html =file_get_contents($url);
echo $html;
use json in query paramter for graphql;
Bit late but I made this code
$endpoint = "https://gql.waveapps.com/graphql/public";
$authToken = ""; //Your Bearer code
$qry = '{"query": "query {user {id firstName lastName defaultEmail createdAt modifiedAt}}"}';
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: Bearer '.$authToken;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $qry);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
var_dump($result);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
I am trying to call Natural Language Understanding Watson API from my PHP code using curl. I have successfully tried curl from terminal. It gives some result on executing this command:
curl -u "my_username":"my_password" "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/analyze?version=2017-02-27&text=I%20still%20have%20a%20dream.&features=sentiment,keywords"
However when I try to use curl in php using this code:
<?php
$url = "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/analyze?version=2017-02-27&text=I%20still%20have%20a%20dream%2C%20a%20dream%20deeply%20rooted%20in%20the%20American%20dream%20%E2%80%93%20one%20day%20this%20nation%20will%20rise%20up%20and%20live%20up%20to%20its%20creed%2C%20%22We%20hold%20these%20truths%20to%20be%20self%20evident%3A%20that%20all%20men%20are%20created%20equal.&features=sentiment,keywords";
$post_args = array(
'version' => '2017-02-27',
'url' => 'https://davidwalsh.name/curl-post',
'features' => 'sentiment,keywords'
);
$headers = array(
'Content-Type:application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERPWD, "my_username:my_password");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
//curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
//curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_args));
$result = curl_exec($ch);
if ($result === FALSE) {
die('Send Error: ' . curl_error($ch));
}
curl_close($ch);
echo $result;
?>
I get this result:
{
"error": "unsupported media type",
"code": 415
}
What should be done?
I can't believe I was stuck here due to a blank space.
Replacing this:
$headers = array(
'Content-Type:application/json'
);
with
$headers = array(
'Content-Type: application/json'
);
worked. Note the blank space between : and application/json.
Trying to send a post request to the ServiceM8 Api however when i attempt the request i get back no errors and nothing adding to the ServiceM8 api.
Here is what servicem8 docs suggest:
curl -u email:password
-H "Content-Type: application/json"
-H "Accept: application/json"
-d '{"status": "Quote", "job_address":"1 Infinite Loop, Cupertino, California 95014, United States","company_id":"Apple","description":"Client has requested quote for service delivery","contact_first":"John","contact_last":"Smith"}'
-X POST https://api.servicem8.com/api_1.0/job.json
and here is what i have:
$data = array(
"username" => "**************8",
"password" => "****************",
"job_address" => "1 Infinite Loop, Cupertino, California 95014, United States"
);
$url_send ="https://api.servicem8.com/api_1.0/job.json";
$str_data = json_encode($data);
function sendPostData($url, $post){
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS,$post);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$result = curl_exec($ch);
return $result;
-- UPDATE TO SHOW PREVIOUS ATTEMPTS TO RESOLVE BUT HAD NO LUCK..
<?php
$data = array(
"username" => "*******************",
"password" => "**********",
"job_address" => "1 Infinite Loop, Cupertino, California 95014, United States"
);
$url_send ="https://api.servicem8.com/api_1.0/job.json";
$str_data = json_encode($data);
function sendPostData($url, $post){
$headers= array('Accept: application/json','Content-Type: application/json');
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS,$post);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$result = curl_exec($ch);
curl_close($ch); // Seems like good practice
return $result;
}
echo " " . sendPostData($url_send, $str_data);
?>
adding the headers as i have in that example still does nothing and does not create the record in servicem8 or show an error.
Hopefully someone can help me make the correct Curl request using the PHP libary.
Thanks
First issue is it looks like you are not setting authentication details correctly. To use HTTP basic auth in CURL:
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
Second issue is that job_status is a mandatory field when creating Jobs, so you need to make sure to include that as part of your create request.
Assuming that you receive a HTTP 200 response, then you the UUID of the record you just created is returned in the x-record-uuid header (docs). See this answer for an example of how to get headers from a HTTP response in CURL.
Here's your example code modified to include the above advice:
$data = array(
"job_address" => "1 Infinite Loop, Cupertino, California 95014, United States",
"status" => "Work Order"
);
$url_send = "https://api.servicem8.com/api_1.0/job.json";
$str_data = json_encode($data);
function sendPostData($url, $post, $username, $password) {
$ch = curl_init($url);
if ($username && $password) {
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
}
$headers = array('Accept: application/json','Content-Type: application/json');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 1); // Return HTTP headers as part of $result
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$result = curl_exec($ch);
// $result is the HTTP headers followed by \r\n\r\n followed by the HTTP body
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($result, 0, $header_size);
$body = substr($result, $header_size);
$strRecordUUID = "";
$arrHeaders = explode("\r\n", $header);
foreach ($arrHeaders as $strThisHeader) {
list($name, $value) = explode(':', $strThisHeader);
if (strtolower($name) == "x-record-uuid") {
$strRecordUUID = trim($value);
break;
}
}
echo "The UUID of the created record is $strRecordUUID<br />";
return $body;
}
echo "the response from the server was <pre>" . sendPostData($url_send, $str_data, $username, $password) . "</pre>";