How to send message to youtube user using youtube API? - php

I am developing a script to send a message to a YouTube user. Actually, I have got the YouTube data feeds with the information - YouTube video id, author name, details etc.., for that corresponding author. I have to send a message using the YouTube api. Is this possible?
I have already written Oauth login and YouTube API feed to get video and user information for that corresponding video. I referred to this documentation in the YouTube API - https://developers.google.com/youtube/2.0/developers_guide_protocol_messages#Sending_a_message for send message, but there are no options for this. There are only options to send message as comments instead of new mail to the inbox of the corresponding video author.
So please update me if you know about that. I have pasted my script below.
$developer_key='###########################';
$client_id= '#################';
$client_secret='#################';
// error checking; user might have denied access
if (isset($_GET['error'])) {
if ($_GET['error'] == 'access_denied') {
echo('You have denied access. Click here to retry…');
} else {
echo("An error has occurred: ". $_GET['error']);
}
exit;
}
// Step 1: redirect to google account login if necessary
if(!isset($_GET['code']) || $_GET['code'] === '') {
Header('Location: https://accounts.google.com/o/oauth2/auth?client_id='. $client_id .
'&redirect_uri=http%3A%2F%2Flocalhost%2Ftest%2Foauth_1.php' .
'&scope=https://gdata.youtube.com&response_type=code&access_type=offline',
true, 307);
exit;
}
$authorization_code= $_GET['code'];
// Step 2: use authorization code to get access token
$url = "https://accounts.google.com/o/oauth2/token";
$message_post= 'code='. $authorization_code .
'&client_id='. $client_id .
'&client_secret='. $client_secret .
'&redirect_uri=http://localhost/test/oauth_1.php' .
'&grant_type=authorization_code';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $message_post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
if ($cur_error= curl_error($ch)) {
echo($cur_error);
curl_close($ch);
exit;
}
curl_close($ch);
$jsonArray= json_decode($result, true);
if ($jsonArray === null) {
echo("Could not decode JSON.");
exit;
}
if (isset($jsonArray['error'])) {
echo("An error has occurred: ". $jsonArray['error']);
exit;
}
if (!isset($jsonArray['access_token'])) {
echo("Access token not found.");
exit;
}
//The user's authentication token
$access_token= $jsonArray['access_token'];
$title ='krishna'; //The title of the caption track
$lang = 'en'; //The languageof the caption track
//$transcript = $_REQUEST['transcript']; //The caption file data
$ur='https://gdata.youtube.com/feeds/api/users/recepient_username/inbox';
$headers = array(
'Host: gdata.youtube.com',
'Content-Type: application/atom+xml utf-8',
'Content-Language: ' . $lang,
'Slug: ' . rawurlencode($title),
'Authorization: AuthSub token=' . $access_token,
'GData-Version: 2',
'X-GData-Key: key=' . $developer_key
);
$xml = '&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>cSVSeHFKBjU</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_SSL_VERIFYHOST, 0);
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);
// close cURL resource, and free up system resources
curl_close($ch);
echo "DONE! Token:" . $access_token . "<br />\n";
var_dump($result);
SO please check and update me if there any options to send mail to the video user instead of comments.

The YouTube v2.0 API does support sending new messages to a user's inbox, but the message must contain both a video and a comment about that video. You cannot send a text-only message.
Documentation, which includes a use case explaining how YouTube's messaging support is intended to be used, can be found here.

Related

Can i store static API Key in php file safely

