gotowebinar api php - php

I tried to find out gotowebinar api in php but didn't get it. So, I have tried to write a simple class which can be useful. It does authentication which is same for gotowebinar, gotomeeting and rest. It fetches the upcoming webinar, all webinars, single webinar information, registrants fields and also create registrant. Now you all can enhance it as you want. Any suggestion would be much appericiated.
help.txt
1) First change the GOTO_WEBINAR_API_KEY in
gotoWebinarClass.php to your appication key.
2) Then change the
REDIRECT_URL_AFTER_AUTHENTICATION in
authorize.php. It is a url where one should be redirected after
authentication.
3) Execute authorize.php.
4) After you autheticate,
it would take you to
REDIRECT_URL_AFTER_AUTHENTICATION with "code" in the query
string.
5) Copy that code and execute the authorize.php again with ?
code='your_code' in the query string.
6) If everything goes fine, we will get the token and we will set into session and be redirected to get-all-webinars.php
which fetches user's all webinars.
This class is not complete, I have laid down the basic
foundation, now you can keep on adding the other functions. Any
suggestion from your side would be much appriciated. Thanks.
gotoWebinarClass.php
<?php
define('GOTO_WEBINAR_API_KEY','your gotowebinar application key');
class OAuth_En{
protected $_accessToken;
protected $_userId;
protected $_organizerKey;
protected $_refreshToken;
protected $_expiresIn;
public function getAccessToken(){
return $this->_accessToken;
}
public function setAccessToken($token){
$this->_accessToken = $token;
}
public function getUserId(){
return $this->_userId;
}
public function setUserId($id){
$this->_userId = $id;
}
public function getOrganizerKey(){
return $this->_organizerKey;
}
public function setOrganizerKey($key){
$this->_organizerKey = $key;
}
public function getRefreshToken(){
return $this->_refreshToken;
}
public function setRefreshToken($token){
$this->_refreshToken = $token;
}
public function getExpiresIn(){
return $this->_expiresIn;
}
public function setExpiresIn($expiresIn){
$this->_expiresIn = $expiresIn;
}
}
class OAuth_Db{
function getToken(){
}
}
class OAuth{
protected $_redirectUrl;
protected $_OAuthEnObj;
protected $_curlHeader = array();
protected $_apiResponse;
protected $_apiError;
protected $_apiErrorCode;
protected $_apiRequestUrl;
protected $_apiResponseKey;
protected $_accessTokenUrl;
protected $_webinarId;
protected $_registrantInfo = array();
protected $_apiRequestType;
protected $_apiPostData;
public function __construct(OAuth_En $oAuthEn){
$this->_OAuthEnObj = $oAuthEn;
}
public function getOAuthEntityClone(){
return clone $this->_OAuthEnObj;
}
public function getWebinarId(){
return $this->_webinarId;
}
public function setWebinarId($id){
$id = (int)$id;
$this->_webinarId = empty($id) ? 0 : $id;
}
public function setApiErrorCode($code){
$this->_apiErrorCode = $code;
}
public function getApiErrorCode(){
return $this->_apiErrorCode;
}
public function getApiAuthorizationUrl(){
return 'https://api.citrixonline.com/oauth/authorize?client_id='.GOTO_WEBINAR_API_KEY.'&redirect_uri='.$this->getRedirectUrl();
}
public function getApiKey(){
return GOTO_WEBINAR_API_KEY;
}
public function getApiRequestUrl(){
return $this->_apiRequestUrl;
}
public function setApiRequestUrl($url){
$this->_apiRequestUrl = $url;
}
public function setRedirectUrl($url){
$this->_redirectUrl = urlencode($url);
}
public function getRedirectUrl(){
return $this->_redirectUrl;
}
public function setCurlHeader($header){
$this->_curlHeader = $header;
}
public function getCurlHeader(){
return $this->_curlHeader;
}
public function setApiResponseKey($key){
$this->_apiResponseKey = $key;
}
public function getApiResponseKey(){
return $this->_apiResponseKey;
}
public function setRegistrantInfo($arrInfo){
$this->_registrantInfo = $arrInfo;
}
public function getRegistrantInfo(){
return $this->_registrantInfo;
}
public function authorizeUsingResponseKey($responseKey){
$this->setApiResponseKey($responseKey);
$this->setApiTokenUsingResponseKey();
}
protected function setAccessTokenUrl(){
$url = 'https://api.citrixonline.com/oauth/access_token?grant_type=authorization_code&code={responseKey}&client_id={api_key}';
$url = str_replace('{api_key}', $this->getApiKey(), $url);
$url = str_replace('{responseKey}', $this->getApiResponseKey(), $url);
$this->_accessTokenUrl = $url;
}
protected function getAccessTokenUrl(){
return $this->_accessTokenUrl;
}
protected function resetApiError(){
$this->_apiError = '';
}
public function setApiTokenUsingResponseKey(){
//set the access token url
$this->setAccessTokenUrl();
//set the url where api should go for request
$this->setApiRequestUrl($this->getAccessTokenUrl());
//make request
$this->makeApiRequest();
if($this->hasApiError()){
echo $this->getApiError();
}else{
//if api does not have any error set the token
echo $this->getResponseData();
$responseData = json_decode($this->getResponseData());
$this->_OAuthEnObj->setAccessToken($responseData->access_token);
$this->_OAuthEnObj->setOrganizerKey($responseData->organizer_key);
$this->_OAuthEnObj->setRefreshToken($responseData->refresh_token);
$this->_OAuthEnObj->setExpiresIn($responseData->expires_in);
}
}
function hasApiError(){
return $this->getApiError() ? 1 : 0;
}
function getApiError(){
return $this->_apiError;
}
function setApiError($errors){
return $this->_apiError = $errors;
}
function getApiRequestType(){
return $this->_apiRequestType;
}
function setApiRequestType($type){
return $this->_apiRequestType = $type;
}
function getResponseData(){
return $this->_apiResponse;
}
function setApiPostData($data){
return $this->_apiPostData = $data;
}
function getApiPostData(){
return $this->_apiPostData;
}
function makeApiRequest(){
$header = array();
$this->getApiRequestUrl();
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_URL, $this->getApiRequestUrl());
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
if($this->getApiRequestType()=='POST'){
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->getApiPostData());
}
if($this->getCurlHeader()){
$headers = $this->getCurlHeader();
}else{
$headers = array(
"HTTP/1.1",
"Content-type: application/json",
"Accept: application/json",
"Authorization: OAuth oauth_token=".$this->_OAuthEnObj->getAccessToken()
);
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$data = curl_exec($ch);
$validResponseCodes = array(200,201,409);
$responseCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$this->resetApiError();
if (curl_errno($ch)) {
$this->setApiError(array(curl_error($ch)));
} elseif(!in_array($responseCode, $validResponseCodes)){
if($this->isJsonString($data)){
$data = json_decode($data);
}
$this->setApiError($data);
$this->setApiErrorCode($responseCode);
}else {
$this->_apiResponse = $data;
$_SESSION['gotoApiResponse'] = $this->getResponseData();
curl_close($ch);
}
}
function isAuthorizationRequiredAgain(){
$arrAuthorizationRequiredCodes = array(400,401,403,500);
$isAuthRequired = 0;
$error = $this->getApiError();
$responseCode = $this->getApiErrorCode();
//we might have to add more exception in this condition
if(in_array($responseCode, $arrAuthorizationRequiredCodes)){
if($responseCode==400 && is_object($error)){ //because for 400 error sometime one needs to authenticate again
foreach($error as $single){
$pos = strpos($single,'Authorization');
if($pos!==false){
$isAuthRequired = 1;
}
}
}else{
$isAuthRequired = 1;
}
}
return $isAuthRequired;
}
function getWebinars(){
$url = 'https://api.citrixonline.com/G2W/rest/organizers/'.$this->_OAuthEnObj->getOrganizerKey().'/webinars';
$this->setApiRequestUrl($url);
$this->setApiRequestType('GET');
$this->makeApiRequest();
if($this->hasApiError()){
return null;
}
$webinars = json_decode($this->getResponseData());
return $webinars;
}
function getWebinar(){
if(!$this->getWebinarId()){
$this->setApiError(array('Webinar id not provided'));
return null;
}
$this->setApiRequestType('GET');
$url = 'https://api.citrixonline.com/G2W/rest/organizers/'.$this->_OAuthEnObj->getOrganizerKey().'/webinars/'.$this->getWebinarId();
$this->setApiRequestUrl($url);
$this->makeApiRequest();
if($this->hasApiError()){
return null;
}
$webinar = json_decode($this->getResponseData());
return $webinar;
}
function getUpcomingWebinars(){
$url = 'https://api.citrixonline.com/G2W/rest/organizers/'.$this->_OAuthEnObj->getOrganizerKey().'/upcomingWebinars';
$this->setApiRequestUrl($url);
$this->setApiRequestType('GET');
$this->makeApiRequest();
if($this->hasApiError()){
return null;
}
$webinars = json_decode($this->getResponseData());
return $webinars;
}
function createRegistrant(){
if(!$this->getWebinarId()){
$this->setApiError(array('Webinar id not provided'));
return null;
}
if(!$this->getRegistrantInfo()){
$this->setApiError(array('Registrant info not provided'));
return null;
}
$this->setApiRequestType('POST');
$this->setApiPostData(json_encode($this->getRegistrantInfo()));
$url = 'https://api.citrixonline.com/G2W/rest/organizers/'.$this->_OAuthEnObj->getOrganizerKey().'/webinars/'.$this->getWebinarId().'/registrants';
$this->setApiRequestUrl($url);
$this->makeApiRequest();
if($this->hasApiError()){
return null;
}
$webinar = json_decode($this->getResponseData());
return $webinar;
}
function getWebinarRegistrantsFields(){
if(!$this->getWebinarId()){
$this->setApiError(array('Webinar id not provided'));
return null;
}
$url = 'https://api.citrixonline.com/G2W/rest/organizers/'.$this->_OAuthEnObj->getOrganizerKey().'/webinars/'.$this->getWebinarId().'/registrants/fields';
$this->setApiRequestUrl($url);
$this->setApiRequestType('GET');
$this->makeApiRequest();
if($this->hasApiError()){
return null;
}
$registrantFields = json_decode($this->getResponseData());
return $registrantFields;
}
function isJsonString($string){
$isJson = 0;
$decodedString = json_decode($string);
if(is_array($decodedString) || is_object($decodedString))
$isJson = 1;
return $isJson;
}
}
Authorize.php
<?php
include_once "gotoWebinarClass.php";
define('REDIRECT_URL_AFTER_AUTHENTICATION','http://url where we want to redirect'); //this is the url where your get token code would be written.
session_start();
$obj = new OAuth_En();
$oauth = new OAuth($obj);
if(!isset($_GET['code'])){
goForAuthorization();
}else{ //when user authenticates and redirect back to application redirect url, get the token
$oauth->authorizeUsingResponseKey($_GET['code']);
if(!$oauth->hasApiError()){
$objOAuthEn = $oauth->getOAuthEntityClone();
$_SESSION['oauthEn'] = serialize($objOAuthEn);
header('Location: get-all-webinars.php');
}
}
//this function has been used for getting the key using which we can get the access token and organizer key
function goForAuthorization(){
global $oauth;
$oauth->setRedirectUrl(REDIRECT_URL_AFTER_AUTHENTICATION);
$url = $oauth->getApiAuthorizationUrl();
header('Location: '.$url);
}
get-all-webinars.php
<?php
include_once "gotoWebinarClass.php";
session_start();
$obj = unserialize($_SESSION['oauthEn']);
/*
this can be used to fetch the stored access token key and organizer key from database and use it without asking the authetication from user again
$obj = new OAuth_En();
$obj->setAccessToken('token');
$obj->setOrganizerKey('organizer key');
*/
$oauth = new OAuth($obj);
$webinars = $oauth->getWebinars();
echo '<pre>';
if(!$oauth->hasApiError()){
print_r($webinars);
}else{
print_r($oauth->getApiError());
}
exit;
/*$webinars = $oauth->getUpcomingWebinars();
if(!$oauth->hasApiError()){
print_r($webinars);
}else{
print_r($oauth->getApiError());
}
exit;
$registrantInfo = array(
"firstName"=>"ashish",
"lastName"=>"mehta",
"email"=>"test#test.com",
);
$oauth->setWebinarId(525120321);
$oauth->setRegistrantInfo($registrantInfo);
$res = $oauth->createRegistrant();
echo $oauth->getApiErrorCode();
if(!$oauth->hasApiError()){
print_r($res);
}else{
echo 'error';
print_r($oauth->getApiError());
}
exit;
$oauth->setWebinarId(525120321);
$webinar = $oauth->getWebinar();
if(!$oauth->hasApiError()){
print_r($webinar);
}else{
print_r($oauth->getApiError());
echo $oauth->getApiErrorCode();
}
*/

