HyBirdAuth Twitch Subscriber? - php

I've written my own function to check if a the user is subscribed, But i did this using my own authentication method, How can i use hybirdauth to use my function to check if the login in user is subscriber? I know i can get the access token by doing Hybrid_Provider_Adapter::getAccessToken(). My function returns a simple httpd 200 if subscriber, any other value isn't important. My main question is where can i insert my function, where do i call to check for the http code. I have add user_subscribe as an additional scope which works.
public function subcheck($access_token){
$username = $this->authenticated_user($access_token);
$url="https://api.twitch.tv/kraken/users/" . $username . "/subscriptions/".$channel;
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/vnd.twitchtv.v3+json', 'Authorization: OAuth '.$access_token));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, 0);
// Execute
$result=curl_exec($ch);
$httpdStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Will dump a beauty json :3
//var_dump(json_decode($result, true));
return $httpdStatus;
}

Change the public scope to
public $scope = "user_read user_subscriptions";
2.Change the getUserProfile to below, this will check if user is a sub, if user isnt a sub it will stop the script and redirect page.
function getUserProfile()
{
$data = $this->api->api( "user" );
if ( ! isset( $data->name ) ){
throw new Exception( "User profile request failed! {$this->providerId} returned an invalid response.", 6 );
}
$access_token = $this->api->access_token;
$username = $data->display_name;
$channel= "Twitch_Channel_Here"
$url="https://api.twitch.tv/kraken/users/" . $username . "/subscriptions/".$channel."";
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/vnd.twitchtv.v3+json', 'Authorization: OAuth '.$access_token));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, 0);
// Execute
$result=curl_exec($ch);
$httpdStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
//Check if Sub?? 200 == Sub?
if ($httpdStatus == "200") {
//Do Nothing
echo 'SUB';
}
else {
//if not a sub then well... ...
header("Location: http://google.com/nonsub.jpg"); /* Redirect browser */
exit();
}
$this->user->profile->identifier = $data->_id;
$this->user->profile->displayName = $data->display_name;
$this->user->profile->photoURL = $data->logo;
$this->user->profile->profileURL = "http://www.twitch.tv/" . $data->name;
$this->user->profile->email = $data->email;
if( ! $this->user->profile->displayName ){
$this->user->profile->displayName = $data->name;
}

Related

AWS Flask session not persistent from PHP requests

I deployed a Flask application to AWS lambda
#bp_google_routes.route('/is_authorized', methods=('POST', ))
def google_is_authorized():
data = json.loads(request.data)
flask.session['user_email'] = data['email']
authorized = aws_handler.already_authorized(data['email'])
return jsonify({'authorized': authorized})
#bp_google_routes.route('/authorize', methods=('GET', ))
def google_authorize():
if 'user_email' not in flask.session:
abort(404)
return 'All good'
I'm accessing the application via an PHP backend to first check the authorization is_authorized which is a POST request and will store the email in the session.
Then right after I'll perform a second call to authorize which always aborts since apparently there's no email in the session. But there should be from the first request:
<?php
$data = array("email" => "test#test.com");
$data_string = json_encode($data);
$aws_endpoint = "https://.../is_authorized";
$aws_endpoint_auth = "https://.../authorize";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $aws_endpoint);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json')
);
$response = curl_exec($ch);
$err = curl_error($ch);
curl_close ($ch);
if ($err) {
echo "There was an error accessing the requested information!";
} else {
$result = json_decode($response);
if (!$result->authorized) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $aws_endpoint_auth);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
echo $result;
print_r('False');
} else {
print_r('True');
}
}
?>
Why is the the session not persistent between the two calls?
You need to tell curl to persist the cookies using a cookiejar.
Add the line below to the top of your file:
$cookieFileName = tempnam('/tmp','cookies.txt');
Then add the curl_setopt calls below to each of your calls:
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFileName);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFileName);
This way, curl will store & re-use the cookies between requests.

My API request keeps using up 25 requests for no apparent reason

My request functions from PUBG official API
<?php
function getProfile($profile, $div){
$pubgapikey = 'xxxxxxxxxxxxx';
$id = getID($profile);
$url = "https://api.pubg.com/shards/pc-na/players/$id/seasons/$div";
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $pubgapikey, 'Accept: application/vnd.api+json'));
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
curl_close($ch);
$json = json_decode($result, true);
if($json["data"]["type"] == "playerSeason"){
return $json["data"]["attributes"];
}else {
return false;
}
}
function getID($name){
$pubgapikey = 'xxxxxxxxxxxxxxxxxxx';
$url = "https://api.pubg.com/shards/pc-na/players?filter[playerNames]=$name";
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $pubgapikey, 'Accept: application/vnd.api+json'));
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
curl_close($ch);
$json = json_decode($result, true);
return $json["data"][0]["id"];
}
So That's my function for requesting the data. I'll include the ways I call this.
// My index.php file (All requests go through here)
$page = explode("/", trim($_SERVER["REQUEST_URI"], "/"));
switch($page[0]){
case "profile":
require("controllers/search_controller.php");
$data = getProfile($page[1], "division.bro.official.2018-09");
if($data != false){
include("pages/profile.php");
}else{
include("pages/home.php");
echo '<script> document.getElementById("error").innerHTML = "Cannot find user. Remember To Be Capital Sensitive!"; </script>';
}
break;
}
I know that I'm using a really dumb way to include pages and what not but I don't wanna use or build my own php framework atm and this works just fine for what I'm doing
// Here is my php for calling the function
<?php
if (isset($_POST['username'])) {
$user = $_POST['username'];
if($user != ""){
header("Location: http://www.statstreak.us/profile/$user");
die();
}
}
?>
That's pretty much it. The form is just a basic html form.
For some reason this keeps using up my 25 requests/minute that I got from PUBG which is annoying as I can't find a reason why it would use up more than 2 requests per user