i want to use FCM in my android application , and i was wondering what is the best practice to store a static API such as Server Key API of FCM .
And after a lot o reading i found that even using ProGard doesn't save the API securely, so the conclusion is to never store keys in the app source code .
My solution is to save the key in a .php file like this, so that every time a device send a notification it sends data ( Notification title , message .. ) to my server that contain the server key and redirect the request to https://fcm.googleapis.com/fcm/send
My php file :
<?php
require_once __DIR__ . '/notification.php';
$notification = new Notification();
$title = "Notification Title";
$message = "Notification Message";
$notification->setTitle($title);
$notification->setMessage($message);
$firebase_api = "API_STATIC_SERVER_CODE_THAT_I_NEED_TO_HIDE";
$requestData = $notification->getNotificatin();
$fields = array(
'to' => '/topics/Test_Topic',
'data' => $requestData,
);
$url = 'https://fcm.googleapis.com/fcm/send';
$headers = array(
'Authorization: key=' . $firebase_api,
'Content-Type: application/json'
);
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Disabling SSL Certificate support temporarily
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
// Execute post
$result = curl_exec($ch);
if($result === FALSE){
die('Curl failed: ' . curl_error($ch));
}
// Close connection
curl_close($ch);
echo '<h2>Result</h2><hr/><h3>Request </h3><p><pre>';
echo json_encode($fields,JSON_PRETTY_PRINT);
echo '</pre></p><h3>Response </h3><p><pre>';
echo $result;
echo '</pre></p>';
?>
But, is that safe ? Could hackers some how download my php content ( without hacking my server ) , or the fact that i am using HTTPS connections keeps my data safe .
And what else can i do if it's not safe enough
Thank you

What is the alternative solution of deprecated google plus api?

Google announced that all google plus api were deprecated on 7th march and I'm using google plus api with oauth2 so I'm worried about is my https://www.googleapis.com/plus/v1/people/me is also deprecated if yes than what is the alternative solution of that..
//index.php
<?php
include('constant.php');
include('google-login-api.php');
// include constant.php
// include google-api library
if(isset($_GET['code'])) {
$gapi = new GoogleLoginApi();
// Get the access token
$data = $gapi->GetAccessToken(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_REDIRECT_URL, GOOGLE_CLIENT_SECRET, $_GET['code']);
if(is_array($data) && count($data)>0)
{
// Get user information
$user_info = $gapi->GetUserProfileInfo($data['access_token']);
echo "<pre>";
print_r($user_info);
}
}else{
//html code
?>
<a class="sign-in sign-google" href="<?php echo GOOGLE_API_URL; ?>"><i class="fa fa-google-plus"aria-hidden="true"></i>Sign In with Google</a>
<?php
}
?>
//google-login-api.php
<?php
class GoogleLoginApi
{
public function GetAccessToken($client_id, $redirect_uri, $client_secret, $code) {
$url = 'https://accounts.google.com/o/oauth2/token';
$curlPost = 'client_id=' . $client_id . '&redirect_uri=' . $redirect_uri . '&client_secret=' . $client_secret . '&code='. $code . '&grant_type=authorization_code';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
$data = json_decode(curl_exec($ch), true);
$http_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);
if($http_code != 200)
throw new Exception('Error : Failed to receieve access token');
return $data;
}
public function GetUserProfileInfo($access_token) {
$url = 'https://www.googleapis.com/plus/v1/people/me';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '. $access_token));
$data = json_decode(curl_exec($ch), true);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if($http_code != 200)
throw new Exception('Error : Failed to get user information');
return $data;
}
}
?>
here is my code which i have using and its run perfectly ...but the question is that Is still running after 7th march
A rough replacement for the Google Plus API (or at least the plus.people portion of the API) is the Google People API. It fundamentally does the same thing (returns profile information for users), although there are some changes in how the request is done and how the response is formatted. The biggest difference is that you need to request exactly what fields you want to receive.
In order to get the information for the user, you'd set $url with something more like
$fields = 'names,emailAddresses';
$url = 'https://people.googleapis.com//v1/people/me?personFields='+$fields;
You can see the reference for people.get for the possible values for the personFields parameter and the OAuth scopes that are valid for access.
Change url from,
$url = 'https://www.googleapis.com/plus/v1/people/me';
to,
$url = 'https://www.googleapis.com/oauth2/v3/userinfo';
I had same issue, solved here

