I'm currently creating a Twitch notification web app in PHP.
For the moment, the authentication works fine :
Client wants use the app -> redirected on Twitch website to accept asked scopes -> redirected on my app website with a "code" parameter -> "code" sent by curl request -> response containing the accessToken.
I stored accessToken and client username in $_COOKIE and $_SESSION variable (set $_COOKIE doesn't work on all web browsers).
After that I have to check (in real-time ?) if the user has new followers. Certains web applications, as TNotifier, exists and do this very well... But I don't know how.
In the Twitch API, we have only for the follows request the possibility to list all of these followers. I thought directly i will have to make requests, again and again (with one second of delay), and compare the new request with the last one... But i think there 's an other way to make that ?
Here is the follows request :
curl -H 'Accept: application/vnd.twitchtv.v2+json' \
-X GET https://api.twitch.tv/kraken/channels/test_user1/follows
And the JSON response :
{
"_links": {
"next": "https://api.twitch.tv/kraken/channels/test_user1/follows?limit=25&offset=25",
"self": "https://api.twitch.tv/kraken/channels/test_user1/follows?limit=25&offset=0"
},
"follows": [
{
"_links": {
"self": "https://api.twitch.tv/kraken/users/test_user2/follows/channels/test_user1"
},
"user": {
"_links": {
"self": "https://api.twitch.tv/kraken/users/test_user2"
},
"staff": false,
"logo": null,
"display_name": "test_user2",
"created_at": "2013-02-06T21:21:57Z",
"updated_at": "2013-02-13T20:59:42Z",
"_id": 40091581,
"name": "test_user2"
}
},
...
]
}
Here is my code, but still thinking a better way exists...
$uknown=""; //to initialize my loop function.
comparaison($uknown);
function comparaison($u){
$options = array(
'http' => array(
'header' => 'Accept: application/vnd.twitchtv.v2+json',
'method' => 'GET',
)
);
$context = stream_context_create($options);
$result = file_get_contents('https://api.twitch.tv/kraken/channels/test_user1/follows', false, $context);
$decode_result = json_decode($result, true);
$follow=$decode_result['follows'][0];
$user=$follow['user'];
$last_follower=$user['display_name'];
if($last_follower != $u){
haveANewFollower($last_follower);
}
comparaison($last_follower);
}
Is it possible TNotifier use another way to check new followers ?
It's the only way, as there's no push way to do followers, so you have to rely on pulling. For subscribers there would be the possibility to listen for chat messages for new subscribers, but as this does not work for followers, you can only rely on the pull method using the kraken api.
Related
I am have set up a proxy that allows me to retrieve data user side from a api only accessible server side. I have several endpoints setup and they all work just fine, but now i'm at a point where I need to send data back to the api to make a reservation. I need to
retrieve data from ajax request in proxy
send data in proxy to api
return success/error message from api to ajax request
I not sure how to do this. Here is my ajax request:
var settings2 = {
"async": true,
"crossDomain": true,
"url": "http://url?method=hello&format=json&entity=" + id,
"dataType": "json",
"data": data,
"method": "POST"
};
var a2 = $.ajax(settings2);
$.when(a2).done(function(d2) {
rp = d2;
console.log(JSON.stringify(rp));
});
and the php function and method I use for the other endpoints that only need to retrieve data from the api, it works for this:
function LocationReserve(data) {
header('Content-Type: application/json');
$url = 'api_url' . $_GET['entity'] ;
$auth = 'Authorization: key';
$ch = curl_init($url);
$options = array(
CURLOPT_HTTPHEADER => array(
$auth
),
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION, 1
);
curl_setopt_array($ch, $options);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
// Method A: Say Hello to the API
if( strcasecmp($_GET['method'],'hello') == 0){
$response['code'] = 1;
$response['status'] = $api_response_code[ $response['code'] ]['HTTP Response'];
$response['data'] = wssLocationReserve();
}
// --- Step 4: Deliver Response
// Return Response to browser
deliver_response($_GET['format'], $response);
with this as it is I get a response back
{"code":1,"status":200,"data":"{\"Message\":\"The requested resource does not support http method 'GET'.\"}"}
I added CURLOPT_POST => true to my options and now the response is
{"code":1,"status":200,"data":"<html><head><title>411 Invalid Request</title></head><body>Invalid Request: ??</body>\r\n"}
How can I modify this to accept the data from my ajax call, send it to the api_url, and send back the response?
**EDIT example expected data by api:
{
"ReservationDay": "05/15/2015",
"Units": [{
"UnitID": 12345,
"InsuranceID": 123 (or null)
}],
"PaymentInfo": {
"FirstName": "User",
"LastName": "Userson",
"Address1": "2727 N Central Ave",
"Address2": "",
"City": "Phoenix",
"State": "AZ",
"Zip": "85022",
"Phone": "602-2877878",
"Email": "email#example.com",
"CreditCard": "6011000000000000",
"ExpirationMMYY": "1215",
"CSC": "100"
}
}
"HTTP Status Code 411 (Length Required) is sent by the server as a response when it refuses to accept a message without a content-length header, for whatever reason."
1.- Test a request sending possible missing arguments.
2.- Have you the format in which the data must be send to the second endpoint? Check the specifications of the expected data and fix your second request.
I've made a call to https://login.windows.net/common/oauth2/token and received something like this in response:
{
"token_type": "Bearer",
"scope": "Directory.Read.All User.Read",
"expires_in": "3600",
"ext_expires_in": "0",
"resource": "https://graph.windows.net",
"access_token": {{really_long_token_1}},
"refresh_token": {{really_long_token_2}},
"id_token": {{really_long_token_3}}
}
I have a website hosted on HostGator that's trying to access an API I have located on Azure.
What is the correct form of a GET call to my API hosted on Azure? Here's what I have so far:
$url = 'https://myappservice.azurewebsites.net/api/getValues';
$options = array(
'http' => array(
'header' => array(
'x-ms-version: 2017-06-02',
'Authorization: Bearer {{really_long_token_1}}'
),
'method' => 'GET'
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
$var_dump($result);
I end up getting 500 Server Errors while making this call.
The 500 is Internal Error which indicates the server encountered an unexpected condition which prevented it from fulfilling the request.
It should not be relative to the authentication/authorization, please check whether there is code can cause this exception. Or you can just replace the code with a very easy code sample without any complex business logic just return the values.
I don't find how to get the user_metadata from the Auth0 Authentication api:
$auth0Api = new Authentication($domain, $clientId, $clientSecret);
$tokenInfo = $auth0Api->login([
'username' => $username,
'password' => $password,
'realm' => 'Username-Password-Authentication',
]);
$accessToken = $tokenInfo["access_token"];
$info = $auth0Api->userinfo($accessToken);
The final $info array only contains the main user information, no meta_data at all. I tried creating a rule from the Auth0 side to add stuff to the user itself (doing user.customtag = 'helloworld' for example) and the customization does not show either.
User info retrieved:
{
"sub":"auth0|XXXX",
"name":"XXXX#XXXX.com",
"nickname":"XXXX",
"picture":"XXXX.png",
"updated_at":"2017-03-31T08:50:59.819Z",
"email":"XXXX#XXXX.com",
"email_verified":true
}
The "Raw Json" tab of that user shows something much more complete:
{
"email": "XXXX#XXXX.com",
"email_verified": true,
"user_id": "auth0|XXXX",
"picture": "XXXX.png",
"nickname": "XXXX",
"identities": [
{
"user_id": "XXXX",
"provider": "auth0",
"connection": "Username-Password-Authentication",
"isSocial": false
}
],
"updated_at": "2017-03-31T08:50:59.819Z",
"created_at": "2017-03-23T16:03:47.075Z",
"name": "XXXX",
"user_metadata": {
"languageCode": "EN"
},
"last_ip": "XXXX",
"last_login": "XXXX",
"logins_count": XXXX,
"blocked_for": [],
"guardian_enrollments": []
}
How is it supposed to work?
Environment:
composer: "auth0/auth0-php": "~5.0"
php 7.1
Auth0 Free account
Try starting up your application locally, then update the following URL with your own settings and paste it into a web browser:
https://YOUR_TENANT.auth0.com/authorize?client_id=YOUR_CLIENT_ID&response_type=code&scope=openid profile&redirect_uri=YOUR_REDIRECT_URI&nonce=12345
This should at least ensure you are making a request with right scopes etc. You should also ensure you have a User Profile with some "metadata" assigned if you are expecting to read that data post authentication of course ;)
I am working on alexa for the first time and I am developing a music app. I need to add multiple track of one artist and play it continuously. I am unable to do so. However, one song is working properly but unable to add and play multiple song.
Here is my code,
$response = '{
"version" : "1.0",
"response" : {
"outputSpeech": {
"type": "PlainText",
"text": "Playing song for Acon"
},
'.$card.',
"directives": [
{
"type": "AudioPlayer.Play",
"playBehavior": "REPLACE_ALL",
"audioItem": {
"stream": {
"token": "track1",
"url": "https://p.scdn.co/mp3-preview/9153bcc4d7bef50eb80a809fa34e694f2854e539?cid=null",
"offsetInMilliseconds": 0
}
}
}
],
"shouldEndSession" : true
}
}';
You need to wait for the AudioPlayer.PlaybackNearlyFinished request from Alexa. At that point, you can enqueue the next track to be played. It will come near the conclusion of the playback of the currently playing track.
Information on it is here:
https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/custom-audioplayer-interface-reference#playbacknearlyfinished-request
When replying with a directive to PlaybackNearlyFinished, be sure that:
You set the playBehavior to ENQUEUE
This will cause the next track to start after the current one finishes
You do NOT include the outputSpeech field
outputSpeech is not allowed when out of session. The session ends when the first stream begins playback.
This blog post that I wrote goes into more detail on approaches to developing and testing for the AudioPlayer interface:
https://bespoken.tools/blog/2016/10/10/unit-testing-alexa-skills
Follow the above doc:
https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/custom-audioplayer-interface-reference#playbacknearlyfinished-request
and then do this to enqueue the second song
In PHP, the way you are handling other requests, you can handle AudioRequest too. For example.
$data = file_get_contents("php://input");
$jsonData = json_decode($data);
if($jsonData->request->type === "AudioPlayer.PlaybackNearlyFinished")
{
$response = '{
"version" : "1.0",
"response" : {
"directives": [
{
"type": "AudioPlayer.Play",
"playBehavior": "ENQUEUE",
"audioItem": {
"stream": {
"token": "track2",
"expectedPreviousToken": "track1",
"url": "Your URL",
"offsetInMilliseconds": 3
}
}
}
],
"shouldEndSession" : true
}
}';
echo $response;
}
This is the way you can handle all the AudioRequest.
I have found a couple of helpful links on stackoverflow but they haven't helped me complete my task because I am a complete beginner in trying to write PHP or use curl etc.
Send json post using php
Posting JSON data to API using CURL
I have been using Postman in Chrome to test API calls but I now want to put together a demo system on my Apache web server.
Does anyone have an example of a PHP webform posting to a json Object to a REST API?
Here is an example of what I want to send:
<?php
$url = "https://api.url/api/v1//accounts/create";
$jdata = json_encode($data);
$data = [{
"status": "active",
"username": ["uname"],
"password": ["pword"],
"attributes": {
"forenames": ["fname"],
"surname": ["lname"],
"emailAddress": ["email"]
},
}]
?>
Any advice would be fantastic. Like I said, I am new to curl and php, am unfamiliar with the array approach mentioned in the other articles and the ["info"] elements should be populated with the information filled in on my webform.
I hope I have been concise and explanitory but please let me know if you need anymore information.
Snook
Try something like the following, modifying steps 1 and 2 accordingly:
function sendRequest($data,$url)
{
$postdata = http_build_query(array('data'=>$data));
$opts = array('http' =>
array(
'method' => 'POST',
'header' => "Content-type: application/x-www-form-urlencoded \r\n",
//"X-Requested-With: XMLHttpRequest \r\n".
//"curl/7.9.8 (i686-pc-linux-gnu) libcurl 7.9.8 (OpenSSL 0.9.6b) (ipv6 enabled)\r\n",
'content' => $postdata,
'ignore_errors' => true,
'timeout' => 10,
)
);
$context = stream_context_create($opts);
return file_get_contents($url, false, $context);
}
// 1.- add your json
$data = '[{
"status" : "active",
"username" : ["uname"],
"password" : ["pword"],
"attributes" : {
"forenames" : ["fname"],
"surname" : ["lname"],
"emailAddress": ["email"]
},
}]';
// 2.- add api endpoint
$url= "https://api.url/api/v1//accounts/create";
// 3.- fire
$result = sendRequest($data,$url);
// 4.- dump result
echo $result;
die();
Good luck!!