I am currently trying to post a message on my Discord channel trying to use a cURL POST type. The issue that I am getting when I run my code is that it is giving me a 401 error saying I'm unauthorized. I am running my PHP code on a webserver using xampp localhost. I also went in and tried to authorize my application bot via URL link (https://discordapp.com/oauth2/authorize?client_id=MYAPPLICATIONID&scope=bot&permissions=8) and have successfully added the bot into my channel. Have a look at my code
$data = array("Authorization: Bot" => $clientSecret, 'content' => 'Test Message');
$data_string = json_encode($data);
$ch = curl_init('https://discordapp.com/api/v6/channels/'.$myChannel.'/messages');
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);
echo $answer;
if (curl_error($ch)) {
echo curl_error($ch);
}
I get $clientSecret from the application page to reveal my client secret token and $myChannel is my discords channel/server id.
NOTE: I have modeled my code off another stackoverflow answer given here discord php curl login Fail . So I am unsure if I am using the correct syntax for the an application bot
Here is full code (Without cURL). Just replace the string WEBHOOK_HERE with your bot's webhook:
<?php
$message = $_POST['message'];
$data = ['content' => $message];
$options = [
'http' => [
'method' => 'POST',
'header' => 'Content-Type: application/json',
'content' => json_encode($data)
]
];
$context = stream_context_create($options);
$result = file_get_contents('WEBHOOK_HERE', false, $context);
?>
<form method="post">
Type your message here :<br><input type="text" name="message"><br>
<input type="submit" value="Submit">
</form>
I'm new here so I hope you enjoy the code!
Close! Your solution has an error.
<?php
$myChannel = "CHANNEL_ID";
$myToken = "TOKEN";
$msg = 'Test Message';
$data = array('content' => $msg);
$data_string = json_encode($data);
$ch = curl_init('https://discordapp.com/api/v6/channels/' . $myChannel . '/messages');
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),
'Authorization: Bot ' . $myToken
)
);
$answer = curl_exec($ch);
echo $answer;
if (curl_error($ch)) {
echo curl_error($ch);
}
?>
I just tested this on my server and it worked. with Bot ' . $token it failed.
I actually had a tough time searching the web for this, without using webhooks. I wanted to post the message as a bot, not a webhook. The error was with your authorization, as it needs to be in the header... So I'm posting the correct solution here for future googlers.
<?php
$myChannel = "CHANNEL_ID";
$myToken = "TOKEN";
$msg = 'Test Message';
$data = array('content' => $msg);
$data_string = json_encode($data);
$ch = curl_init('https://discord.com/api/v6/channels/' . $myChannel . '/messages');
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),
'Authorization: Bot ' . $myToken
)
);
$answer = curl_exec($ch);
echo $answer;
if (curl_error($ch)) {
echo curl_error($ch);
}
?>
Related
I have simple php website (non-wordpress site) and I want to save my posted data to my wordpress database table, Is there a way I can achieve this?
Thank you!
Yes you can save post from another PHP site using this code
<?php
$username = 'adminusername';
$password = 'adminpassword';
$rest_api_url = "https://yourwebsite.com/wp-json/wp/v2/posts";
$data_string = json_encode([
'title' => 'Your Title',
'content' => <<<HEREDOC
Paste you content here
HEREDOC
,
'status' => 'publish',
]);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $rest_api_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string),
'Authorization: Basic ' . base64_encode($username . ':' . $password),
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
if ($result) {
echo 'yes';
} else {
echo 'no';
// ...
}
?>
I'm trying to shorten URL using the bit.ly API V4, but i always get the same error, I can't get the short URL.
Can someone help me please?
Here is the code that Im using:
$long_url = 'https://estaticos.muyinteresante.es/media/cache/1140x_thumb/uploads/images/gallery/59bbb29c5bafe878503c9872/husky-siberiano-bosque.jpg';
$apiv4 = 'https://api-ssl.bitly.com/v4/bitlinks';
$genericAccessToken = 'MyToken';
$data = array(
'long_url' => $long_url
);
$payload = json_encode($data);
$header = array(
'Authorization: Bearer ' . $genericAccessToken,
'Content-Type: application/json',
'Content-Length: ' . strlen($payload)
);
$ch = curl_init($apiv4);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
$result = curl_exec($ch);
$resultToJson = json_decode($result);
if (isset($resultToJson->link)) {
echo $resultToJson->link;
}
else {
echo 'Not found';
}
I always get "Not found", anybody knows why?
I have a very detailed answer on integrating with Bit.ly V4 and how to shorten URLs.
You can find the link here.
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 using ParseAPI (https://parse.com/docs/rest/guide#objects-updating-objects) and I'm attempting to update an object with their rest api. I get a response back from parse saying the object was updated, however no change was made.
Can someone please guide me in the correct direction?
Thank you!!
<?php
$url = ' https://api.parse.com/1/classes/GameScore/Ed1nuqPvcm';
$appId = 'my app id';
$restKey = 'my rest key';
$headers = array(
"Content-Type: application/json",
"X-Parse-REST-API-Key: " . $restKey,
"X-Parse-Application-Id: " . $appId
);
$data = array('pass' => 'hi');
$jsonDataEncoded = json_encode($data);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($jsonDataEncoded));
$response = curl_exec($ch);
echo $response;
?>
I found a great code that sends push messages through the GCM.
The question is if it is possible to change the String "Google Cloud Messaging working well"
Address bar example I would write www.example.com/index.php?text=work
And the string will work.
Thanks
<?php
define("GOOGLE_API_KEY", "AIzaSyCJiVkatisdQ44rEM353PFGbia29mBVscA");
define("GOOGLE_GCM_URL", "https://android.googleapis.com/gcm/send");
function send_gcm_notify($reg_id, $message) {
$fields = array(
'registration_ids' => array( $reg_id ),
'data' => array( "message" => $message ),
);
$headers = array(
'Authorization: key=' . GOOGLE_API_KEY,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, GOOGLE_GCM_URL);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if ($result === FALSE) {
die('Problem occurred: ' . curl_error($ch));
}
curl_close($ch);
echo $result;
}
$reg_id = "APA91bHuSGES.....nn5pWrrSz0dV63pg";
$msg = "Google Cloud Messaging working well";
send_gcm_notify($reg_id, $msg);
Replace
"Google Cloud Messaging working well";
with
$_GET['text'];
to have a nicer code you would use
filter_input (INPUT_GET, 'text', FILTER_SANITIZE_STRING);