Get courses list with udemy api - javascript

Im trying to reach udemy courses list with their affiliate API and PHP.
I can get data without problem if i dont use json_decode'. When i use json_decode im getting this error.
'SyntaxError: JSON.parse: unexpected character at line 1 column 1 of
the JSON data'
function getcourse($id)
{
header('Content-Type: application/json');
$url = "https://www.udemy.com/api-2.0/courses/$id?fields[course]=#all";
// Initiate curl
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$c_id = base64_encode('myclientid');
$c_sid = base64_encode('myclientsecretid');
curl_setopt($ch,CURLOPT_HTTPHEADER,array('X-Udemy-Client-Id: '.$c_id.'','X-Udemy-Client-Secret: '.$c_sid.'',"Authorization: base64 encoded value of client-id:client-secret","Accept: application/json, text/plain, */*"));
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
$result=curl_exec($ch);
echo curl_getinfo($ch, CURLINFO_HEADER_OUT);
echo curl_getinfo($ch,CURLINFO_HTTP_CODE);
// Closing
curl_close($ch);
$result = json_decode($result);
return $result;
}
$cdetail = getcourse(120042);
print_r($cdetail);

I didn't get any error running your code.
You're getting this error
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data'
Because you're using "header('Content-Type: application/json');", and you're probably using Firefox, it will think all content is json and it will verify if there is anything wrong with it.
Comment "header('Content-Type: application/json');" and you'll get your data.

Related

Need to call SAP web service to send XML file from web page using JavaScript

We need to call an SAP web service from our website and submit an XML file to the SAP url. SAP API has credentials.
The purpose is to execute a function module in SAP which creates an SAP user ID and then returns the SAP user ID name back to our website via a return xml.
Below is the PHP code which i have tried.
<?php
$credentials = "Username:Password";
// Read the XML to send to the Web Service
$request_file = "m2bsubscr.XML";
$fh = fopen($request_file, 'r');
$xml_data = fread($fh, filesize($request_file));
fclose($fh);
$url = "SAP API HERE";
$headers = array(
"Content-type: text/xml;charset=\"utf-8\"",
"Accept: text/xml",
"Cache-Control: no-cache",
"Pragma: no-cache",
"SOAPAction: \"run\"",
"Content-length: ".strlen($xml_data),
"Authorization: Basic " . base64_encode($credentials)
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_USERAGENT, $defined_vars['HTTP_USER_AGENT']);
// Apply the XML to our curl call
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_data);
$data = curl_exec($ch);
if (curl_errno($ch)) {
print "Error: " . curl_error($ch);
} else {
// Show me the result
echo "Success!<br />\n";
}
curl_close($ch);
// Handle the response from a successful request
$xmlobj = simplexml_load_string($data);
var_dump($xmlobj);
?>
My XML File:
<n0:_-majul_-m2bSubscriptionCreate xmlns:n0="urn:sap-com:document:sap:soap:functions:mc-style">
<IsSubscription>
<Bupar></Bupar>
<Sstat></Sstat>
<Categ></Categ>
<Fname>Wolfgang</Fname>
<Lname>Haerle</Lname>
<Email>whaerle#hotmail.com</Email>
<Srmrk></Srmrk>
<Cczip></Cczip>
<Cccty></Cccty>
<Ccadr></Ccadr>
<Cntry>US</Cntry>
<Product>1</Product>
<Begda>2020-07-08</Begda>
<Endda>2020-08-08</Endda>
<Price>765</Price>
<Curr>USD</Curr>
<Quantity>1</Quantity>
<Unit>MON</Unit>
<Userid></Userid>
</IsSubscription>
</n0:_-majul_-m2bSubscriptionCreate>
but it returns Success with bool(false) as a result. I tried to display error but it has no error.
Please help me to find what is the issue.
I wanted to do this in JavaScript. Kindly suggest me the way to do.

XmlHttpRequest - post JSON - json string too many quotes (i think) [duplicate]

