Problem to shorten URL using PHP-Bitly v4 - php

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.

Related

invalid_client When Sending OAuth2 Request to Discord API

So I've been working on a login system with Discord, and this is the first roadblock I've hit.
I'm trying to POST to /oauth2/token/revoke and it keeps giving me back the error "invalid_client".
I've tried using a client secret and not using it, only sending the token, changing the name "access_token" to "token", and a few other things I can't recall.
My code for sending the request is this:
session_start();
//debug thing
echo OAUTH2_CLIENT_ID;
$params = array(
"access_token" => $_SESSION["access_token"],
"client_id" => OAUTH2_CLIENT_ID
);
apiRequest("https://discordapp.com/api/oauth2/token/revoke", $params);
The code for that apiRequest function is adapted from a different thread on here and is as follows:
function apiRequest($url, $post=FALSE, $headers=array()) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($ch);
if($post) {
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
}
$headers[] = 'Accept: application/json, application/x-www-form-urlencoded';
if(isset($_SESSION["access_token"]))
$headers[] = 'Authorization: Bearer ' . $_SESSION["access_token"];
// using this to see my headers
var_dump($headers);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($code != 200) {
//using this to see the error
echo $response;
exit();
fatalError($code, $_SERVER[REQUEST_URI]);
}
return $response;
}
And yes, both the access token and client ID are valid. They work properly on other requests and I've displayed them on this page and confirmed them to be valid.
Any ideas? Am I missing something stupid?
Worked out the fields you need and fiddled with curl a bit and this code is working.
$params = array(
"token" => $_SESSION["access_token"],
"client_id" => OAUTH2_CLIENT_ID,
"client_secret" => OAUTH2_CLIENT_SECRET
);
$ch = curl_init("https://discord.com/api/oauth2/token/revoke");
curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
$headers[] = 'Accept: application/json';
$headers[] = 'Authorization: Bearer ' . $_SESSION["access_token"];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($code != 200) {
#error handling
}
curl_close($ch);

Discord Post Message To Channel Using cURL - PHP

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);
}
?>

Can't get response from MS CRM 2016 API on premise

We are using dynamics crm 2016 in-premise using IFD. I am using below code to get a lead from CRM using API in php
//$url = $crm_url . "XRMServices/2011/OrganizationData.svc/LeadSet($lead)";
$url = $crm_url . "api/data/v8.1/leads($lead)";
$headers = array(
'Method: GET',
'OData-MaxVersion: 4.0',
'OData-Version: 4.0',
'Connection: keep-alive',
'User-Agent: PHP-SOAP-CURL',
'Content-Type: application/json; charset=utf-8',
'Accept: application/json',
'Host: ' . $host);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_NTLM);
//curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
if( $response === false) { echo 'Curl error: ' . curl_error($ch);}
$status = curl_getinfo( $ch, CURLINFO_HTTP_CODE );echo "Status: $status ";
$response=json_decode($response, true);
foreach ($response as $id) {
$guid = $id['LeadId'];
echo 'GUID: ' . $guid. ' ';
}
echo "Lead id: "; var_dump($response['LeadId']);
echo "<pre>";
print_r($response);
echo "</pre>";
curl_close($ch);
I am getting this response:
Status: 401 GUID: T GUID: GUID: Lead id: NULL
Array
(
[Message] => There was an error processing the request.
[StackTrace] =>
[ExceptionType] =>
)
Can someone please help me how to get the correct response.
Alse please let me know if there is another method.
Many thanks..
Seems like the leadid is not filled in your request.
$url = $crm_url . "api/data/v8.1/leads($lead)";
Did you replace that variable by the guid?
exemple:
https://contoso.api.crm.dynamics.com/api/data/v8.1/accounts(1e3983e8-7894-e511-80db-3863bb2e3248)
Also, a good trick to test your queries is to paste them into your browser. I use Chrome. With IE you need to disable the RSS feed.
Sorry, i'm not familliar with php.

CURL x-www-form-urlencoded request - PHP

I'm trying to write simple CURL request from server. Script looks like:
$ch = curl_init();
$url = 'http://URL/';
curl_setopt($ch, CURLOPT_URL, $url);
// ADD URL
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded',
'Accept: application/json',
'Authorization: Basic Y291bn54adsASD78asd5LWFkbWlu'));
// ADD HEADER
curl_setopt($ch, CURLOPT_POST, 1);
// SAY IT'S POST
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if($response === false){
echo 'Curl error: ' . curl_error($ch);
}
else{
$sessionID = json_decode($response, true);
print_r($sessionID);
}
curl_close($ch);
Problem is that I need to add some x-www-form-urlencoded like: grant_type = value, login = value2, password=value3. But I just can't make it work.
Can somebody help please?
The values must be like they would be in an URL (hence the urlencoded), so:
grant_type=value&login=value2&password=value3
If values are not numbers, you will probably need to enclose them between quotes.

Token invalid - Error 401 in YouTube API

I am Working send message using youtuba api. But i got a Error on my file. it shows Invalid Token 401 Error. My file is given below.I'm pretty sure I must be missing something vital but small enough to not notice it.
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.google.com/accounts/ClientLogin");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$data = array('accountType' => 'GOOGLE',
'Email' => 'User Email',
'Passwd' => 'pass',
'source'=>'PHI-cUrl-Example',
'service'=>'lh2');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$kk = curl_getinfo($ch);
$response = curl_exec($ch);
list($auth, $youtubeuser) = explode("\n", $response);
list($authlabel, $authvalue) = array_map("trim", explode("=", $auth));
list($youtubeuserlabel, $youtubeuservalue) = array_map("trim", explode("=", $youtubeuser));
$developer_key = 'AI39si7SavL5-RUoR0kvGjd0h4mx9kH3ii6f39hcAFs3O1Gf15E_3YbGh-vTnL6mLFKmSmNJXOWcNxauP-0Zw41obCDrcGoZVw';
$token = '7zWKm-LZWm4'; //The user's authentication token
$url = "http://gdata.youtube.com/feeds/api/users/worshipuk/inbox" ; //The URL I need to send the POST request to
$title = $_REQUEST['title']; //The title of the caption track
$lang = $_REQUEST['lang']; //The languageof the caption track
$transcript = $_REQUEST['transcript']; //The caption file data
$headers = array(
'Host: gdata.youtube.com',
'Content-Type: application/atom+xml',
'Content-Language: ' . $lang,
'Slug: ' . rawurlencode($title),
'Authorization: GoogleLogin auth='.$authvalue,
'GData-Version: 2',
'X-GData-Key: key=' . $developer_key
);
$xml = '<?xml version="1.0" encoding="UTF-8"?>
<entry xmlns="http://www.w3.org/2005/Atom"
xmlns:yt="http://gdata.youtube.com/schemas/2007">
<id>Qm6znjThL2Y</id>
<summary>sending a message from the api</summary>
</entry>';
// create a new cURL resource
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, $url );
curl_setopt($ch, CURLOPT_HEADER, TRUE );
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, urlencode($xml) );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1 );
$tt = curl_getinfo($ch);
print_r($tt);
$result = curl_exec($ch);
print_r($result);
exit;
// close cURL resource, and free up system resources
curl_close($ch);
?>
any problem in my code? Please guide me. How can I get a result from this code?
Most likely your authentication is wrong, please debug that part first. Either you are not using right scope or that API is not enabled from your console.
On a separate note, I strongly suggest to use Youtube Data API v3 for this. We have updated PHP client library and great samples to get you started.

Categories