How can I get an Authentication Token for Microsoft Translator API?

I want to get an Authentication Token for the Microsoft Translator API. This is my code:
<?php
//1. initialize cURL
$ch = curl_init();
//2. set options
//Set to POST request
curl_setopt($ch, CURLOPT_POST,1);
// URL to send the request to
curl_setopt($ch, CURLOPT_URL, 'https://api.cognitive.microsoft.com/sts/v1.0/issueToken');
//return instead of outputting directly
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//whether to include header in the output. here set to false
curl_setopt($ch, CURLOPT_HEADER, 0);
//pass my subscription key
curl_setopt($ch, CURLOPT_POSTFIELDS,array(Subscription-Key => '<my-key>'));
//CURLOPT_SSL_VERIFYPEER- Set to false to stop verifying certificate
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//3. Execute the request and fetch the response. check for errors
$output = curl_exec($ch);
if ($output === FALSE) {
echo "cURL Error" . curl_error($ch);
}
//4. close and free up the curl handle
curl_close($ch);
//5. display raw output
print_r($output);
?>
it gives me the following error:
{ "statusCode": 401, "message": "Access denied due to missing subscription key. Make sure to include subscription key when making requests to an API." }
which could mean that the key is invalid according to the website below, but I ensured the key is valid on the same website.
http://docs.microsofttranslator.com/oauth-token.html
I did find some examples online on how to get the Authenticationtoken, but they are outdated.
How can I get the AuthenticationToken/achieve that microsoft recognises my key?
You're passing the subscription-key wrong -
The subscription key should passed in the header (Ocp-Apim-Subscription-Key) or as a querystring parameter in the URL ?Subscription-Key=
And you should use Key1 or Key2 generated by the Azure cognitive service dashboard.
FYI - M$ has made a token generator available for testing purposes, this should give you a clue which keys are used for which purpose:
http://docs.microsofttranslator.com/oauth-token.html
Here's a working PHP script which translates a string from EN to FR (it's based on an outdated WP plugin called Wp-Slug-Translate by BoLiQuan which I've modified for this purpose):
<?php
define("CLIENTID",'<client-name>'); // client name/id
define("CLIENTSECRET",'<client-key>'); // Put key1 or key 2 here
define("SOURCE","en");
define("TARGET","fr");
class WstHttpRequest
{
function curlRequest($url, $header = array(), $postData = ''){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
if(!empty($header)){
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
if(!empty($postData)){
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, is_array($postData) ? http_build_query($postData) : $postData);
}
$curlResponse = curl_exec($ch);
curl_close($ch);
return $curlResponse;
}
}
class WstMicrosoftTranslator extends WstHttpRequest
{
private $_clientID = CLIENTID;
private $_clientSecret = CLIENTSECRET;
private $_fromLanguage = SOURCE;
private $_toLanguage = TARGET;
private $_grantType = "client_credentials";
private $_scopeUrl = "http://api.microsofttranslator.com";
private $_authUrl = "https://api.cognitive.microsoft.com/sts/v1.0/issueToken";
// added subscription-key
private function _getTokens(){
try{
$header = array('Ocp-Apim-Subscription-Key: '.$this->_clientSecret);
$postData = array(
'grant_type' => $this->_grantType,
'scope' => $this->_scopeUrl,
'client_id' => $this->_clientID,
'client_secret' => $this->_clientSecret
);
$response = $this->curlRequest($this->_authUrl, $header, $postData);
if (!empty($response))
return $response;
}
catch(Exception $e){
echo "Exception-" . $e->getMessage();
}
}
function translate($inputStr){
$params = "text=" . rawurlencode($inputStr) . "&from=" . $this->_fromLanguage . "&to=" . $this->_toLanguage;
$translateUrl = "http://api.microsofttranslator.com/v2/Http.svc/Translate?$params";
$accessToken = $this->_getTokens();
$authHeader = "Authorization: Bearer " . $accessToken;
$header = array($authHeader, "Content-Type: text/xml");
$curlResponse = $this->curlRequest($translateUrl, $header);
$xmlObj = simplexml_load_string($curlResponse);
$translatedStr = '';
foreach((array)$xmlObj[0] as $val){
$translatedStr = $val;
}
return $translatedStr;
}
}
function bing_translator($string) {
$wst_microsoft= new WstMicrosoftTranslator();
return $wst_microsoft->translate($string);
}
echo bing_translator("How about translating this?");
?>
Add your key also in the URL.
curl_setopt($ch, CURLOPT_URL, 'https://api.cognitive.microsoft.com/sts/v1.0/issueToken?Subscription-Key={your key}');
But leave it also in the CURLOPT_POSTFIELDS.