I looked around a lot before posting this question so my apologies if it is on another post and this is only my second quesiton on here so apologies if I don't format this question correctly.
I have a really simple web service that I have created that needs to take post values and return a JSON encoded array. That all worked fine until I was told I would need to post the form data with a content-type of application/json. Since then I cannot return any values from the web service and it is definitely something to do with how I am filtering their post values.
Basically in my local setup I have created a test page that does the following -
$curl = curl_init();
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data))
);
curl_setopt($curl, CURLOPT_URL, 'http://webservice.local/'); // Set the url path we want to call
$result = curl_exec($curl);
//see the results
$json=json_decode($result,true);
curl_close($curl);
print_r($json);
On the webservice I have this (I have stripped out some of the functions) -
<?php
header('Content-type: application/json');
/* connect to the db */
$link = mysql_connect('localhost','root','root') or die('Cannot connect to the DB');
mysql_select_db('webservice',$link) or die('Cannot select the DB');
if(isset($_POST['action']) && $_POST['action'] == 'login') {
$statusCode = array('statusCode'=>1, 'statusDescription'=>'Login Process - Fail');
$posts[] = array('status'=>$statusCode);
header('Content-type: application/json');
echo json_encode($posts);
/* disconnect from the db */
}
#mysql_close($link);
?>
Basically I know that it is due to the $_POST values not being set but I can't find what I need to put instead of the $_POST. I tried
json_decode($_POST), file_get_contents("php://input") and a number of other ways but I was shooting in the dark a bit.
Any help would be greatly appreciated.
Thanks, Steve
Thanks Michael for the help, that was a definite step forward I now have at least got a repsonse when I echo the post....even if it is null
updated CURL -
$curl = curl_init();
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_URL, 'http://webservice.local/');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
updated php on the page that the data is posted to -
$inputJSON = file_get_contents('php://input');
$input= json_decode( $inputJSON, TRUE ); //convert JSON into array
print_r(json_encode($input));
As I say at least I see a response now wheras prior it was returning a blank page
You have empty $_POST. If your web-server wants see data in json-format you need to read the raw input and then parse it with JSON decode.
You need something like that:
$json = file_get_contents('php://input');
$obj = json_decode($json);
Also you have wrong code for testing JSON-communication...
CURLOPT_POSTFIELDS tells curl to encode your parameters as application/x-www-form-urlencoded. You need JSON-string here.
UPDATE
Your php code for test page should be like that:
$data_string = json_encode($data);
$ch = curl_init('http://webservice.local/');
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);
$result = json_decode($result);
var_dump($result);
Also on your web-service page you should remove one of the lines header('Content-type: application/json');. It must be called only once.
Hello this is a snippet from an old project of mine that uses curl to get ip information from some free ip databases services which reply in json format. I think it might help you.
$ip_srv = array("http://freegeoip.net/json/$this->ip","http://smart-ip.net/geoip-json/$this->ip");
getUserLocation($ip_srv);
Function:
function getUserLocation($services) {
$ctx = stream_context_create(array('http' => array('timeout' => 15))); // 15 seconds timeout
for ($i = 0; $i < count($services); $i++) {
// Configuring curl options
$options = array (
CURLOPT_RETURNTRANSFER => true, // return web page
//CURLOPT_HEADER => false, // don't return headers
CURLOPT_HTTPHEADER => array('Content-type: application/json'),
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle compressed
CURLOPT_USERAGENT => "test", // who am i
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 5, // timeout on connect
CURLOPT_TIMEOUT => 5, // timeout on response
CURLOPT_MAXREDIRS => 10 // stop after 10 redirects
);
// Initializing curl
$ch = curl_init($services[$i]);
curl_setopt_array ( $ch, $options );
$content = curl_exec ( $ch );
$err = curl_errno ( $ch );
$errmsg = curl_error ( $ch );
$header = curl_getinfo ( $ch );
$httpCode = curl_getinfo ( $ch, CURLINFO_HTTP_CODE );
curl_close ( $ch );
//echo 'service: ' . $services[$i] . '</br>';
//echo 'err: '.$err.'</br>';
//echo 'errmsg: '.$errmsg.'</br>';
//echo 'httpCode: '.$httpCode.'</br>';
//print_r($header);
//print_r(json_decode($content, true));
if ($err == 0 && $httpCode == 200 && $header['download_content_length'] > 0) {
return json_decode($content, true);
}
}
}
you can put your json in a parameter and send it instead of put only your json in header:
$post_string= 'json_param=' . json_encode($data);
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $post_string);
curl_setopt($curl, CURLOPT_URL, 'http://webservice.local/'); // Set the url path we want to call
//execute post
$result = curl_exec($curl);
//see the results
$json=json_decode($result,true);
curl_close($curl);
print_r($json);
on the service side you can get your json string as a parameter:
$json_string = $_POST['json_param'];
$obj = json_decode($json_string);
then you can use your converted data as object.

Unable to access Microsoft Graph API after getting OAuth access_token

I'm using adal.js to generate an access token via Microsoft OAuth, however whenever I try to use the access token to call the https://graph.microsoft.com/v1.0/me endpoint (or graph.windows.net), I receive the following error: Authentication_MissingOrMalformed: Access Token missing or malformed.
Any ideas on how I can remedy this? Here's my config in JS:
<script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.0.12/js/adal.min.js"></script>
<script>
var authContext = new AuthenticationContext({
instance: 'https://login.microsoft.com/',
tenant: 'xxxxxx-xxxxxxx-xxxxxx-xxxxxx', //COMMON OR YOUR TENANT ID
clientId: 'xxxxxx-xxxxxxx-xxxxxx-xxxxxx', //REPLACE WITH YOUR CLIENT ID
redirectUri: '/login.php', //REPLACE WITH YOUR REDIRECT URL
callback: getUser,
popUp: true,
cacheLocation: 'localStorage'
});
...
authContext.login();
// SET COOKIE
var newToken = authContext.getCachedToken('tenantid-xxxxxxx-xxxxxx-xxxxxx');
var now = new Date();
now.setTime(now.getTime() + 1 * 3600 * 1000);
document.cookie = "token="+newToken+"; expires=" + now.toUTCString() + "; path=/";
</script>
And here's how I'm attempting to pull/use the token in my PHP script:
<?php
// Get the token
$token = $_COOKIE['token'];
// Set headers
$headers = array(
"Authorization: Bearer " . $token,
'Content-Type: application/json'
);
// Make request to Graph API
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://graph.windows.net/mywebsite.org/me?api-version=1.6");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$response = json_decode($response);
curl_close($ch);
echo "<pre>";
var_dump($response);
echo "</pre>";
?>
All it does is return this error: Authentication_MissingOrMalformed: Access Token missing or malformed.
How can I fix this?? Is it a problem with not specifying the correct resource?
To call the Azure AD Graph REST successfully, we need to acquire the token for the Azure AD Graph.
To check whether the token is correct for the Azure AD Graph, you can print the token and parse it from here.
The aud claim in the token should be https://graph.windows.net. If it does't match, you need to acquire the token using the acquireToken instead of getting the token from cache. And the resource parameter should be https://graph.windows.net.

