I want users to send their videos on my YT channel via my site.
It worked last year but now Youtube requests users to be authenticated on Youtube.
If it even possible now?
Here is the code:
public function getPostParams()
{
$header = array(
"alg" => "RS256",
"typ" => "JWT"
);
$jwt = array(
"iss" => "gulliapp#appspot.gserviceaccount.com",
"scope" => "https://www.googleapis.com/auth/youtube",
"aud" => "https://accounts.google.com/o/oauth2/token",
"exp" => time() + 3600,
"iat" => time()
);
$jwt_string = JWT::encode($jwt, null, 'RS256', "52e47342c1d175e88a94e0076e7a87474013a798", $header);
$headers = array(
"Content-type: application/x-www-form-urlencoded",
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://accounts.google.com/o/oauth2/token");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_TIMEOUT, 3000);
curl_setopt($ch, CURLOPT_POST, true);
$post = "grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion=" . $jwt_string ;
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$res = curl_exec($ch);
$url = curl_getinfo($ch);
$token = json_decode($res);
curl_close($ch);
return $token->access_token;
}
public function saveFile($file, $name, $description, $token)
{
$client = new Google_Client();
$client->setClientId(self::$OAUTH2_CLIENT_ID);
$client->setClientSecret(self::$OAUTH2_CLIENT_SECRET);
$client->setScopes('https://www.googleapis.com/auth/youtube');
$redirect = filter_var('http://gulli.ru/videocontest/add/', FILTER_SANITIZE_URL);
$client->setRedirectUri($redirect);
$client->setAccessToken($token);
$client->setAccessType("offline");
$youtube = new Google_Service_YouTube($client);
if ($client->getAccessToken()) {
try{
$videoPath = $file['tmp_name'];
$snippet = new Google_Service_YouTube_VideoSnippet();
$snippet->setTitle("web2016");
$snippet->setDescription("web2016");
$snippet->setTags(array("tag1", "tag2"));
$snippet->setCategoryId("22");
$status = new Google_Service_YouTube_VideoStatus();
$status->privacyStatus = "private";
// Associate the snippet and status objects with a new video resource.
$video = new Google_Service_YouTube_Video();
$video->setSnippet($snippet);
$video->setStatus($status);
$chunkSizeBytes = 1 * 1024 * 1024;
$client->setDefer(true);
$insertRequest = $youtube->videos->insert("status,snippet", $video);
$media = new Google_Http_MediaFileUpload(
$client,
$insertRequest,
'video/*',
null,
true,
$chunkSizeBytes
);
$media->setFileSize(filesize($videoPath));
$status = false;
$handle = fopen($videoPath, "rb");
while (!$status && !feof($handle)) {
$chunk = fread($handle, $chunkSizeBytes);
$status = $media->nextChunk($chunk);
}
fclose($handle);
$client->setDefer(false);
} catch (Google_Service_Exception $e) {
$htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
} catch (Google_Exception $e) {
$htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
}
$_SESSION['token'] = $client->getAccessToken();
}
return false;
}
Related
I'm trying to add a custom app in Hubspot. I'm using PHP. I have:
A Hubspot app
A working webhook URL
A redirect URL with the following code
$url = 'https://api.hubapi.com/oauth/v1/token';
$code = $_GET['code']; // Getting code parameter from redirect URL
//echo $code;
$fields = array();
$fields['grant_type'] = 'authorization_code'; // Have also tried 'refresh_token' - same result
$fields['client_id'] = '{CLIENT_ID}';
$fields['client_secret'] = '{CLIENT_SECRET}';
$fields['redirect_uri'] = '{REDIRECT_URI}';
$fields['code'] = trim($code);
//$fields['refresh_token'] = trim($code); // Have also tried 'refresh_token' - same result
$request_type = 'POST';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json', $headers));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, POST);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_POST, 1);
if($fields){
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$return = curl_exec($ch);
curl_close($ch);
echo var_dump ($return);
My understanding is that Hubspot will use the 'code' parameter passed to the on the "authorization" URL to validate the authorization. However, I keep getting this error:
string(171) "{"status":"BAD_GRANT_TYPE","message":"missing or unknown grant type","correlationId":"f0508752-24bc-40e4-b0bc-51e358459653","requestId":"96044613d4e4a5aab7356fab04001e5c"}"
I had the same error response and it seemed that this is an encoding issue.
I debugged with Postman and found out that the following code works:
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.hubapi.com/oauth/v1/token",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "grant_type=authorization_code&code=string&redirect_uri=string&client_id=string&client_secret=string",
CURLOPT_HTTPHEADER => array(
"content-type: application/x-www-form-urlencoded",
"Cookie: __cfduid=someidfrompostman"
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
I was using the following code to get gmail contacts and it suddenly stopped working. The same code works with another domain. The credentials are being correctly retrieved from a file. The domain has been verified for google.
Any help would be appreciated.
//setup new google client
$client = new Google_Client();
$client -> setClientid($google_client_id);
$client -> setClientSecret($google_client_secret);
$client -> setRedirectUri($google_redirect_uri);
$client -> setAccessType('online');
$client -> setScopes('https://www.google.com/m8/feeds');
$googleImportUrl = $client -> createAuthUrl();
//echo 'google import url: '.$googleImportUrl.'<br>';
function curl($url, $post = "") {
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5);
if ($post != "") {
curl_setopt($curl, CURLOPT_POST, 5);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
}
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($curl, CURLOPT_AUTOREFERER, TRUE);
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
$contents = curl_exec($curl);
curl_close($curl);
if($contents === FALSE) {
die(curl_error($ch));
}
return $contents;
}
if (isset($_GET['code'])) {
$auth_code = $_GET["code"];
$_SESSION['google_code'] = $auth_code;
header('Location: ' . $google_redirect_uri);
}
if(isset($_SESSION['google_code'])) {
$auth_code = $_SESSION['google_code'];
$max_results = 10000;
$fields=array(
'code'=> urlencode($auth_code),
'client_id'=> urlencode($google_client_id),
'client_secret'=> urlencode($google_client_secret),
'redirect_uri'=> urlencode($google_redirect_uri),
'grant_type'=> urlencode('authorization_code')
);
$post = '';
foreach($fields as $key=>$value)
{
$post .= $key.'='.$value.'&';
}
$post = rtrim($post,'&');
$result = curl('https://accounts.google.com/o/oauth2/token',$post);
$response = json_decode($result);
$accesstoken = $response->access_token;
$url = 'https://www.google.com/m8/feeds/contacts/default/full?max-results='.$max_results.'&alt=json&v=3.0&oauth_token='.$accesstoken;
$xmlresponse = curl($url);
$contacts = json_decode($xmlresponse,true);
unset($_SESSION['google_code']);
}
I have an app set for push notification. The Android code works fine and I receive a push notification. For Apple, the phone just vibrates and makes sound for push notifications, but I don't get a badge or anything else.
Can someone please show me where I am going wrong?
<?php
// function to send Android push notification
function send_message($deviceToken, $message){
$messageArr['message'] = "";
if($message=="")
{
$messageArr['message'] = "Test data";
}
else
{
$messageArr['message'] = $message ;
}
$registatoin_ids = $deviceToken;
return mer_send_notification($registatoin_ids, $messageArr);
}
function mer_curlPost($url, $headers, $fields) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $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('Curl failed: ' . curl_error($ch));
}
curl_close($ch);
return $result;
}
function mer_send_notification($registatoin_ids, $message) {
$url = 'https://android.googleapis.com/gcm/send';
$apiKey = 'mykeyishere';
echo 'Test if 4\n';
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $message,
);
$headers = array(
'Authorization: key=' . $apiKey,
'Content-Type: application/json'
);
$result = mer_curlPost($url, $headers, $fields);
return $result;
}
function sendNotification($dataArr, $device_token_array) {
$apns_url = NULL;
$apns_cert = NULL;
$apns_port = 2195;
$development = false;
if ($development) {
$apns_url = 'gateway.sandbox.push.apple.com';
$apns_cert = 'devcert.pem';
} else {
$apns_url = 'gateway.push.apple.com';
$apns_cert = 'prodcert.pem';
}
$stream_context = stream_context_create();
stream_context_set_option($stream_context, 'ssl', 'local_cert', $apns_cert);
stream_context_set_option($stream_context, 'ssl', 'passphrase', 'mypassphrase');
$payload = array();
$payload['aps'] = $dataArr;
$payloadJson = json_encode($payload);
$apns = #stream_socket_client('ssl://' . $apns_url . ':' . $apns_port, $error, $error_string, 2, STREAM_CLIENT_CONNECT, $stream_context);
foreach ($device_token_array as $key => $device_token) {
$apns_message = chr(0) . chr(0) . chr(32) . pack('H*', str_replace(' ', '', $device_token)) . chr(0) . chr(strlen($payloadJson)) . $payloadJson;
$xxx[] = #fwrite($apns, $apns_message);
}
$yyy = #socket_close($apns);
$zzz = #fclose($apns);
$arr = array();
$arr[] = $stream_context;
$arr[] = $apns;
$arr[] = $xxx;
$arr[] = $yyy;
$arr[] = $zzz;
return $arr;
}
The notification format for iOS is different than for Android. See here for iOS format: https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/ApplePushService.html#//apple_ref/doc/uid/TP40008194-CH100-SW1
Im using following ruby code to upload files to office 365
uri = URI.parse("#{site_url}/_api/v1.0/me/files/#{folder}/children/#{temp_file.original_filename}/content")
https = Net::HTTP.new(uri.host,uri.port)
https.use_ssl = true
req = Net::HTTP::Put.new(uri.path, initheader = {
'Content-Type' =>'application/octet-stream',
'Authorization' => 'Bearer ' + #current_user.o_auth_token,
'resource' => 'site_url'
})
req.set_form_data(
'file' => temp_file.read,
'Content-Type' => 'application/octet-stream'
)
JSON.parse(https.request(req).body)
The file uploaded to office 365 is corrupt. What's the issue in the code?
The following code in PHP works fine. Please note these are functions within a class and also requires creating a SharepointException class.
public function upload_file($folder_id, $filepath, $filename) {
//remove illegal characters form filename
try {
$filename = $this->clean_filename($filename);
} catch (SharepointException $e) {
throw new SharepointException($e->getMessage());
}
//build uri
if (is_null($folder_id)) {
$uri = $this->base_url . 'files/root/children/'.rawurlencode($filename).'/content?nameConflict=abort';
} else {
$uri = $this->base_url . 'files/'.$folder_id.'/children/'.rawurlencode($filename).'/content?nameConflict=abort';
}
$response = $this->upload($uri, $filepath);
if (array_key_exists('error', $response)) {
throw new SharepointException($response['error']);
}
return $response;
}
private function upload($uri, $filepath) {
$pointer = fopen($filepath, 'r+');
$stat = fstat($pointer);
$pointersize = $stat['size'];
$ch = curl_init($uri);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_PUT, true);
curl_setopt($ch, CURLOPT_INFILE, $pointer);
curl_setopt($ch, CURLOPT_INFILESIZE, (int)$pointersize);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, TRUE);
//Expect:
//HTTP response code 100 workaround
//see http://www.php.net/manual/en/function.curl-setopt.php#82418
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Expect:',
'Content-Type: application/json',
'Authorization: Bearer ' . $this->access_token,
));
$response = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$accepted_codes = array(
'200',
'201',
);
if (!in_array($httpcode, $accepted_codes)) {
//generic error
$error = 'HTTP status code not expected - got '.$httpcode;
//more descriptive error
if ($httpcode == '400') {
$data = json_decode($response, true);
if (isset($data['error']['message'])) {
$error = $data['error']['message'];
}
}
return array('error' => $error);
}
return json_decode($response, true);
}
private function clean_filename($filename) {
$filename = preg_replace('/[*><|}{&#%~:"?\/\\\\]/', '', $filename);
if (strpos('.', $filename) === 0) {
$filename = substr($filename, 1);
}
if (empty($filename)) {
throw new SharepointException('File is empty after removing illegal characters.');
}
return $filename;
}
I have an issue with a website i'm hosting on a shared server where an 'open_basedir' is set... So therefore the credit system throws an error and won't charge the buyers credit card.
Error Message
Warning: curl_setopt() [function.curl-setopt]: CURLOPT_FOLLOWLOCATION cannot be activated when in safe_mode or an open_basedir is set in
Code
function http_post($method, $server, $port, $url, $vars) {
$postdata = "";
foreach($vars as $key => $value) {
$postdata .= urlencode($key) . "=" . urlencode($value) . "&";
}
$postdata = substr($postdata,0,-1);
$content_length = strlen($postdata);
$headers = "POST $url HTTP/1.1\r\n".
"Accept: */*\r\n".
"Accept-Language: en-nz\r\n".
"Content-Type: application/x-www-form-urlencoded\r\n".
"Host: $server\r\n".
"Connection: Keep-Alive\r\n".
"Cache-Control: no-cache\r\n".
"Content-Length: $content_length\r\n\r\n";
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $method . '://' . $server .":". $port . $url);
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_POST, 1);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $postdata);
$ret = curl_exec($ch);
curl_close($ch);
return $ret;
}
Is there anyway around this without having access to the root PHP.ini and having to switch hosts? Thank you.
There is no way to override the value of open_basedir in php.ini as this would somewhat defeat the purpose. An alternative is to write your own function perform the same functionality as CURLOPT_FOLLOWLOCATION would with open_basedir not set. I have used a variation of this code found from http://php.benscom.com/manual/en/function.curl-setopt.php#102121 which loops your request and does a regex match for Location: in the response headers, following as needed with a new request:
function curl_exec_follow(/*resource*/ $ch, /*int*/ &$maxredirect = null) {
$mr = $maxredirect === null ? 5 : intval($maxredirect);
if (ini_get('open_basedir') == '' && ini_get('safe_mode' == 'Off')) {
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, $mr > 0);
curl_setopt($ch, CURLOPT_MAXREDIRS, $mr);
} else {
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
if ($mr > 0) {
$newurl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
$rch = curl_copy_handle($ch);
curl_setopt($rch, CURLOPT_HEADER, true);
curl_setopt($rch, CURLOPT_NOBODY, true);
curl_setopt($rch, CURLOPT_FORBID_REUSE, false);
curl_setopt($rch, CURLOPT_RETURNTRANSFER, true);
do {
curl_setopt($rch, CURLOPT_URL, $newurl);
$header = curl_exec($rch);
if (curl_errno($rch)) {
$code = 0;
} else {
$code = curl_getinfo($rch, CURLINFO_HTTP_CODE);
if ($code == 301 || $code == 302) {
preg_match('/Location:(.*?)\n/', $header, $matches);
$newurl = trim(array_pop($matches));
} else {
$code = 0;
}
}
} while ($code && --$mr);
curl_close($rch);
if (!$mr) {
if ($maxredirect === null) {
trigger_error('Too many redirects. When following redirects, libcurl hit the maximum amount.', E_USER_WARNING);
} else {
$maxredirect = 0;
}
return false;
}
curl_setopt($ch, CURLOPT_URL, $newurl);
}
}
return curl_exec($ch);
}