Microsoft Graph Api displays insufficient privileges to complete the operation - azure-active-directory

I have an admin account that am trying to update its data using microsoft Graph API via php Curl but its showing error:
{
"error": {
"code": "Authorization_RequestDenied",
"message": "Insufficient privileges to complete the operation.",
"innerError": {
"request-id": "110ac3f6-16d1-41a2-b2dc-add954514666",
"date": "2017-12-04T00:12:02"
}
}
}
below is the code for updating
<?php
session_start();
echo $acc= $_SESSION['access_token'];
$data_string = array("jobTitle" => 'Fibre ngineer', "officeLocation" => "SAMOLA");
$data = json_encode($data_string);
//$data = $data_string;
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://graph.microsoft.com/v1.0/users/#mydata.onmicrosoft.com",
//CURLOPT_URL => "https://graph.microsoft.com/v1.0/me",
CURLOPT_HEADER => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
//curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PATCH');
CURLOPT_CUSTOMREQUEST => "PATCH",
CURLOPT_POSTFIELDS => "$data",
CURLOPT_HTTPHEADER => array(
"accept: application/json",
"authorization: Bearer $acc",
"content-type: application/json; charset=utf-8"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
print_r($response);
$json = json_decode($response);
if ($err) {
echo "cURL Error #:" . $err;
} else {
//echo $response;
}
?>
I have also set all the required permission like Directory and Users read access but cannot get it to work

Related

Is this the correct way to create and post a mutipart form data in CakePhp3?

I am trying to post a mutipart form data in CakePhp3. The form should contain a few information about the user (text fields) and an image.
I'm doing something like this:
$request = [
'fistname'=>$user->firstname,
'lastname'=>'$user->lastname',
'_session'=>'$session'
];
$form = new FormData();
foreach ($request as $key => $value) {
$form->add($key,$request);
}
$file = $form->addFile('upload',fopen(WWW_ROOT.'img/picture.png','r'));
$file->contentId('mypicture'); // <-- not sure what this is
$file->disposition('attachment');
$response = $http->post(
$url,
(string)$form,
['headers' => ['Content-Type' => $form->contentType()]]
);
Is this the correct way to create and post a mutipart form data in CakePhp3?
Thanks for your help.
EDIT
If I post to my own server it seems to be working (thanks #Mary), but I get firstname and lastname replicated (this might be the problem):
object(Cake\Http\ServerRequest) {
trustProxy => false
...
[protected] data => [
'fistname' => [
'fistname' => 'Test',
'lastname' => 'Test'
],
'lastname' => [
'fistname' => 'Test',
'lastname' => 'Test'
],
'upload' => [
'tmp_name' => '/private/var/folders/g5/jjd1vc557bs21hq805lcxjk80000gn/T/phpAVXNqK',
'error' => (int) 0,
'name' => 'SELL5BAE2B6348272_gallery_1.png',
'type' => 'image/png',
'size' => (int) 200231
]
]
...
If I post to the API server it doesn't work.
I did the same with CURL and it works:
$filename = WWW_ROOT.'ufiles/medium/'.$img['image_1'];
$cFile = curl_file_create($filename);
$request = [
'_operation'=>'uploadFile',
'id'=>$ticket_id,
'_session'=>$session,
'file' => $cFile
];
try{
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_URL,$this->crm['endpoint']);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
$response=curl_exec($ch);
curl_close ($ch);
}catch(\Exception $e){
$response = null;
}
Counterquestion: Does it work?
As you can see here, $file->contentId() sets the Content ID or part in a multipart form data request body:
https://github.com/cakephp/cakephp/blob/master/src/Http/Client/FormDataPart.php#L114
I’m not sure about this, but I don’t think you have to set it as it doesn’t seem to be required for multipart/form-data:
https://www.w3.org/TR/2006/REC-xforms-20060314/slice11.html#serialize-form-data
Edit
I did some testing and: It. works. Here is what I tried:
use Cake\Http\Client;
use Cake\Http\Client\FormData;
public function test() {
$request = [
'fistname'=>'Test',
'lastname'=>'Test'
];
$form = new FormData();
$http = new Client();
foreach ($request as $key => $value) {
$form->add($key,$request);
}
$file = $form->addFile('upload',fopen(WWW_ROOT.'img/awards.png','r'));
$file->contentId('mypicture'); // <-- not sure what this is
$file->disposition('attachment');
$response = $http->post(
'http://www.testurl.dev/test',
(string)$form,
['headers' => ['Content-Type' => $form->contentType()]]
);
var_dump($response);
exit;
}
Output of var_dump($response):
object(Cake\Http\Client\Response)#150 (12) {
["code":protected]=>int(200)
…
["headers":protected]=>array(12) {
["Date"]=>array(1) {
[0]=>string(29) "Fri, 28 Sep 2018 12:44:31 GMT"
}
…
}
}
Server access log output:
[28/Sep/2018:14:44:31 +0200] "POST /test HTTP/1.1" 200 6852 "-" "CakePHP"

drupal_mail() returns true but unable to send mail

I have written a drupal module with custom form api which will send email to my inbox on each submit. I have written a condition under drupal_mail which returns true but shows an error message "Unable to send e-mail. Contact the site administrator if the problem persists."
Below my code:
function my_module_name_mail($key, &$message, $params)
{
$headers = array(
'MIME-Version' => '1.0',
'Content-Type' => 'text/html; charset=UTF-8;',
'Content-Transfer-Encoding' => '8Bit',
'X-Mailer' => 'Drupal'
);
foreach ($headers as $key => $value) {
$message['headers'][$key] = $value;
}
$message['subject'] = $params['subject'];
$message['body'] = $params['body'];
}
function my_module_name_form_submit($form, &$form_state)
{
$from = $form_state['values']['email'];
$body= 'Name: '.$name.'<br />Email: '.$email;
$to = "my_mail_id#example.com";
$params = array(
'body' => $body,
'subject' => 'Website Information Request',
);
drupal_mail('my_module_name', 'some_mail_key', $to, language_default(), $params, $from, TRUE);
}
Check your Drupal logs for more clues. Enable devel / devel-admin modules. Once you do, drupal_mail will pipe emails to your temp directory, which will help you narrow down if the problem is with your email server or the config.

How to send cURL request in json by using php

I need to curl following input string for GoGoVan API
curl -X GET \
-H 'GoGoVan-API-Key: 3af4ba76-3767-4963-9680-327bb6d391d1' \
-H 'GoGoVan-User-Language: en-US' \
-F 'order[name]=John' \
-F 'order[phone_number]=61577364' \
-F 'order[pickup_time]=2016-01-20T18:00:00H' \
-F 'order[service_type]=delivery' \
-F 'order[vehicle]=motorcycle' \
-F 'order[title_prefix]=Corporate Order' \
-F 'order[extra_requirements][express_service]=true' \
-F 'order[extra_requirements][remark]=Please confirm the following 3 items' \
-F 'order[locations]=[[1.333948, 103.840142,"Toa Payoh, Singapore"],[1.353945, 103.843884,"5G Jalan Berjaya, Singapore"]]' \
'https://gogovan-staging-sg.herokuapp.com/api/v0/orders/price.json'
I'm using Following code to create query
$query = urlencode(json_encode(array(
'order' => array(
'name' => 'john',
'phone_number' => '61577364' ,
'pickup_time' => '2017-07-18T18:00:00H',
'service_type' => 'delivery',
'vehicle' => 'motorcycle',
'title_prefix' => 'Corporate Order',
'extra_requirements' => array(
'express_service' => 'true',
'remark'=> 'Please confirm the following 3 items'
),
'locations' => array(
'1.333948, 103.840142,"Toa Payoh, Singapore"',
'1.353945, 103.843884,"5G Jalan Berjaya, Singapore"'
)
)
))));
$apifullurl = "https://gogovan-staging-sg.herokuapp.com/api/v0/orders/price.json";
$apifullurl = $apifullurl . '?json=' . $query;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $apifullurl);
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'GoGoVan-API-Key: 3af4ba76-3767-4963-9680-327bb6d391d1',
'GoGoVan-User-Language: en-US'
)
);
$response = curl_exec($curl);
echo print_r($response);
$err_status = curl_error($curl);
curl_close($curl);
Response output that I get is null
{
"breakdown": {
"fee": {
"title": "Fee",
"value":null
}
},
"base": null,
"total": 0,
"payment_method": "cash"
}1
whereas there should be output like :
{
"base" : 10,
"total" : 35,
"breakdown" : {
"fee" : {
"title" : "Fee",
"value" : 30
},
"extra_charge_for_express":{
"title":"Express service",
"value":3
},
"multi_point_concession":{
"title":"Promotional Discount",
"value":-3
},
},
}
}
I also have same query. I think something wrong in query generation for following curl
order[locations] = [
[
1.333948,
103.840142,
"Toa Payoh, Singapore"
],
[
1.353945,
103.843884,
"5G Jalan Berjaya, Singapore"
]
]
It is an array of array. means multidimensional array .