Soundcloud PUT API returning 401

I am trying to update soundcloud track details using HTTP API with CURL. I am getting 401 Unauthorized error as response eventhough I have passed my Client ID.
PUT https://api.soundcloud.com/tracks/11111111?client_id=12345666666
The response is
{
"errors": [
{
"error_message": "401 - Unauthorized"
}
]
}
Also wondering if I can pass access_token with the request.
If you want to pass your token, simply append "&oauth_token=" + TOKEN_VALUE
https://api.soundcloud.com/tracks/11111111?client_id=12345666666&oauth_token=YOUR_TOKEN
Edited to add example code
Here is an example of PUT using Curl & with PHP for soundcloud auth token. This code is from a working soundcloud project.
$data = array(
'code' => $token,
'client_id' => $this->getClientId(false), // your client ID
'client_secret' => $this->getClientSecret(), // your client secret
'redirect_uri' => $this->getCallback(), // callback URL
'grant_type' => 'authorization_code'
);
$url = "https://api.soundcloud.com/oauth2/token";
try {
$ch = curl_init();
// set options
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
$response = curl_exec($ch);
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($response, 0, $header_size);
$body = substr($response, $header_size);
// read / process result
curl_close($ch);
} catch(Exception $e) {
// error handling...
}
This may work. Try turning off various CURL options. In my case I had PUT working under PHP5.5 but after migrating to new server with PHP7 the POST operation would fail until I set CURLOPT_SAFE_UPLOAD to false for soundcloud POST operations (file uploads); however after making this change to all my curl inits, my PUT operations failed because they also had safeupload set to false, so I removed this setting from my PUT operations and the PUT operations started working.
In short, try turning off SAFE UPLOAD option for your PUT operations.
More info about this curl option on this post.

Passing a URL into a JSON array

I'm attempting to execute a curl statement in PHP that uses a JSON array. I'll post my code below with a little explanation of what im trying to do
function doPost($url, $user, $password, $params) {
$authentication = 'Authorization: Basic '.base64_encode("$user:$password");
$http = curl_init($url);
curl_setopt($http, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($http, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($http, CURLOPT_RETURNTRANSFER, true);
curl_setopt($http, CURLOPT_URL, $url);
curl_setopt($http, CURLOPT_POST, true);
curl_setopt($http, CURLOPT_POSTFIELDS, $params);
curl_setopt($http, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json', $authentication));
return curl_exec($http);
}
$link = "http://link.it/i.htm?id=55&key=23987gf2389fg";
$phone = '5551231234';
$phone = '1' . $phone;
//Write message
$msg = "Click here " . $link;
$params = '[{"phoneNumber":"'.$phone.'","message":"'.$msg.'"}]';
//Send message
$return = doPost('https://api.link.com','username','password',$params);
echo $return;
Params ends up being
$params = '[{"phoneNumber":"15551231234","message":"Click here http://link.it/i.htm?id=55&key=23987gf2389fg"}]';
All looks good. And the JSON array that is being created by params actually works perfectly if there is no link inside the $msg variable. I am able to execute a successful CURL call. The only time it fails is when I add a link to my $msg variable.
I have contact the support team for the API and they inform me that everything should work on their end.
At this point I am guessing that the link needs to be escaped somehow before it can be written into the JSON array. I have tried escaping the colons and forward slashes with back slashes, but it does not fix the problem. Is there anyone that can shed some light on how to pass a url?
Thank you in advance!!
Don't construct your JSON manually. Construct and array or object then call json_encode() on it.
$params = array();
$object = array("phone"=>$phone, "message"=>$linkMsg);
$params[] = (object) $object;
$param_json_string = json_encode($params);
Then when submitting the JSON via POST with curl, you need to specify the lenght of the string in the header.
curl_setopt($http, CURLOPT_HTTPHEADER,
array( 'Content-Type: application/json',
'Content-Length: '. strlen($param_json_string)));
Of course, this is in addition to other headers like authentication you're setting (as I see you do in your doPost() method).

Categories

Resources