Suggestion #1: AMAZING CLASS! :)
Suggestion #2: Because I didn't really have to do any actual "work" to implement your class, I had some trouble with submitting custom question responses when creating a registrant.
This is because if you use custom fields, you need to add an additional parameter to the header:
Accept: application/vnd.citrix.g2wapi-v1.1+json
Other than that this class is MONEY IN THE BANK! Thanks for this you saved me a TON of time (and only had to focus on one problem instead of 30).

I've been trying this class and it is really helpful and great. :)
The only problem I am encountering is that when it redirects to GotoWebinar, it would first ask me to enter my username and password before it returns the Array containing the upcoming webinars.
Is there a way to auto-login to GotoWebinar by using POST or any other code so that I won't have to manually enter the username and password? Here is my current code for the authorize.php.
I tried the Direct Login, https://developer.citrixonline.com/page/direct-login. However, it would return the information of my user account. But it would not redirect to the page that will generate the webinars.
Thanks a lot!

Related

Too Many redirects in Facebook Login with Phalcon

We have a problem with facebook authentication. We use phalcon and we have the authentication process with the php-sdk-v4 plugin. When we try to login, we have the error of too many redirects. Our website is https://app.wowego.com/register. some help?
CODE:
FILE: AUTH.PHP
public function loginWithFacebook()
{
$di = $this->getDI();
$facebook = new FacebookConnector($di);
$facebookUser = $facebook->getUser();
if (!$facebookUser) {
$scope = [
'scope' => 'email,user_birthday,user_location',
];
return $this->response->redirect($facebook->getLoginUrl($scope), true);
}
try {
return $this->authenticateOrCreateFacebookUser($facebookUser);
} catch (\FacebookApiException $e) {
$di->logger->begin();
$di->logger->error($e->getMessage());
$di->logger->commit();
$facebookUser = null;
}
}
FACEBOOKCONNECTOR.PHP
public function __construct($di)
{
$this->di = $di;
$fbConfig = $di->get('config')->pup->connectors->facebook;
$protocol = strtolower(substr($_SERVER['SERVER_PROTOCOL'], 0, strpos($_SERVER['SERVER_PROTOCOL'], '/'))).'://';
$protocol="https://";
if (isset($fbConfig['route'])) {
$this->url = $protocol.$_SERVER['HTTP_HOST'].$fbConfig['route'];
} else {
$this->url = $protocol.$_SERVER['HTTP_HOST'].'/usercontrol/loginwithfacebook';
}
//echo $this->url;die();
FacebookSession::setDefaultApplication($fbConfig->appId, $fbConfig->secret);
}
public function getLoginUrl($scope = [])
{
$this->helper = new FacebookRedirectLoginHelper($this->url);
return $this->helper->getLoginUrl($scope);
}
/**
* Get facebook user details.
*
* #return unknown|bool
*/
public function getUser()
{
try {
$this->helper = new FacebookRedirectLoginHelper($this->url);
$this->fb_session = $this->helper->getSessionFromRedirect();
} catch (FacebookRequestException $ex) {
$this->di->get('flashSession')->error($ex->getMessage());
} catch (\Exception $ex) {
$this->di->get('flashSession')->error($ex->getMessage());
}
if ($this->fb_session) {
$request = new FacebookRequest($this->fb_session, 'GET', '/me?fields=id,first_name,last_name,email');
$response = $request->execute();
$fb_user = $response->getGraphObject()->asArray();
return $fb_user;
}
return false;
}
USERCONTROLLER.PHP
public function loginwithfacebookAction()
{
try {
//echo "dentro del try";
$this->view->disable();
$fopen = fopen('../logs/loginWithFacebook.log');
fwrite( $this->auth->loginWithFacebook() , $fopen );
fclose( $fopen );
return $this->auth->loginWithFacebook();
} catch(AuthException $e) {
$this->flash->error('There was an error connectiong to Facebook.');
}
}
I couldn't test it, but it seems to be circular: in facebookconnector.php the if leads to the same call to the static function FacebookSession::setDefaultApplication. You may try:
if (isset($fbConfig['route'])) {
$this->url = $protocol.$_SERVER['HTTP_HOST'].$fbConfig['route'];
FacebookSession::setDefaultApplication($fbConfig->appId, $fbConfig->secret);
} else {
$this->url = $protocol.$_SERVER['HTTP_HOST'].'/usercontrol/loginwithfacebook';
return $this->response->redirect($this->url);
}