Getting Unauthorized Error 401 in Firebase Cloud Messaging in cURL command

I'm going to send Firebase Cloud Messaging and the problem that I'm facing is I get an Unauthorized Error 401.
I got the security key from my Firebase website then set it. The device token is already in database and I read from database with no problem.
This is my code so far:
<?php
function send_notification($tokens, $message)
{
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array('registration_ids' => $tokens, 'data' => $message);
$headers = array('Authorization: key=' . "My Firebase key", 'Content-Type: application/json');
echo "work well before init curl";
$ch = curl_init();
echo "init well";
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_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
echo "init finishe well";
$result = curl_exec($ch);
echo "Execute to get result";
if ($result === false) {
die('Curl failed: ' . curl_error($ch));
}
curl_close($ch);
echo "function finished well";
return $result;
}
$conn = mysqli_connect("localhost", "root", "mysql_password", "FCM") or die("Error connecting");
$sql = " Select Token From users";
$result = mysqli_query($conn, $sql);
$tokens = array();
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$tokens[] = $row["Token"];
}
}
mysqli_close($conn);
$message = array("message" => " FCM PUSH NOTIFICATION TEST MESSAGE");
$message_status = send_notification($tokens, $message);
echo $message_status;
?>
When using FCM, you must use the Server Key seen in the Cloud Messaging tab of your Firebase Console as the value for Authorization in your requests.
Using the documentation at https://developers.google.com/instance-id/reference/server, I wanted to use https://iid.googleapis.com/iid/info/IID_TOKEN to get information about app instances.
In the code of my app, I used this to get the IDD_TOKEN:
// Get token using example from https://github.com/firebase/quickstart-android/blob/master/messaging/app/src/main/java/com/google/firebase/quickstart/fcm/java/MainActivity.java.
// [START retrieve_current_token]
FirebaseInstanceId.getInstance().getInstanceId()
.addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
#Override
public void onComplete(#NonNull Task<InstanceIdResult> task) {
if (!task.isSuccessful()) {
Log.w(TAG, "getInstanceId failed", task.getException());
return;
}
// Get new Instance ID token
String token = task.getResult().getToken();
System.out.println("task.getResult().getToken() = "+token);
// Log and toast
String msg = getString(R.string.msg_token_fmt, token);
Log.d(TAG, msg);
Toast.makeText(FirstActivity.this, msg, Toast.LENGTH_SHORT).show();
}
});
// [END retrieve_current_token]
Then in the Android Studio logs, I found the token (I am changing the value of the token because I do not want to post the real one here):
I/System.out: task.getResult().getToken() = bepGr4F2b0Q:APB91cEAKsN1bGjMm5xsobxBHxuYZLfioTPMEIN90njdiK5C2MnOYF5NcOy6ot6XFanMTBIoKRGcyev5RJuydGWt1XHwsniNZ6h3Pjvn9Fqth-Mqgj_2-YN9pv_nMAugG8blc5boeDyH
This means that the IDD_TOKEN was bepGr4F2b0Q:APB91cEAKsN1bGjMm5xsobxBHxuYZLfioTPMEIN90njdiK5C2MnOYF5NcOy6ot6XFanMTBIoKRGcyev5RJuydGWt1XHwsniNZ6h3Pjvn9Fqth-Mqgj_2-YN9pv_nMAugG8blc5boeDyH. So in my PHP code I used this:
$curlUrl = "https://iid.googleapis.com/iid/info/bepGr4F2b0Q:APB91cEAKsN1bGjMm5xsobxBHxuYZLfioTPMEIN90njdiK5C2MnOYF5NcOy6ot6XFanMTBIoKRGcyev5RJuydGWt1XHwsniNZ6h3Pjvn9Fqth-Mqgj_2-YN9pv_nMAugG8blc5boeDyH?details=true";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $curlUrl);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
//turning off the server and peer verification(TrustManager Concept).
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization:key=[My server key]'));
//getting response from server
$response = curl_exec($ch);
print_r($response);
Where is the [My server key] found? You can find it at https://console.firebase.google.com/. Go to the Cloud Messaging tab, and in the Project credentials section, you will find the Server key:
The result was this:
{"applicationVersion":"50","connectDate":"2019-05-09","attestStatus":"NOT_ROOTED","application":"[My package name]","scope":"*","authorizedEntity":"[My Firebase Sender ID]","rel":{"topics":{"Toronto":{"addDate":"2019-05-09"}}},"appSigner":"[My appSigner]","platform":"ANDROID"}
That is correct. I can tell that those values correspond to my IID_TOKEN for the device that I connected, I can recognize that and everything is correct. I can confirm that I subscribed my device to that topic and everything works correctly! I was able to use https://iid.googleapis.com/iid/info/IID_TOKEN to get information about my app instances corresponding to an Android device that I connected using Firebase.

