Here I am using google drive to backup my data on drive and for that I wrote a script which i want to run through cronjob. but it needs access_token to access google drive. I am keeping access token in my db and providing it to backup file but that token is not getting updated through cronjob . but when I am running it on browser then working fine. I want to update token through cronjob which didn't get updated.
oauth2callback.php
<?php
require_once '../inc/google/vendor/autoload.php';
require_once '../classes/dbconnection.class.php';
$client = new Google_Client();
$client->setAuthConfigFile('client_secret.json');
$client->setAccessType("offline");
$client->setRedirectUri('https://******/controllers/oauth2callback.php');
$client->addScope(Google_Service_Drive::DRIVE);
if (! isset($_GET['code'])) {
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
$client->authenticate($_GET['code']);
$token_data = $client->getAccessToken();
update_token($token_data);
$redirect_uri = 'https://******/controllers/db_backup.php?action=backup';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
function update_token($data){
$db = new dbconnection;
$conn = $db->connect('pf_central');
$update_token = $conn->query("UPDATE google_drive_token SET access_token = '{$data['access_token']}', token_type = '{$data['token_type']}', expires_in = '{$data['expires_in']}', created = '{$data['created']}' WHERE id = '1'");
}
?>
db_backup.php
<?php
date_default_timezone_set('Asia/Kolkata');
require_once '../classes/dbconnection.class.php';
$week = array(
'Sun' => '0',
'Mon' => '1',
'Tue' => '2',
'Wed' => '3',
'Thu' => '4',
'Fri' => '5',
'Sat' => '6'
);
$folder = array(
'Sun' => '0B7nanNCGzXwLbmx3emVQNFBLNlU',
'Mon' => '0B7nanNCGzXwLb0hDTWFLVmNza3c',
'Tue' => '0B7nanNCGzXwLaVFtRkVRcUU0NFE',
'Wed' => '0B7nanNCGzXwLdlFwQVZuOURSZjA',
'Thu' => '0B7nanNCGzXwLSUhBMnVQVWpVUzQ',
'Fri' => '0B7nanNCGzXwLUGJmOFJId19TVGs',
'Sat' => '0B7nanNCGzXwLcnhhV2tvMUdFNkk'
);
if($_GET['action'] == 'backup' || $_GET['action'] == 'Backup' || $_GET['action'] == 'BACKUP' || $_GET['action'] == 'backup#'){
require_once '../inc/google/vendor/autoload.php';
require_once '../classes/dumper.class.php';
$client = new Google_Client();
$client->setAuthConfigFile('client_secret.json');
$client->setAccessType("offline");
$client->addScope(Google_Service_Drive::DRIVE);
$db = new dbconnection;
$conn = $db->connect('pf_central');
$token_data = $conn->query("SELECT access_token,token_type,expires_in,created FROM google_drive_token WHERE id = '1'")->fetch_assoc();
//var_dump($token_data);
if (isset($token_data) && $token_data) {
$client->setAccessToken($token_data);
$drive_service = new Google_Service_Drive($client);
// $files_list = $drive_service->files->listFiles(array())->getFiles();
$timestamp = strtotime(date("Y-m-d"));
$day = date("D", $timestamp);
$backup_result = $conn->query("SELECT `cd`.`db_name`,`b`.`backup`,`b`.`id`,`b`.`file_id`,`b`.`file_name` FROM `client_db` AS `cd` INNER JOIN `backup` AS `b` ON `cd`.`id` = `b`.`client_id` WHERE `b`.`backup` <> '2' AND `day_code` = '{$week[$day]}' ");
if($backup_result->num_rows ){
while ($row = $backup_result->fetch_assoc()){
try {
if($row['backup'] == 0){
if(isset($row['file_id']) && !empty($row['file_id']))
deleteFile($drive_service,$row['file_id']);
$world_dumper = Shuttle_Dumper::create(array(
'host' => 'localhost',
'username' => 'Joeroot',
'password' => '*****',
'db_name' => $row['db_name'],
));
$zipFilename = $row['db_name'].'.sql.gz';
$world_dumper->dump($zipFilename); // if dump is not working then please check a folder perimission and change it to '777'
$update_backup = $conn->query("UPDATE `backup` SET `backup`= '1',`file_name`='{$zipFilename}' WHERE `id` = '{$row['id']}' ");
$file = new Google_Service_Drive_DriveFile(array(
'name' =>$zipFilename ,
'parents' => array($folder[$day])
));
$result = $drive_service->files->create($file, array(
'data' => file_get_contents($zipFilename),
'mimeType' => 'application/octet-stream',
'uploadType' => 'multipart'
));
if($result['id']){
$update_backup = $conn->query("UPDATE `backup` SET `backup`= '2',`file_id`='{$result['id']}',`file_name`='{$zipFilename}' WHERE `id` = '{$row['id']}' ");
unlink($zipFilename);
}
}
else if($row['backup'] == 1){
$file = new Google_Service_Drive_DriveFile(array(
'name' =>$row['file_name'] ,
'parents' => array($folder[$day])
));
$result = $drive_service->files->create($file, array(
'data' => file_get_contents($row['file_name']),
'mimeType' => 'application/octet-stream',
'uploadType' => 'multipart'
));
if($result['id']){
$update_backup = $conn->query("UPDATE `backup` SET `backup`= '2',`file_id`='{$result['id']}',`file_name`='{$row['file_name']}' WHERE `id` = '{$row['id']}' ");
unlink($row['file_name']);
}
}
} catch(Shuttle_Exception $e) {
//$update_backup = $conn->query("UPDATE `backup` SET `backup`= '0',`file_name`='{$zipFilename}' WHERE `id` = '{$row['id']}' ");
}
}
}
else
echo "No data to backup";
} else {
$redirect_uri = 'https://papa.fit/controllers/oauth2callback.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
}
else if ($_GET['action'] == 'reSchedule' || $_GET['action'] == 'RESCHEDULE' || $_GET['action'] == 'reschedule' ) {
$db = new dbconnection;
$conn = $db->connect('pf_central');
$timestamp = strtotime(date("Y-m-d"));
$day = date("D", $timestamp);
$update_backup = $conn->query("UPDATE `backup` SET `backup`= '0' WHERE `day_code` = '{$week[$day]}' ");
if($update_backup)
echo "Resheduled databases for next backup";
}
function deleteFile($service, $fileId) {
try {
$service->files->delete($fileId);
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
?>
Related
I am using given below code but i am unable to insert event in google calendar through . Please help me out . If you have any info . Please reply as soon as possible.
$client = new Google_Client();
$client->setApplicationName("calender");
$client->setClientId('1065799091955-kuek7e5miai4q590v49jpntr00u3pcbp.apps.googleusercontent.com');
$client->setClientSecret('SBOs_gfbFn92bpGdBt8aQY1z');
$client->setRedirectUri('http://www.sydneywebexperts.com.au/Add-Calendar/event.php');
$client->setDeveloperKey('AIzaSyDjRKaWPdAlwvJQlKeLuxKnyzXdKZiR5_A');
//$cal = new Google_CalendarService($client);
$event = new Google_CalendarService(array(
'summary' => 'Google I/O 2015',
'location' => '800 Howard St., San Francisco, CA 94103',
'description' => 'A chance to hear more about Google\'s developer products.',
'start' => array(
'dateTime' => '2015-05-28T09:00:00-07:00',
'timeZone' => 'America/Los_Angeles',
),
'end' => array(
'dateTime' => '2015-05-28T17:00:00-07:00',
'timeZone' => 'America/Los_Angeles',
),
'recurrence' => array(
'RRULE:FREQ=DAILY;COUNT=2'
),
'attendees' => array(
array('email' => 'lpage#example.com'),
array('email' => 'sbrin#example.com'),
),
'reminders' => array(
'useDefault' => FALSE,
'overrides' => array(
array('method' => 'email', 'minutes' => 24 * 60),
array('method' => 'popup', 'minutes' => 10),
),
),
));
$calendarId = 'primary';
$event = $service->events->insert($calendarId, $event);
printf('Event created: %s\n', $event->htmlLink);
---------------------- or------------------------
<?php
error_reporting(E_ALL);
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_CalendarService.php';
session_start();
if ((isset($_SESSION)) && (!empty($_SESSION))) {
echo "There are cookies<br>";
echo "<pre>";
print_r($_SESSION);
}
$client = new Google_Client();
$client->setApplicationName("calender");
$client->setClientId('1065799091955-kuek7e5miai4q590v49jpntr00u3pcbp.apps.googleusercontent.com');
$client->setClientSecret('SBOs_gfbFn92bpGdBt8aQY1z');
$client->setRedirectUri('http://www.sydneywebexperts.com.au/Add-Calendar/event.php');
$client->setDeveloperKey('AIzaSyDjRKaWPdAlwvJQlKeLuxKnyzXdKZiR5_A');
$cal = new Google_CalendarService($client);
if (isset($_GET['logout'])) {
echo "<br><br><font size=+2>Logging out</font>";
unset($_SESSION['token']);
}
if (isset($_GET['code'])) {
echo "<br>I got a code from Google = ".$_GET['code']; // You won't see this if redirected later
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
echo "<br>I got the token = ".$_SESSION['token']; // <-- not needed to get here unless location uncommented
}
if (isset($_SESSION['token'])) {
echo "<br>Getting access";
$client->setAccessToken($_SESSION['token']);
}
if ($client->getAccessToken()){
echo "<hr><font size=+1>I have access to your calendar</font>";
$event = new Google_Event();
$event->setSummary('Halloween');
$event->setLocation('The Neighbourhood');
$start = new Google_EventDateTime();
$start->setDateTime('2016-4-13T10:00:00.000-05:00');
$event->setStart($start);
$end = new Google_EventDateTime();
$end->setDateTime('2016-4-13T10:25:00.000-05:00');
$event->setEnd($end);
print_r($event);
$createdEvent = $cal->events->insert('primary', $event);
print_r($createdEvent);
echo "<br><font size=+1>Event created</font>";
echo "<hr><br><font size=+1>Already connected</font> (No need to login)";
} else {
$authUrl = $client->createAuthUrl();
print "<hr><br><font size=+2><a href='$authUrl'>Connect Me!</a></font>";
}
$url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
echo "<br><br><font size=+2><a href=$url?logout>Logout</a></font>";
?>
I am frustrated but i am unable to insert event in calendar.
I'm trying to connect to Royal Mail shipping API, but I'm receiving the famous Could not connect to host.
$api_password = "****";
$api_username = "****";
$api_application_id = "****";
$api_service_type = "D";
$api_service_code = "SD1";
$api_service_format = "";
$api_certificate_passphrase = "****";
$time = gmdate('Y-m-d\TH:i:s');
$created = gmdate('Y-m-d\TH:i:s\Z');
$nonce = mt_rand();
$nonce_date_pwd = xyz(copy from sample);
$passwordDigest = zyz(copy from sample);
$ENCODEDNONCE = zyz(copy from sample);
$soapclient_options = array();
$soapclient_options['cache_wsdl'] = 'WSDL_CACHE_NONE';
$soapclient_options['local_cert'] = "CA2+Splash+Felipe+RM10001654+usr.p12";
$soapclient_options['passphrase'] = $api_certificate_passphrase;
$soapclient_options['trace'] = true;
$soapclient_options['ssl_method'] = 'SOAP_SSL_METHOD_SSLv3';
$soapclient_options['location'] = '****';
//launch soap client
$client = new SoapClient("SAPI/ShippingAPI_V2_0_8.wsdl", $soapclient_options);
$client->__setLocation($soapclient_options['location']);
(setting header)
$HeaderObject = new SoapVar( $HeaderObjectXML, XSD_ANYXML );
//push soap header
$header = new SoapHeader( 'oasis-200401-wss-wssecurity-utility-1.0.xsd', 'Security', $HeaderObject );
$client->__setSoapHeaders($header);
(setting request part)
if($api_service_enhancements != "") {
$request['requestedShipment']['serviceEnhancements'] = array('enhancementType' => array('serviceEnhancementCode' => array('code' => $api_service_enhancements)));
}
//try make the call
try {
$response = $client->__soapCall('createShipment', array($request), array('soapaction' => '***api-link***') );
} catch (Exception $e) {
//catch the error message and echo the last request for debug
echo $e->getMessage();
echo "REQUEST:\n" . $client->__getLastRequest() . "\n";
die;
}
Is it correct the way I'm setting the connection and the local cert?
Is any information I'm missing?
Thanks & Regards
Follow my final code :) this one works for sure. Even have the retry in case the server is buzy, enjoy.
<?php
//ini_set('soap.wsdl_cache_enabled', '1');
ini_set('soap.wsdl_cache_enabled',0);
ini_set('soap.wsdl_cache_ttl',0);
class royalmaillabelRequest
{
private $apiapplicationid = "insert urs";
private $api_password = "insert urs";
private $api_username = "insert urs"; //"rxxxxxAPI"
private $api_certificate_passphrase = "insert urs";
private $locationforrequest = 'https://api.royalmail.com/shipping/onboarding'; //live 'https://api.royalmail.com/shipping' onbording 'https://api.royalmail.com/shipping/onboarding'
private $api_service_enhancements = "";
private function preparerequest(){
//PASSWORD DIGEST
$time = gmdate('Y-m-d\TH:i:s');
$created = gmdate('Y-m-d\TH:i:s\Z');
$nonce = mt_rand();
$nonce_date_pwd = xyz(copy from sample);
$passwordDigest = nyz(copy from sample);
$ENCODEDNONCE = (copy from sample);
//SET CONNECTION DETAILS
$soapclient_options = array();
$soapclient_options['cache_wsdl'] = 'WSDL_CACHE_NONE';
$soapclient_options['stream_context'] = stream_context_create(
array('http'=>
array(
'protocol_version'=>'1.0'
, 'header' => 'Connection: Close'
)
)
);
$soapclient_options['local_cert'] = dirname(__FILE__) . "/certificate.pem";
$soapclient_options['passphrase'] = $this->api_certificate_passphrase;
$soapclient_options['trace'] = true;
$soapclient_options['ssl_method'] = 'SOAP_SSL_METHOD_SSLv3';
$soapclient_options['location'] = $this->locationforrequest;
$soapclient_options['soap_version'] = 'SOAP_1_1';
//launch soap client
$client = new SoapClient(dirname(__FILE__) . "/SAPI/ShippingAPI_V2_0_8.wsdl", $soapclient_options);
$client->__setLocation($soapclient_options['location']);
//headers needed for royal mail//D8D094Fd2716E3Es142588808s317
$HeaderObjectXML = '<wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<wsse:UsernameToken wsu:Id="UsernameToken-D8D094FC22716E3EDE14258880881317">
<wsse:Username>'.$this->api_username.'</wsse:Username>
<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">'.$passwordDigest.'</wsse:Password>
<wsse:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">'.$ENCODEDNONCE.'</wsse:Nonce>
<wsu:Created>'.$created.'</wsu:Created>
</wsse:UsernameToken>
</wsse:Security>';
//push the header into soap
$HeaderObject = new SoapVar( $HeaderObjectXML, XSD_ANYXML );
//push soap header
$header = new SoapHeader( 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd', 'Security', $HeaderObject );
$client->__setSoapHeaders($header);
return $client;
}
public function CreateShippiment($data){
$request = $this->buildCreateshippiment($data);
$type = 'createShipment';
return $this->makerequest($type, $request);
}
public function PrintLabel($shipmentNumber,$order_tracking_id){
$time = gmdate('Y-m-d\TH:i:s');
$request = array(
'integrationHeader' => array(
'dateTime' => $time,
'version' => '2',
'identification' => array(
'applicationId' => $this->apiapplicationid,
'transactionId' => $order_tracking_id
)
),
'shipmentNumber' => $shipmentNumber,
'outputFormat' => 'PDF',
);
$type = 'printLabel';
$response = $this->makerequest($type, $request);
return $response->label;
}
private function makerequest($type, $request){
$client = $this->preparerequest();
$response = false;
$times = 1;
while(true){
try {
$response = $client->__soapCall( $type, array($request), array('soapaction' => $this->locationforrequest) );
// echo "REQUEST:\n" . htmlentities($client->__getLastResponse()) . "\n";
break;
} catch (Exception $e) {
print_r($e);
if($e->detail->exceptionDetails->exceptionCode == "E0010" && $times <= 25){
sleep(1.5);
$times++;
continue;
}else{
echo $e->getMessage();
echo "<pre>";
print_r($e->detail);
echo $client->__getLastResponse();
echo "REQUEST:\n" . htmlentities($client->__getLastResponse()) . "\n";
break;
}
}
break;
}
return $response;
}
private function buildCreateshippiment($data2) {
$time = gmdate('Y-m-d\TH:i:s');
$data = new ArrayObject();
foreach ($data2 as $key => $value)
{
$data->$key = $value;
}
$request = array(
'integrationHeader' => array(
'dateTime' => $time,
'version' => '2',
'identification' => array(
'applicationId' => $this->apiapplicationid,
'transactionId' => $data->order_tracking_id
)
),
'requestedShipment' => array(
'shipmentType' => array('code' => 'Delivery'),
'serviceOccurrence' => 1,
'serviceType' => array('code' => $data->api_service_type),
'serviceOffering' => array('serviceOfferingCode' => array('code' => $data->api_service_code)),
'serviceFormat' => array('serviceFormatCode' => array('code' => $data->api_service_format)),
'shippingDate' => date('Y-m-d'),
'recipientContact' => array('name' => $data->shipping_name, 'complementaryName' => $data->shipping_company),
'recipientAddress' => array('addressLine1' => $data->shipping_address1, 'addressLine2' => $data->shipping_address2, 'postTown' => $data->shipping_town, 'postcode' => $data->shipping_postcode),
'items' => array('item' => array(
'numberOfItems' => $data->order_tracking_boxes,
'weight' => array( 'unitOfMeasure' => array('unitOfMeasureCode' => array('code' => 'g')),
'value' => $data->order_tracking_weight,
)
)
),
//'signature' => 0,
)
);
if($data->api_service_enhancements == 6 && $data->api_service_type == 1){
$request['requestedShipment']['serviceEnhancements'] = array('enhancementType' => array('serviceEnhancementCode' => array('code' => $data->api_service_enhancements)));
}
return $request;
}
}
docs.oasis-open.org is slow and doesn't respond in time.
Download oasis-200401-wss-wssecurity-utility-1.0.xsd and modify ShippingAPI_V2_0_8.wsdl to use local version.
Your location looks wrong..
$soapclient_options['location'] = '****';
Shouldn't this look like this..
$soapclient_options['location'] = 'https://api.royalmail.com/shipping/onboarding';
I'm running Magento sample code for a REST API
(http://www.magentocommerce.com/api/rest/introduction.html)
I achieved a correct authentication, with an authentication token, and after the POST I got feedback of a correct upload with this message:
Array (
[url] => http://magentohost.pt/magento/api/rest/products
[http_code] => 200
[download_content_length] => 37
[content_type] => text/html
[size_download] => 37
[size_upload] => 250
)
However, the sent data doesn't appear in database/magento.
In any of the sample codes on the Magento API REST page, I get communication with the API but not the changes on products/customers data of the database.
What am I doing wrong ?
This is how you can create products using REST API
<?php
/**
* Example of simple product POST using Admin account via Magento REST API. OAuth authorization is used
*/
$callbackUrl = "http://yourhost/oauth_admin.php";
$temporaryCredentialsRequestUrl = "http://magentohost/oauth/initiate?oauth_callback=" . urlencode($callbackUrl);
$adminAuthorizationUrl = 'http://magentohost/admin/oauth_authorize';
$accessTokenRequestUrl = 'http://magentohost/oauth/token';
$apiUrl = 'http://magentohost/api/rest';
$consumerKey = 'yourconsumerkey';
$consumerSecret = 'yourconsumersecret';
session_start();
if (!isset($_GET['oauth_token']) && isset($_SESSION['state']) && $_SESSION['state'] == 1) {
$_SESSION['state'] = 0;
}
try {
$authType = ($_SESSION['state'] == 2) ? OAUTH_AUTH_TYPE_AUTHORIZATION : OAUTH_AUTH_TYPE_URI;
$oauthClient = new OAuth($consumerKey, $consumerSecret, OAUTH_SIG_METHOD_HMACSHA1, $authType);
$oauthClient->enableDebug();
if (!isset($_GET['oauth_token']) && !$_SESSION['state']) {
$requestToken = $oauthClient->getRequestToken($temporaryCredentialsRequestUrl);
$_SESSION['secret'] = $requestToken['oauth_token_secret'];
$_SESSION['state'] = 1;
header('Location: ' . $adminAuthorizationUrl . '?oauth_token=' . $requestToken['oauth_token']);
exit;
} else if ($_SESSION['state'] == 1) {
$oauthClient->setToken($_GET['oauth_token'], $_SESSION['secret']);
$accessToken = $oauthClient->getAccessToken($accessTokenRequestUrl);
$_SESSION['state'] = 2;
$_SESSION['token'] = $accessToken['oauth_token'];
$_SESSION['secret'] = $accessToken['oauth_token_secret'];
header('Location: ' . $callbackUrl);
exit;
} else {
$oauthClient->setToken($_SESSION['token'], $_SESSION['secret']);
$resourceUrl = "$apiUrl/products";
$productData = json_encode(array(
'type_id' => 'simple',
'attribute_set_id' => 4,
'sku' => 'simple' . uniqid(),
'weight' => 1,
'status' => 1,
'visibility' => 4,
'name' => 'Simple Product',
'description' => 'Simple Description',
'short_description' => 'Simple Short Description',
'price' => 99.95,
'tax_class_id' => 0,
));
$headers = array('Content-Type' => 'application/json');
$oauthClient->fetch($resourceUrl, $productData, OAUTH_HTTP_METHOD_POST, $headers);
print_r($oauthClient->getLastResponseInfo());
}
} catch (OAuthException $e) {
print_r($e);
}
Reference: http://www.magentocommerce.com/api/rest/introduction.html#RESTAPIIntroduction-CreateasimpleproductasanAdminuserwithOAuthauthentication
I'm trying to create a webservice with PHP and nuSoap but everytime I try to execute it I'm getting the error:
XML error parsing SOAP payload on line 1: Not well-formed (invalid token)
Can anyone see what's wrong?
service.php
<?php
require 'lib/nusoap.php';
$server = new nusoap_server();
$server->configureWSDL("casamitger" . "urn:casamitger");
$server->wsdl->schemaTargetNamespace = 'urn:casamitger';
include 'functions.php';
//getAvailabilities
$server->wsdl->addComplexType('Availabilities','complexType','struct','all','',array(
'StartDate' => array('name' => 'StartDate', 'type' => 'xsd:date'),
'EndDate' => array('name' => 'EndDate', 'type' => 'xsd:date'),
'State' => array('name' => 'State', 'type' => 'xsd:string'),
));
$server->wsdl->addComplexType('ArrayOfAvailabilities', 'complexType', 'array', '', 'SOAP-ENC:Array', array(), array(
array('ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:Availabilities[]')), 'tns:Availabilities');
$server->register(
'getAvailabilities',
array(
"SessionID" => 'xsd:string',
"AccommodationId" => 'xsd:integer'
),
array("return" => 'tns:ArrayOfAvailabilities')
);
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$server->service($HTTP_RAW_POST_DATA);
?>
functions.php
function getAvailabilities($sessionID, $accommodation_code) {
$connection = mysqli_connect("localhost", "root", "", "casamitger");
if (authenticate($sessionID)) {
$user = getUser($sessionID);
$query = mysqli_query($connection, "SELECT count(AccommodationId) c FROM UserAccommodations WHERE AccommodationId = '$accommodation_code' AND CompanyId = '$user'") or die();
$row = mysqli_fetch_object($query);
$count = $row->c;
if ($count > 0) {
$query = mysqli_query($connection, "SELECT StartDate,EndDate,State FROM Availabilities WHERE AccommodationId = '$accommodation_code'") or die();
$n = 0;
while ($row = mysqli_fetch_object($query)) {
$result[$n]['StartDate'] = $row->StartDate;
$result[$n]['EndDate'] = $row->EndDate;
$result[$n]['State'] = $row->State;
$n++;
}
return $result;
}
}
}
and the client.php
<?php
require 'lib/nusoap.php';
include 'functions.php';
$sessionid = '1234';
$accommodation_code = '83081';
$client = new nusoap_client("http://192.168.8.155:8090/ws/service.php?wsdl");
$availabilities = $client->call(
'getAvailabilities',
array(
"SessionID" => "$sessionid",
"AccommodationId" => "$accommodation_code",
)
);
if ($client->fault) {
echo 'Fault';
} else {
$err = $client->getError();
if ($err) {
echo $err;
} else {
print_r($servicetypes);
}
}
?>
If I call the method getAvailabilities() directly it works but it doesn't through the web service, any help will be appreciated, thanks.
When i type this url direct into browser i get the post sent to user feed wall
https://graph.facebook.com/xx facebook uid xx/feed?access_token=xx app access token xx&message=Welcome%20to%20App!&method=post
But it gives me this error OAuthException: Invalid OAuth access token signature. when i automate the post with this code
<?PHP
include_once "inc/facebook.php";
require_once 'inc/config.php';
// Create our application instance
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
));
$dbh = new PDO('mysql:dbname='.$db_name.';host='.$db_host.';charset=utf8', $db_username, $db_password );
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare('SELECT fb_id FROM offline_access_users');
$stmt->execute();
$body = array(
'message' => 'Test Multiple Messages',
'link' => '',
'picture' => '',
'name' => '',
'description'=> ''
);
$batchPost=array();
$i=1;
foreach ($stmt as $value) {
$id = $value['fb_id'];
$batchPost[] = array(
'method' => 'POST',
'relative_url' => "/" . $id . "/feed?access_token=" . $access_token,
'body' => http_build_query($body) );
if($i++ == 50) {
try {
$multiPostResponse = $facebook->api('?batch=' . urlencode(json_encode($batchPost)), 'POST');
echo "Success";
} catch(FacebookApiException $e) {
error_log($e);
echo($e);
}
unset($batchPost);
$i=1;
}
}
if(isset($batchPost) && count($batchPost) > 0 ) {
try{
$multiPostResponse = $facebook->api('?batch=' . urlencode(json_encode($batchPost)), 'POST');
echo "Success";
} catch(FacebookApiException $e){
error_log($e);
echo($e);
}
}
$db = null;
?>
I really don't know how to come over this issue. Please help me