Load a PHP class multiple times

I've created a class which has multiple private an public functions and an construct function. It's an client to connect to the vCloud API. I want two objects loaded with different initiations of this class. They have to exist in parallel.
$vcloud1 = new vCloud(0, 'system');
$vcloud2 = new vCloud(211, 'org');
When I check the output of $vcloud1 it's loaded with info of $vcloud2. Is this correct, should this happen? Any idea how I can load a class multiple times and isolate both class loads?
This is part of my class, it holds the most important functions. Construct with user and org to login to. If info in the DB exists, then we authenticate with DB info, else we authenticate with system level credentials. So I would like to have two class loads, one with the user level login and one with system level login.
class vCloud {
private $client;
private $session_id;
private $sdk_ver = '7.0';
private $system_user = 'xxxxxxxxxxx';
private $system_password = 'xxxxxxxxxxxxxxxxx';
private $system_host = 'xxxxxxxxxxxxx';
private $org_user;
private $org_password;
private $org_host;
private $base_url;
public function __construct($customerId, $orgName) {
if ($this->vcloud_get_db_info($customerId)) {
$this->base_url = 'https://' . $this->org_host . '/api/';
$this->base_user = $this->org_user . "#" . $orgName;
$this->base_password = $this->org_password;
} else {
$this->base_url = 'https://' . $this->system_host . '/api/';
$this->base_user = $this->system_user;
$this->base_password = $this->system_password;
}
$response = \Httpful\Request::post($this->base_url . 'sessions')
->addHeaders([
'Accept' => 'application/*+xml;version=' . $this->sdk_ver
])
->authenticateWith($this->base_user, $this->base_password)
->send();
$this->client = Httpful\Request::init()
->addHeaders([
'Accept' => 'application/*+xml;version=' . $this->sdk_ver,
'x-vcloud-authorization' => $response->headers['x-vcloud-authorization']
]);
Httpful\Request::ini($this->client);
}
public function __destruct() {
$deleted = $this->vcloud_delete_session();
if (!$deleted) {
echo "vCloud API session could not be deleted. Contact administrator if you see this message.";
}
}
private function vcloud_delete_session() {
if (isset($this->client)) {
$response = $this->client::delete($this->base_url . 'session')->send();
return $response->code == 204;
} else {
return FALSE;
}
}
public function vcloud_get_db_info($customerId) {
global $db_handle;
$result = $db_handle->runQuery("SELECT * from vdc WHERE customer=" . $customerId);
if ($result) {
foreach ($result as $row) {
if ($row['org_host'] != "") {
$this->org_user = $row['org_user'];
$this->org_password = $row['org_password'];
$this->org_host = $row['org_host'];
return true;
} else {
return false;
}
}
} else {
return false;
}
}
public function vcloud_get_admin_orgs() {
$response = $this->client::get($this->base_url . 'query?type=organization&sortAsc=name&pageSize=100')->send();
return $response->body;
}
}
$vcloud1 = new vCloud('user1', 'system');
$vcloud2 = new vCloud('user2', 'org');
This is enough to make two instances which are not related.
I suppose your database is returning the same results.
How about providing a custom equals method to each object that retreives an instance of vCloud?
class vCloud {
//Other definitions
public function equals(vCloud $other){
//Return true if $other is same as this class (has same client_id etc etc)
}
}
So you just need to do as the code says:
$vcloud1 = new vCloud('user1', 'system');
$vcloud2 = new vCloud('user2', 'org');
if($vcloud1.equals($vclous2)){
echo "Entries are the same";
} else {
echo "Entries are NOT the same";
}
Also you may need to have various getter and setter methods into your class definitions. What is needed for you to do is to fill the equals method.