How to get success or failure response from paypal?

Iam trying to do the paypal payment.after completion of the payment how can we get the details of the transaction and how to get the success or failure response from paypal payment in angularjs?
I'm using this PHP Code to make it. So, after you complete a transaction in Paypal, they will return to you a response, (even if the transaction was a failure). Just check the the parameter "ACK" at the array.
This response is an array with the informations about your transaction.
If you want to confer the information of your transaction. Just use the method "GetTransactionDetails", and the paypal server will return you an array with all informations(you must the transaction ID to make your Query, not your token). Just adapt this code to angularJS
<?php
function verify_Transaction($idTrans,$show){
$nvp = array(
'METHOD' => 'GetTransactionDetails',
'VERSION' => '124.0',
'PWD' => 'YOUR PASS',
'USER' => 'YOUR USER',
'SIGNATURE' => 'YOUR SIGNATURE' ,
'TRANSACTIONID' => yourTransactionID
);
$curl = curl_init();
curl_setopt( $curl , CURLOPT_URL , 'https://api-3t.sandbox.paypal.com/nvp' );
curl_setopt( $curl , CURLOPT_SSL_VERIFYPEER , false );
curl_setopt( $curl , CURLOPT_RETURNTRANSFER , 1 );
curl_setopt( $curl , CURLOPT_POST , 1 );
curl_setopt( $curl , CURLOPT_POSTFIELDS , http_build_query( $nvp ) );
$response = urldecode( curl_exec( $curl ) );
$responseNvp = array();
if ( preg_match_all( '/(?<name>[^\=]+)\=(?<value>[^&]+)&?/' , $response , $matches ) ) {
foreach ( $matches[ 'name' ] as $offset => $name ) {
$responseNvp[ $name ] = $matches[ 'value' ][ $offset ];
}
}
if($show){
echo '<pre>';print_r($responseNvp);echo'</pre>';
}
if($responseNvp['ACK']=='Success'){
//echo "true";
return true;
}else{
//echo "false";
return false;
}
}
?>