HP ALM REST API login using PHP CURL

I'm new to REST and I'm trying to develop a web app that will connect with JIRA from one sid (already covered) and with HP's ALM from the other side.
what I'm attempting to accomplish right now is basic authentication to ALM with PHP but can't seem to progress.
here is my code:
$handle=curl_init('http://192.168.1.7:8081');
$headers = array(
'Accept: application/xml',
'Content-Type: application/xml',
'Authorization: Basic YWRtaW46MTIzNA==',
);
$username='admin';
$password='1234';
$url = 'http://192.168.1.7:8081/qcbin/authentication-point/login.jsp';
curl_setopt_array(
$handle,
array(
CURLOPT_URL=>'http://192.168.1.7:8081/qcbin/rest/domains/default/projects/Ticomsoft/defects?login-form-required=y',
//CURLOPT_COOKIEFILE=>$ckfile,
CURLOPT_POST=>true,
//CURLOPT_HTTPGET =>true,
CURLOPT_COOKIEJAR=>$ckfile,
CURLOPT_VERBOSE=>1,
//CURLOPT_POSTFIELDS=>,
//CURLOPT_GETFIELDS=>'j_username=admin&j_password=1234&redirect-url=http://192.168.1.7:8081/myUiResource.jsps',
CURLOPT_SSL_VERIFYHOST=> 0,
CURLOPT_SSL_VERIFYPEER=> 0,
CURLOPT_RETURNTRANSFER=>true,
CURLOPT_FOLLOWLOCATION=>true,
CURLOPT_HEADER=>false,
CURLOPT_HTTPHEADER=> $headers,
CURLOPT_AUTOREFERER=>true
//CURLOPT_COOKIE=>
//CURLOPT_USERPWD=>"admin:yahala"
//CURLOPT_CUSTOMREQUEST=>"POST"
)
);
$result=curl_exec($handle);
$ch_error = curl_error($handle);
$response = curl_getinfo($handle);
print_r($response);
if ($ch_error) {
echo "cURL Error: $ch_error";
} else {
//var_dump(json_decode($result, true));
echo $result;
}
curl_close($handle);
?>
as you can see there is a lot of garbage as my trial and error progressed.
Here we go. I followed the QC Rest API documentation to study the order that QC expects requests to be made. I've tested it against ALM11. I'm new to cURL as well, but this should get you in and working......
<?php
//create a new cURL resource
$qc = curl_init();
//create a cookie file
$ckfile = tempnam ("/tmp", "CURLCOOKIE");
//set URL and other appropriate options
curl_setopt($qc, CURLOPT_URL, "http://qualityCenter:8080/qcbin/rest/is-authenticated");
curl_setopt($qc, CURLOPT_HEADER, 0);
curl_setopt($qc, CURLOPT_HTTPGET, 1);
curl_setopt($qc, CURLOPT_RETURNTRANSFER, 1);
//grab the URL and pass it to the browser
$result = curl_exec($qc);
$response = curl_getinfo($qc);
//401 Not authenticated (as expected)
//We need to pass the Authorization: Basic headers to authenticate url with the
//Correct credentials.
//Store the returned cookfile into $ckfile
//Then use the cookie when we need it......
if($response[http_code] == '401')
{
$url = "http://qualityCenter:8080/qcbin/authentication-point/authenticate";
$credentials = "qc_username:qc_password";
$headers = array("GET /HTTP/1.1","Authorization: Basic ". base64_encode($credentials));
curl_setopt($qc, CURLOPT_URL, $url);
curl_setopt($qc, CURLOPT_HTTPGET,1); //Not sure we need these again as set above?
curl_setopt($qc, CURLOPT_HTTPHEADER, $headers);
//Set the cookie
curl_setopt($qc, CURLOPT_COOKIEJAR, $ckfile);
curl_setopt($qc, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($qc);
$response = curl_getinfo($qc);
//The response will be 200
if($response[http_code] == '200')
{
//Use the cookie for subsequent calls...
curl_setopt($qc, CURLOPT_COOKIEFILE, $ckfile);
curl_setopt($qc, CURLOPT_RETURNTRANSFER, true);
curl_setopt($qc, CURLOPT_URL, "http://qualityCenter:8080/qcbin/rest/domains/Your_Domain/projects/Your_Project/defects");
//In this example we are retrieving the xml so...
$xml = simplexml_load_string(curl_exec($qc));
print_r($xml);
//Call Logout
logout($qc,"http://qualityCenter:8080/qcbin/authentication-point/logout");
}
else
{
echo "Authentication failed";
}
}
else
{
echo "Not sure what happened?!";
}
//Close cURL resource, and free up system resources
curl_close($qc);
function logout($qc, $url)
{
curl_setopt($qc, CURLOPT_URL, $url);
curl_setopt($qc, CURLOPT_HEADER, 0);
curl_setopt($qc, CURLOPT_HTTPGET,1);
curl_setopt($qc, CURLOPT_RETURNTRANSFER, 1);
//grab the URL and pass it to the browser
$result = curl_exec($qc);
}
?>
Let me know if it worked!
Thanks,
Rich
one of the important things to keep in mind is after authenticating you must do the following
POST /qcbin/rest/site-session
with cookies LWSSO
this will return QCSession and XSRF-TOKEN which are needed to perform any operations
Here is my solution in Perl for this problem: The authentication step is performed first, setting the cookie for the next libcurl request which then can be performed with no problems. This is a version for background jobs. For a dialog application, the credentials could be passed through from the user's input instead. Also, I had to do this with https instead of http. The Perl program also shows how to instruct curl for https (there is a very good how-to on http://unitstep.net/blog/2009/05/05/using-curl-in-php-to-access-https-ssltls-protected-sites/ ).
#!/usr/bin/perl
# This script accesses, as a proxy, the REST API of the HP quality center
# Running it without query parameter, the complete list of defects is returned
# A query parameter, e.g. 'query={id[2283]}' will be passed as is to the HP QC API
# We are using the libcurl wrapper WWW::Curl::Easy
# The access is https, so a certificate has to be passed to libcurl
# The main point for using curl, however, is the authentication procedure:
# HP requires a preparative call to a special authentication service
# The authentication ticket will then be passed back as a cookie
# Only with this ticket, the real GET request on the defects can be performed
use WWW::Curl::Easy;
use strict;
use warnings;
use constant {
URL_QC_DEFECTS => "https://[QC DOMAIN]/qcbin/rest/domains/[DOMAIN]/projects/[PROJECT]/defects/",
URL_QC_AUTH => "https://[QC DOMAIN]/qcbin/authentication-point/authenticate",
PATH_CERT => "[PATH TO CREDENTIALS]" # contains certificate and credentials, see below
};
doRequest( URL_QC_DEFECTS . "?" . $ENV{QUERY_STRING} );
return 0;
sub doRequest {
my ($url,$cookies,$response) = (shift,"","");
eval {
my $curl = get_curl_instance(\$cookies,\$response);
authenticate( $curl );
get( $curl, $url );
if ($response =~ /.*?(<\?xml\b.*)/s) {
print "Content-Type:text/xml\n\n";
print $1;
}
else {
die "The response from HP QC is not in XML format";
}
};
if ($#) {
print "Content-Type:text/plain\n\n$#";
}
}
sub get_curl_instance {
my ($cookie,$response) = #_;
my $curl = WWW::Curl::Easy->new( );
open( my $cookiefile, ">", $cookie) or die "$!";
$curl->setopt( CURLOPT_COOKIEFILE, $cookiefile );
open( my $responsefile, ">", $response) or die "$!";
$curl->setopt( CURLOPT_WRITEDATA, $responsefile );
$curl->setopt( CURLOPT_SSL_VERIFYPEER, 1);
$curl->setopt( CURLOPT_SSL_VERIFYHOST, 2);
$curl->setopt( CURLOPT_CAINFO, cert() );
$curl->setopt( CURLOPT_FOLLOWLOCATION, 1 );
return $curl;
}
sub authenticate {
my $curl = shift;
my ($rc,$status);
$curl->setopt( CURLOPT_URL, URL_QC_AUTH );
$curl->setopt( CURLOPT_USERPWD, cred( ) );
if (($rc = $curl->perform( )) != 0) {
die "Error Code $rc in curl->perform( ) on URL " . URL_QC_AUTH;
}
if (($status=$curl->getinfo(CURLINFO_HTTP_CODE))!="200") {
die "HTTP-Statuscode $status from authentication call";
}
}
sub get {
my ($curl,$url) = #_;
my ($rc,$status);
$curl->setopt( CURLOPT_URL, $url );
$curl->setopt( CURLOPT_HEADER, { Accept => "text/xml" } );
if (($rc = $curl->perform( )) != 0) {
die "Error Code $rc from defects request";
}
if (($status=$curl->getinfo(CURLINFO_HTTP_CODE))!="200") {
die "HTTP Statuscode $status from defects request";
}
}
sub cred {
open CRED, PATH_CERT . '/.cred_qc' or die "Can't open credentials file: $!";
chomp( my $cred = <CRED>);
close CRED;
return $cred;
}
sub cert {
return PATH_CERT . '/qc.migros.net.crt';
}
As an alternative to Sohaib's answer concerning the need to POST to /qcbin/rest/site-session after authenticating, you can do both in one step by POSTing to /qcbin/api/authentication/sign-in , as per the below:
"There are four cookies that come back, and in ALM 12.53 the authentication point has changed ( but the documentation has not so it sends you to the wrong place ! )
So, send a POST request with BASIC authentication, base64 encoded username / password to /qcbin/api/authentication/sign-in and you will get back
LWSSO_COOKIE_KEY
QCSESSION
ALM_USER
XSRF_TOKEN
include these with all your subsequent GETS and PUTS and you should be OK."
(This answer is taken from https://community.microfocus.com/t5/ALM-QC-User-Discussions/Authentication-fails-when-trying-to-pull-data-from-ALM-server/td-p/940921, and worked for me in a similar context).

Categories