PHP create override function only for certain parts of the original function

Hi there and welcome to my first official problem! I'm trying to override a function, but only certain parts. The function i want to override, is different in several versions of the open source CMS system. The specific parts which i need to change in order for this to work, are the same in all of those versions.
The override has to work with all of those different versions of the CMS system.
I can't use PECL (apd) package or any other external PHP package for this. And as far i know and could find in the PHP manual, there is no function for this.
So, for example:
We have the different CMS system versions: 1, 2 and 3.
And we would have a original function like this one (THIS IS JUST AN EXAMPLE AND NOT THE ACTUAL FUNCTION I NEED CHANGED), which can only be used for version 3. Certain parts are the same in all versions, and some parts are different:
public function createAccessToken($body = false)
{
if (!$body) { //this is different
$body = 'grant_type=client_credentials'; //this is different
}
$this->action = 'POST'; //this is different
$this->endpoint = 'v1/oauth2/token'; //this is different
$response = $this->makeCall($body, "application/json", true); //this is different
if (!isset($response->access_token)) { //this is THE SAME
return false; //this is THE SAME
}
$this->token = $response->access_token; //this is different
return true; //this is different
}
And this is what i would like to change for all of those versions:
public function createAccessToken($body = false)
{
if (!$body) {
$body = 'grant_type=client_credentials';
}
$this->action = 'POST';
$this->endpoint = 'v1/oauth2/token';
$response = $this->makeCall($body, "application/json", true);
if (isset($response->access_token)) { //IT'S CHANGED! THE -> ! IS GONE
return false;
}
$this->token = $response->access_token;
return true;
}
But the function above (which has changed), will only work with version 3 of the CMS system.
Therefore, is there any way i can only override the specific part i need to change and "get" the code which doesn't have to change some other way so the function would still be executed? So again:
public function createAccessToken($body = false)
{
//some way to get the code above the part i need to change, untill i get to the part which needs to be changed. So the override "takes over" from here.
if (isset($response->access_token)) { //IT'S CHANGED! THE -> ! IS GONE
return false;
}
//some way to get the rest of the code and have the function continue agian
}
Hope you can help me out on this.
You could create your own middle layer. This is assuming you have access to some variable that defines your current VERSION.
public function createAccessToken($body = false) {
if (VERSION == 1 || VERSION == 2) { createAccessTokenOld($body); }
else { createAccessTokenNew($body); }
}
public function createAccessTokenOld($body = false)
{
if (!$body) {
$body = 'grant_type=client_credentials';
}
$this->action = 'POST';
$this->endpoint = 'v1/oauth2/token';
$response = $this->makeCall($body, "application/json", true);
if (!isset($response->access_token)) { //IT'S CHANGED! THE -> ! IS GONE
return false;
}
$this->token = $response->access_token;
return true;
}
public function createAccessTokenNew($body = false)
{
if (!$body) {
$body = 'grant_type=client_credentials';
}
$this->action = 'POST';
$this->endpoint = 'v1/oauth2/token';
$response = $this->makeCall($body, "application/json", true);
if (isset($response->access_token)) { //IT'S CHANGED! THE -> ! IS GONE
return false;
}
$this->token = $response->access_token;
return true;
}
You could also do it with a bit more code reuse:
public function createAccessToken($body = false) {
if (VERSION == 1 || VERSION == 2) { createAccessToken($body, true); }
else { createAccessToken($body, false); }
}
public function createAccessToken($body = false, $isOld = false)
{
if (!$body) {
$body = 'grant_type=client_credentials';
}
$this->action = 'POST';
$this->endpoint = 'v1/oauth2/token';
$response = $this->makeCall($body, "application/json", true);
if ($isOld) { if (!isset($response->access_token)) { return false; } }
else { if (isset($response->access_token)) { return false; } }
$this->token = $response->access_token;
return true;
}