Not Getting access token from of Gmail Contacts API using Oauth2 while code is in Google App Engine Server

I am using zend-framework2 and google-app-engine server to import all gmail contact list. I am getting authorization code from gmail after login. When hitting curl using this authorization code to get access token, it gives blank array as response.
Also this app is a billed app in google-app-engine. and already set
extension = "curl.so"
in php.ini file. and the credentials which i have given are correct.
// Import Gmail Contacts
$client_id='xxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com';
$client_secret='xxxxxxxxxxxxxx-xxxxxxxxx';
$redirect_uri='http://xxxxxxxxxxxxxxx.appspot.com/u/invite/gmailCallback';
$max_results = 1000;
if(isset($_GET["code"]) && $_GET["code"] != '') {
$auth_code = $_GET["code"];
$fields=array(
'code'=> urlencode($auth_code),
'client_id'=> urlencode($client_id),
'client_secret'=> urlencode($client_secret),
'redirect_uri'=> urlencode($redirect_uri),
'grant_type'=> urlencode('authorization_code')
);
$post = '';
foreach($fields as $key=>$value) { $post .= $key.'='.$value.'&'; }
$post = rtrim($post,'&');
$curl = curl_init();
curl_setopt($curl,CURLOPT_URL,'https://accounts.google.com/o/oauth2/token');
curl_setopt($curl,CURLOPT_POST,5);
curl_setopt($curl,CURLOPT_POSTFIELDS,$post);
curl_setopt($curl, CURLOPT_RETURNTRANSFER,TRUE);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER,FALSE);
$result = curl_exec($curl);
//$info = curl_getinfo($curl);
//echo "<pre>"; print_r($info); die;
curl_close($curl);
$response = json_decode($result);
//echo "<pre>"; var_dump($response); die;
if(isset($response->access_token) && $response->access_token != '') {
$accesstoken = $response->access_token;
$url = 'https://www.google.com/m8/feeds/contacts/default/full?max-results='.$max_results.'&oauth_token='.$accesstoken;
//$url = 'https://www.google.com/m8/feeds/contacts/default/full?oauth_token='.$accesstoken;
$xmlresponse = $this->curl_file_get_contents($url);
//At times you get Authorization error from Google.
if((strlen(stristr($xmlresponse,'Authorization required'))>0) && (strlen(stristr($xmlresponse,'Error '))>0)) {
//$returnArr['error_msg'] = "Something went wrong to import contacts!!";
echo '<h2>Something went wrong to import contacts !!</h2>';die;
} else {
$xml = new SimpleXMLElement($xmlresponse);
$xml->registerXPathNamespace('gd', 'http://schemas.google.com/g/2005');
$result = $xml->xpath('//gd:email');
//echo "<pre>"; print_r($result); die;
foreach ($result as $title) {
$emailsArr[] = (string) $title->attributes()->address;
}
}
}
}
Please help.
From previous experience (and this answer) I don't think cURL is enabled on App Engine as C extensions aren't supported.
You'll have to use URL Fetch instead e.g.
$data = ['data' => 'this', 'data2' => 'that'];
$data = http_build_query($data);
$context = [
'http' => [
'method' => 'GET',
'header' => "custom-header: custom-value\r\n" .
"custom-header-two: custom-value-2\r\n",
'content' => $data
]
];
$context = stream_context_create($context);
$result = file_get_contents('http://app.com/path?query=update', false, $context);
App engine supports cURL, but it seems to be buggy. I have the same problem with OAuth authentication via Google. The POST cURL call just returns FALSE without any error message. Here is the official bug report: https://code.google.com/p/googleappengine/issues/detail?id=11985
What you can do now, is to switch to url fetch functions. To make a POST request you can use following function:
protected function _call($url, array $params, $method = 'GET', array $headers = [])
{
$query = http_build_query($params);
$headers_str = '';
if ($headers) {
foreach ($headers as $name => $value) {
$headers_str .= $name . ': ' . $value . "\r\n";
}
}
$headers_str .= "Content-type: "."application/x-www-form-urlencoded"."\r\n";
$options =
array('http'=>
array(
'method' => $method,
'header' => $headers_str,
'content' => $query,
'ignore_errors' => true,
)
);
if ($method === 'POST') {
$options['http']['content'] = $query;
} else if ($query) {
$url .= '?' . $query;
}
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
// check for zipped response and decode it
if (array_search('Content-Encoding: gzip', $http_response_header)) {
$response = gzinflate(substr($response, 10, -8));
}
return $response;
}
Or you can try to use this cURL wrapper library https://github.com/azayarni/purl, which was implemented before GAE provided cURL support. Hope it is helpful:)

Resources