Terminate function a() when function b() failed

We are a little bit confuse how we can achieve this problem. We don't want to run the createsite function in our code if createSubaccount function fails. We would truly appreciate any feedbacks, comments, guides on our code.
<?php
//Set API user and password
define("API_USER","user");
define("API_PASS","pw");
$createdSite = createSite($_REQUEST['template_id'],$_REQUEST['original_url']);
//echo 'Site Created: ' . $createdSite . '<br/>';
$accountCreated = createSubAccount($_REQUEST['email']);//client email
//echo 'Account created: ' . $accountCreated . '<br/>';
$first_name = $_REQUEST['first_name'];//First Name
$last_name = $_REQUEST['last_name'];//Last Name
$retArr = ["sso"=>$sso_link,"ru"=>$resetURL,"ac"=>$accountCreated,"fn"=>$first_name,"ln"=>$last_name];//assoc array
print json_encode ($retArr);//json string
function createSite($template_id,$original_url) {
//create array with data
if($original_url) {
$data = array("template_id"=>$_REQUEST['template_id'],"url"=>$original_url);
} else {
$data = array("template_id"=>$_REQUEST['template_id']);
}
//turn data into json to pass via cURL
$data = json_encode($data);
//Set cURL parameters
$ch = curl_init();
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_URL, 'https://api.website.com/api/create');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, API_USER.':'.API_PASS);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
//execute cURL call and get template data
$output = curl_exec($ch);
//check for errors in cURL
if(curl_errno($ch)) {
die('Curl error: ' . curl_error($ch));
}
$output = json_decode($output);
return $output->site_name;//Output /Return : {"site_name":"28e1182c"}
}
function createSubAccount($emailToCreate) {
$first_name = $_REQUEST['first_name'];//First Name
$last_name = $_REQUEST['last_name'];//Last Name
$data = '{"account_name":"'.$emailToCreate.'", "first_name":"'.$first_name.'", "last_name":"'.$last_name.'"}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_URL, 'https://api.website.com/api/create');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, API_USER.':'.API_PASS);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
//execute cURL call and get template data
$output = curl_exec($ch);
if(curl_getinfo($ch,CURLINFO_HTTP_CODE) == 204) {
curl_close($ch);
return $emailToCreate;//Expected return HTTP Code: 204 No Content
} else {
curl_close($ch);
$output = 'failed';
return $output;
die('Account creation failed, error: '. $output . '<br/>');
}
}
?>
This is where an Exception comes in handy.
function createSite() {
throw new \Exception('Failed');
}
try {
$createdSite = createSite($_REQUEST['template_id'],$_REQUEST['original_url']);
//echo 'Site Created: ' . $createdSite . '<br/>';
$accountCreated = createSubAccount($_REQUEST['email']);//client email
} catch(\Exception $err) {
echo $err->getMessage();
}
The Exception prevents the rest of the code in the block from executing once thrown.

Airbnb Login Script through the command line using PHP