hitbox.tv api can't update_live_media

Currently I doing a project by using hitbox.tv api plug in to my website. I would like to update my video title during when I'm broadcasting live stream. I using guzzle 6 to send http request to api end point, the following is my code
myGuzzle.php
<?php
namespace myGuzzle;
require __DIR__.'/../vendor/autoload.php';
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
class myGuzzle{
public $params;
public $method;
public $endpoint;
public $body;
public $status;
public $errorJson;
function response($params=[],$method,$endpoint) {
$this->params = $params;
$this->method = $method;
$this->endpoint = $endpoint;
$client = new Client();
try{
$response = $client->request($this->method, $this->endpoint,['json' => $this->params]);
$this->body = $response->getBody();
$this->status = $response->getStatusCode();
}
catch(ClientException $e){
$this->body = $e->getMessage();
$this->status = $e->getCode();
$this->errorJson = $e->getResponse()->getBody();
}
}
function getStatus(){
return $this->status;
}
function getBody(){
return $this->body;
}
function getErrorJson(){
return $this->errorJson;
}
}
updateLiveMedia.php
namespace models;
use myGuzzle\myGuzzle;
class updateLiveMedia {
protected $username;
protected $access_token;
public $media_user_name;
public $media_id;
public $media_category_id;
public $media_live_delay;
public $media_hidden;
public $media_recording;
public $media_mature;
public $media_hosted_name;
public $media_countries = [];
public $media_status;
public $media_description;
function __construct($username,$acessToken) {
$this->username = $username;
$this->access_token = $acessToken;
$this->media_countries = ["EN"];
$this->media_category_id = '0';
$this->media_recording = "1";
$this->media_mature ='0';
$this->media_user_name = $this->username;
$this->media_hosted_name = "on";
$this->media_live_delay='2';
$this->media_hidden = '0';
}
/*
* Parameters function(title,descritption) or
* Parameters function(title,description,countries).
*/
function update($opts=[]){
if(is_array($opts)){
foreach($opts as $key=>$value){
$this->$key = $value;
}
}
$myGuzzle = new myGuzzle;
$uri = "https://api.hitbox.tv/media/live/".$this->username."?authToken=".$this->access_token;
$params = ["livestream"=>[
[
"media_user_name"=>$this->username,
"media_id"=>$this->media_id,
"media_category_id"=>$this->media_category_id,
"media_live_delay"=>$this->media_live_delay,
"media_hidden"=>$this->media_hidden,
"media_recording"=>$this->media_recording,
"media_mature"=>$this->media_mature,
"media_hosted_name"=>$this->media_hosted_name,
"media_countries"=> $this->media_countries,
"media_status"=>$this->media_status,
"media_description"=>$this->media_description,
]
]];
$myGuzzle->response($params,"PUT",$uri);
return $myGuzzle->getBody();
if($myGuzzle->getStatus() == 200){
return true;
}
return false;
}
}
run update() return the following result
{"success":true,"error":false,"message":"host_mode_enabled"}
According the documentation provided by hitbox.tv (http://developers.hitbox.tv/#update-live-media) should return something like the following
{
"livestream": [
{
"media_user_name": "masta",
"media_id": "1",
"media_category_id": "447",
"media_live_delay": "0",
"media_hidden": "0",
"media_recording": "1",
"media_mature": "0",
"media_countries": [
"EN"
],
"media_status": "This is a stream title!",
"media_description_md": null
}
]
}
The API documentation for update-live-media describes the response to be expected only when the hosting flag is not being modified.
The other cases would return different types of answers:
When host mode is being enabled
{"success":true,"error":false,"message":"host_mode_enabled"}
When host mode is being disabled
{"success":true,"error":false,"message":"host_mode_disabled"}
And an error would also return something different than the documentation, for example:
If the authToken/media_id is invalid or there is insufficient permissions
{"success":true,"error":false,"message":"auth_required_token"} or
{"success":true,"error":false,"message":"auth_required"}
When you are updating the hosting mode, you won't be updating any other information (title). Just try to leave out media_hosted_name from your query, and watch how description and titles get updated. Users (and chat bots) then can see the updated information.
Let me know if you still are having any trouble with the API. I would need a specific example and could help you further.

save form field in component params joomla

I am using joomla 2.5, I am working on custom component of joomla . I have created the form in backend admin page. what i need is , i want to save the post data of form in params row of that component in database of #_extensions.
Here is my tables/component.php
<?php defined('_JEXEC') or die('Restricted access');
jimport('joomla.database.table');
class componentTablecomponent extends JTable {
function __construct(&$db)
{
parent::__construct('#__extensions', 'extension_id', $db);
}
public function bind($array, $ignore = '')
{
if (isset($array['params']) && is_array($array['params']))
{
// Convert the params field to a string.
$parameter = new JRegistry;
$parameter->loadArray($array['params']);
$array['params'] = (string)$parameter;
}
return parent::bind($array, $ignore);
}
public function load($pk = null, $reset = true)
{
if (parent::load($pk, $reset))
{
// Convert the params field to a registry.
$params = new JRegistry;
$params->loadJSON($this->params);
$this->params = $params;
return true;
}
else
{
return false;
}
} public function store() {
parent::store(null);
}
}
Instead of saving the $data in params row of that component . This code is creating new empty rows in that table(data is saving in those params field).
Here is my save() function in controllers/component.php
public function save()
{
// Check for request forgeries.
JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN'));
// Check if the user is authorized to do this.
if (!JFactory::getUser()->authorise('core.admin'))
{
`JFactory::getApplication()->redirect('index.php',JText::_('JERROR_ALERTNOAUTHOR'));`
return;
}
// Initialise variables.
$app = JFactory::getApplication();
$model = $this->getModel('component');
$form = $model->getForm();
$data = JRequest::getVar('jform', array(), 'post', 'array');
print_r($data);
// Validate the posted data.
$return = $model->validate($form, $data);
// Check for validation errors.
if ($return === false)
{
// Get the validation messages.
$errors = $model->getErrors();
// Push up to three validation messages out to the user.
for ($i = 0, $n = count($errors); $i < $n && $i < 3; $i++) {
if ($errors[$i] instanceof Exception) {
$app->enqueueMessage($errors[$i]->getMessage(), 'warning');
} else {
$app->enqueueMessage($errors[$i], 'warning');
}
}
// Redirect back to the edit screen.
$this->setRedirect(JRoute::_('somelink',false));
return false;
}
// Attempt to save the configuration.
$data = $return;
$return = $model->save($data);
// Check the return value.
if ($return === false)
{
// Save failed, go back to the screen and display a notice.
$message = JText::sprintf('JERROR_SAVE_FAILED', $model->getError());
$this->setRedirect('index.php/somelink','error');
return false;
}
// Set the success message.
$message = JText::_('COM_CONFIG_SAVE_SUCCESS');
// Set the redirect based on the task.
switch ($this->getTask())
{
case 'apply':
$this->setRedirect('somelink',$message);
break;
case 'cancel':
case 'save':
default:
$this->setRedirect('index.php', $message);
break;
}
return true;
}
models/component.php
public function save($data) {
parent::save($data);
return true;
}
I thinks these codes are enough . I can add more codes if you need.
If you want to store params in the extension table, why not just use com_config for it?
See http://docs.joomla.org/J2.5:Developing_a_MVC_Component/Adding_configuration
Then you don't have to do anything besides creating the config.xml and adding a link to the config options in the toolbar.
I have come up with a solution . it works for me . By using this method you can control save () functions i.e. you can run your custom php scripts on save, apply toolbar buttons.
I copied save(),save($data), store($updateNulls = false) functions from com_config component , I have copied the layout from component view . Removed the buttons. Added toolbar buttons in .html.php file.
controllers/mycomponent.php
<?php
defined('_JEXEC') or die;
class componentControllermycomponent extends JControllerLegacy {
function __construct($config = array())
{
parent::__construct($config);
// Map the apply task to the save method.
$this->registerTask('apply', 'save');
}
function save()
{
// Check for request forgeries.
JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN'));
// Set FTP credentials, if given.
JClientHelper::setCredentialsFromRequest('ftp');
// Initialise variables.
$app = JFactory::getApplication();
$model = $this->getModel('mymodel');
$form = $model->getForm();
$data = JRequest::getVar('jform', array(), 'post', 'array');
$id = JRequest::getInt('id');
$option = 'com_mycomponent';
// Check if the user is authorized to do this.
if (!JFactory::getUser()->authorise('core.admin', $option))
{
JFactory::getApplication()->redirect('index.php', JText::_('JERROR_ALERTNOAUTHOR'));
return;
}
// Validate the posted data.
$return = $model->validate($form, $data);
// Check for validation errors.
if ($return === false) {
// Get the validation messages.
$errors = $model->getErrors();
// Push up to three validation messages out to the user.
for ($i = 0, $n = count($errors); $i < $n && $i < 3; $i++) {
if ($errors[$i] instanceof Exception) {
$app->enqueueMessage($errors[$i]->getMessage(), 'warning');
} else {
$app->enqueueMessage($errors[$i], 'warning');
}
}
// Save the data in the session.
$app->setUserState('com_iflychat.config.global.data', $data);
// Redirect back to the edit screen.
$this->setRedirect(JRoute::_('index.php?option=com_mycomponent&view=component&component='.$option.'&tmpl=component', false));
return false;
}
// Attempt to save the configuration.
$data = array(
'params' => $return,
'id' => $id,
'option' => $option
);
// print_r($data);
$return = $model->save($data);
// Check the return value.
if ($return === false)
{
// Save the data in the session.
$app->setUserState('com_config.config.global.data', $data);
// Save failed, go back to the screen and display a notice.
$message = JText::sprintf('JERROR_SAVE_FAILED', $model->getError());
$this->setRedirect('index.php?option=com_mycomponent&view=component&component='.$option.'&tmpl=component', $message, 'error');
return false;
}
// Set the redirect based on the task.
switch ($this->getTask())
{
case 'apply':
$message = JText::_('COM_MYCOMPONENT_SAVE_SUCCESS');
print_r($data);
$this->setRedirect('index.php?option=com_mycomponent&view=myview&layout=edit', $message);
break;
case 'save':
default:
$this->setRedirect('index.php');
break;
}
return true;
}
function cancel()
{
$this->setRedirect('index.php');
}
}
models/mymodel.php
<?php
defined('_JEXEC') or die;
jimport('joomla.application.component.modelform');
class componentModelmymodel extends JModelForm {
protected $event_before_save = 'onConfigurationBeforeSave';
protected $event_after_save = 'onConfigurationAfterSave';
public function getForm($data = array(), $loadData = true){
// Get the form.
$form = $this->loadForm('com_mycomponent.form', 'config',
array('control' => 'jform', 'load_data' => $loadData));
if (empty($form)){
return false;
}
return $form;
}
public function save($data)
{
$dispatcher = JDispatcher::getInstance();
$table = JTable::getInstance('extension');
$isNew = true;
// Save the rules.
if (isset($data['params']) && isset($data['params']['rules']))
{
$rules = new JAccessRules($data['params']['rules']);
$asset = JTable::getInstance('asset');
if (!$asset->loadByName($data['option']))
{
$root = JTable::getInstance('asset');
$root->loadByName('root.1');
$asset->name = $data['option'];
$asset->title = $data['option'];
$asset->setLocation($root->id, 'last-child');
}
$asset->rules = (string) $rules;
if (!$asset->check() || !$asset->store())
{
$this->setError($asset->getError());
return false;
}
// We don't need this anymore
unset($data['option']);
unset($data['params']['rules']);
}
// Load the previous Data
if (!$table->load($data['id']))
{
$this->setError($table->getError());
return false;
}
unset($data['id']);
// Bind the data.
if (!$table->bind($data))
{
$this->setError($table->getError());
return false;
}
// Check the data.
if (!$table->check())
{
$this->setError($table->getError());
return false;
}
// Trigger the oonConfigurationBeforeSave event.
$result = $dispatcher->trigger($this->event_before_save, array($this->option . '.' . $this->name, $table, $isNew));
if (in_array(false, $result, true))
{
$this->setError($table->getError());
return false;
}
// Store the data.
if (!$table->store())
{
$this->setError($table->getError());
return false;
}
// Clean the component cache.
$this->cleanCache('_system');
// Trigger the onConfigurationAfterSave event.
$dispatcher->trigger($this->event_after_save, array($this->option . '.' . $this->name, $table, $isNew));
return true;
}
function getComponent()
{
$result = JComponentHelper::getComponent('com_mycomponent');
return $result;
}
}
tables/mycomponent.php
<?php
// No direct access
defined('_JEXEC') or die('Restricted access');
// import Joomla table library
jimport('joomla.database.table');
/**
* Hello Table class
*/
class componentTableMycomponent extends JTable
{
function __construct(&$db)
{
parent::__construct('#__extensions', 'extension_id', $db);
}
public function bind($array, $ignore = '')
{
if (isset($array['params']) && is_array($array['params']))
{
// Convert the params field to a string.
$parameter = new JRegistry;
$parameter->loadArray($array['params']);
$array['params'] = (string)$parameter;
}
return parent::bind($array, $ignore);
}
public function load($pk = null, $reset = true)
{
if (parent::load($pk, $reset))
{
// Convert the params field to a registry.
$params = new JRegistry;
$params->loadJSON($this->params);
$this->params = $params;
return true;
}
else
{
return false;
}
}
public function store($updateNulls = false)
{
// Transform the params field
if (is_array($this->params)) {
$registry = new JRegistry();
$registry->loadArray($this->params);
$this->params = (string)$registry;
}
$date = JFactory::getDate();
$user = JFactory::getUser();
if ($this->id) {
// Existing item
$this->modified = $date->toSql();
$this->modified_by = $user->get('id');
} else {
// New newsfeed. A feed created and created_by field can be set by the user,
// so we don't touch either of these if they are set.
if (!intval($this->created)) {
$this->created = $date->toSql();
}
if (empty($this->created_by)) {
$this->created_by = $user->get('id');
}
}
// Verify that the alias is unique
$table = JTable::getInstance('Yourinstance', 'mycomponentTable');
if ($table->load(array('alias'=>$this->alias, 'catid'=>$this->catid)) && ($table->id != $this->id || $this->id==0)) {
$this->setError(JText::_('COM_CONTACT_ERROR_UNIQUE_ALIAS'));
return false;
}
// Attempt to store the data.
return parent::store($updateNulls);
}
}
Note : your config.xml file should be in models/forms folder.

Categories