Is there a way to programmatically login to Airbnb with email/password through a CLI PHP script? and get a response back?
Thanks.
If you're looking to remotely log in to Airbnb and return information, you can use cURL to post data to Airbnb and return the results.
Examples on how to post form data can be found all over the web, however, a very reputable tutorial can be found here. Essentially, you want to cURL the login page, and include the login information with POST.
<?php
// A very simple PHP example that sends a HTTP POST to a remote site
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://www.airbnb.com/login");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
"email=" . $email . "&password=" . $password);
// in real life you should use something like:
// curl_setopt($ch, CURLOPT_POSTFIELDS,
// http_build_query(array('email' => $email, 'password' => $password)));
// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
curl_close ($ch);
// further processing ....
if ($server_output == "OK") { ... } else { ... }
?>
Make sure you check out this answer on SO, as well as the tutorials here.
Yes, there is. Airbnb's API isn't open to the general public, but if you sniff the traffic from your phone, you can see what requests are being sent to which endpoints. I experimented a little bit with their API and it follows as such for logging in
<?php
class AirBnB {
// Define the properties
public $currency = 'USD';
public $language = 'en';
public $country = 'us';
public $network = 'AT&T';
public $apiKey = '915pw2pnf4h1aiguhph5gc5b2';
public $adId = '911EBF1C-7C1D-46D5-A925-2F49ED064C92';
public $deviceId = 'a382581f36f1635a78f3d688bf0f99d85ec7e21f';
public function SendRequest($endpoint, $token, $post, $data, $cookies) {
$headers = array(
'Host: api.airbnb.com',
'Accept: application/json',
'Accept-Language: en-us',
'Connection: keep-alive',
'Content-Type: application/json',
'Proxy-Connection: keep-alive',
'X-Airbnb-Carrier-Country: '.$this->country,
'X-Airbnb-Currency: '.$this->currency,
'X-Airbnb-Locale: '.$this->language,
'X-Airbnb-Carrier-Name: '.$this->network,
'X-Airbnb-Network-Type: wifi',
'X-Airbnb-API-Key: '.$this->apiKey,
'X-Airbnb-Device-ID: '.$this->deviceId,
'X-Airbnb-Advertising-ID: '.$this->adId,
);
// Add the new custom headers
if($token) {
$header = 'X-Airbnb-OAuth-Token: '.$token;
array_push($headers, $header);
}
// Add the query string
if(!$post && is_array($data)) {
$endpoint .= '?'.http_build_query($data);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.airbnb.com/'.$endpoint);
curl_setopt($ch, CURLOPT_USERAGENT, 'Airbnb/15.50 iPhone/9.2 Type/Phone');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
if($post) {
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
}
if($cookies) {
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies.txt');
} else {
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies.txt');
}
$response = curl_exec($ch);
$http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return array(
'http' => $http,
'response' => $response
);
}
public function Authorize($username, $password) {
$data = array(
'username' => $username,
'password' => $password,
'prevent_account_creation' => TRUE,
);
$data = $this->SendRequest('v1/authorize', FALSE, TRUE, $data, FALSE);
if($data['http'] == 200) {
$json = #json_decode($data['response'], TRUE);
return $json['access_token'];
} else {
return FALSE;
}
}
}
// Call a new instance of AirBnB
$airbnb = new AirBnB;
// Get the OAuth token
$token = $airbnb->Authorize('my#email.com', 'password');
?>
You can find out more about their API here.

Retrieving menu information from mmjmenu api to deliver to my website

I am new to working with api and have been searching for the little tiny piece of code that makes the following snippit possible, but I am having trouble finding it. I have been watching tutorials on jquery, ajax, json, and php but have not found exactly what I need. If someone could show me a simple example of how the request would be constructed from the opening tag of the file to the closing tag it would be very helpful. After I get the data returned I can figure out how to parse and style it for display.
The first piece of code is the example that someone else said they use but I tried it (with my own api key) and I seem to be missing something. The second code is the "Mmjmenu.php" file that I assume needs to be in the same directory as the first php file. Following the code is the error I get.
("my api key" is replacing my actual key)
<?php
require 'API/Mmjmenu.php';
$client = new Mmjmenu('my api key');
$menuItems = $client->menuItems();
$menuItems = json_decode($menuItems, true);
foreach($menuItems['menu_items'] as $item)
{
echo $item['name'];
}
?>
This is the "Mmjmenu.php" file (can be found on git hub):
<?php
class Mmjmenu {
private $domain = 'https://mmjmenu.com/api/v1';
private $active_api_key;
private $active_domain;
private $username;
private $password;
public function __construct($api_key, $active_domain = null, $active_api_key = null) {
$this->setActiveDomain($this->domain, $api_key);
}
public function setActiveDomain($active_domain, $active_api_key) {
$this->active_domain = $active_domain;
$this->active_api_key = $active_api_key;
$this->username = $this->active_api_key;
$this->password = 'x';
}
private function sendRequest($uri, $method = 'GET', $data = '') {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://mmjmenu.com/api/v1" . $uri);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_MAXREDIRS, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Accept: application/json'
));
curl_setopt($ch, CURLOPT_USERPWD, $this->username . ':' . $this->password);
$method = strtoupper($method);
if($method == 'POST')
{
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
}
else if ($method == 'PUT')
{
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
}
else if($method != 'GET')
{
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
}
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$result = new StdClass();
$result->response = curl_exec($ch);
$result->code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$result->meta = curl_getinfo($ch);
$curl_error = ($result->code > 0 ? null : curl_error($ch) . ' (' . curl_errno($ch) . ')');
curl_close($ch);
if ($curl_error) {
//print('ERROR');
}
return $result;
}
/****************************************************
********************* MENU ITEMS ********************
****************************************************/
public function menuItems() {
$base_url = '/menu_items';
$menuItems = $this->sendRequest($base_url);
return $menuItems->response;
}
public function menuItem($id) {
$base_url = "/menu_items/$id";
$menuItem = $this->sendRequest($base_url);
return $menuItem->response;
}
}
?>
This is the error I get when executing the first file:
Fatal error: Class 'Mmjmenu' not found in /home/...(my directory).../mmtest.php on line 4

Categories