Twitter API returns error code 32 - php

We're currently working with the Twitter API and failed to sucessfully send a tweet to their API. It's always exiting with code 32 in both Java and PHP (made a PHP prototype just for sending the request). I guess I'm missing something about the OAuth1 specification here.
The PHP prototype we're using:
<?PHP
require_once("cURL.php");
$headers = [];
$postParams = [];
$signatureParams = [];
$authString = "";
$URL = "https://api.twitter.com/1.1/statuses/update.json";
$method = "POST";
$token = "someValidToken";
$tokenSecret = "someValidTokenSecret";
$timestamp = time();
$status = "Hi, Twitter!";
$signatureParams['status'] = $status;
$clientID = "someClientID";
$clientSecret = "someClientSecret";
$signatureParams['oauth_consumer_key'] = urlencode($clientID);
$signatureParams['oauth_nonce'] = urlencode(base64_encode($timestamp));
$signatureParams['oauth_signature_method'] = urlencode("HMAC-SHA1");
$signatureParams['oauth_timestamp'] = $timestamp;
$signatureParams['oauth_token'] = urlencode($token);
$signatureParams['oauth_version'] = urlencode("1.0");
$oauthSignature = generateSignature();
$signatureParams["oauth_signature"] = $oauthSignature;
unset($signatureParams['status']);
ksort($signatureParams);
$count = 0;
$authStringLoop = "";
foreach($signatureParams as $key => $signatureParam)
{
if($count++ == 0)
{
$authStringLoop .= "OAuth ";
}
$authStringLoop .= urlencode($key);
$authStringLoop .= "=\"";
$authStringLoop .= urlencode($signatureParam)."\",";
}
$authStringLoop = substr($authStringLoop,0,strlen($authStringLoop)-1);
echo "</br></br>";
echo "AuthString loop: $authStringLoop</br></br>";
$headers = array(
"Authorization: $authStringLoop"
);
var_dump($headers).'</br>';
var_dump(POST($URL,json_encode($status),$headers,0));
function generateSignature()
{
global $clientSecret;
global $signatureParams;
global $URL;
global $method;
global $clientSecret;
global $clientID;
global $tokenSecret;
ksort($signatureParams);
$parameterString = "";
foreach($signatureParams as $key => $signatureParam)
{
$parameterString .= urlencode($key."=".$signatureParam."&");
}
$signingBase = strtoupper($method)."&".urlencode($URL)."&".$parameterString;
$signingKey = urlencode($clientSecret)."&".urlencode($tokenSecret);
var_dump($signingBase);
echo '</br>';
echo "Base64 encoded: ".base64_encode(hash_hmac("SHA1",$signingBase,$signingKey,TRUE));
echo '</br>';
echo "URL encoded: ".urlencode(base64_encode(hash_hmac("SHA1",$signingBase,$signingKey,TRUE)))."</br>";
return base64_encode(hash_hmac("SHA1",$signingBase,$signingKey,TRUE));
}
?>
My guess that there is something wrong with the way the signature is generated. However, all I found was to sort it alphabetically which should be done with the ksort() call. What do we miss here?

Related

how to use dreamscape api in nodejs for check domain name

I have already work this in php. Here is my working code:
$request = array(
'DomainNames' => $domain_names
);
$response = dreamScapeAPI('DomainCheck', $request);
$available = false;
$alt_domains = array(); // Alternative to user's expected domain names
if (!is_soap_fault($response)) {
// Successfully checked the availability of the domains
if (isset($response->APIResponse->AvailabilityList)) {
$availabilityList = $response->APIResponse->AvailabilityList;
foreach ($availabilityList as $list) {
if ($list->Available){
if ($domain == $list->Item) {
$available = true; // user prefered domain found
}
else {
$alt_domains[] = $list->Item;
}
}
}
}
else {
$error = $response->APIResponse->Errors;
foreach ($error as $e) {
$api_error = $e->Message;
//echo $e->Item . ' - ' . $e->Message . '<br />';
}
}
}
function dreamScapeAPI($method, $data = null) {
$reseller_api_soap_client = "";
$soap_location = 'http://soap.secureapi.com.au/API-2.1';
$wsdl_location = 'http://soap.secureapi.com.au/wsdl/API-2.1.wsdl';
$authenticate = array();
$authenticate['AuthenticateRequest'] = array();
$authenticate['AuthenticateRequest']['ResellerID'] = '**';
$authenticate['AuthenticateRequest']['APIKey'] = '**';
//convert $authenticate to a soap variable
$authenticate['AuthenticateRequest'] = new SoapVar($authenticate['AuthenticateRequest'], SOAP_ENC_OBJECT);
$authenticate = new SoapVar($authenticate, SOAP_ENC_OBJECT);
$header = new SoapHeader($soap_location, 'Authenticate', $authenticate, false);
$reseller_api_soap_client = new SoapClient($wsdl_location, array('soap_version' => SOAP_1_2, 'cache_wsdl' => WSDL_CACHE_NONE));
$reseller_api_soap_client->__setSoapHeaders(array($header));
$prepared_data = $data != null ? array($data) : array();
try {
$response = $reseller_api_soap_client->__soapCall($method, $prepared_data);
} catch (SoapFault $response) { }
return $response;
}
I tried with this : https://github.com/dan-power/node-dreamscape
But domain search can not work properly. Mainly, I want it on nodejs using nodejs dreamscape api but this method is not available on nodejs.
Here is my working demo: click here

having php fatal error Function name must be a string in C:\wamp\www\drupal-7.42\sites\all\modules\form_fun\form_fun.cake.inc on line 78

I am trying to send a curl request to moodle using drupal.But each tiem i run this code i get an error message that function name must be a string.I have tried everything but nothing is working.Can anybody please help me?
function form_fun_cake_submit(&$form, &$form_state) {
$serverUrl=' http://localhost/moodle/my/webservice/rest/server.php?wstoken=d90b5d90db13711d12df525366f15db1';
$functionName = 'core_user_create_users';
$user1 = new stdClass();
$user1->username = 'testusername1';
$user1->password = 'Uk3#0d5w';
$user1->firstname = 'testfirstname1';
$user1->lastname = 'testlastname1';
$user1->email = 'testemail1#moodle.com';
$user1->auth = 'manual';
$user1->idnumber = '';
$user1->lang = 'en';
$user1->timezone = 'Australia/Sydney';
$user1->mailformat = 0;
$user1->description = '';
$user1->city = '';
$user1->country = 'AU'; //list of abrevations is in yourmoodle/lang/en/countries
$preferencename1 = 'auth_forcepasswordchange';
$user1->preferences = array(
array('type' => $preferencename1, 'value' => 'true')
);
$users = array($user1);
$params = array('users' => $users);
/// REST CALL
$rest_format = 'json';
//$server_url = $domain_name . '/webservice/rest/server.php' . '?wstoken=' . $token . '&wsfunction=' . $function_name;
$server_url = 'localhost/moodle/my' . '/webservice/rest/server.php'. '?wstoken=' . '15bd45a3dab2958b7e8fc237b14f76cd' .'&wsfunction='. $functionName;
dpm($server_url);
require_once('curl.inc');
$curl = new curl;
$rest_format = ($rest_format == 'json') ? '&moodlewsrestformat=' . $rest_format : '';
$resp =$curl($server_url . $rest_format, $params); //This is my line no 78
dpm($rest_format);
$respRc = json_decode($resp, true);
dpm($resp);
echo '</br>************************** Server Response createUser()**************************</br></br>';
echo $server_url . '</br></br>';
var_dump($resp);
}
Line 78 replace $curl(...) with new curl(..), your object instancing is incorrect. What is telling the php log is that you are using a variable as function name aka $curl (nothing to do with $functionName wich might have generated an error later with curl not on compile if it was wrong).
$resp = new curl($server_url . $rest_format, $params);

CakePHP 2.x won't save the record but continues execution without throwing an error

I have written an application in CakePHP. I am facing an issue. Sometimes it happens that when an order is placed, it's not reflecting in database, but I am both getting an email and it's reflecting in my PayU account dashboard that someone has placed an order with x amount.
Below is my code. What is wrong?
if(!empty($this->data)){
$data = $this->data;
$userInfo = $this->User->find('first',array('conditions'=>array('User.id'=>$userID)));
$sales_rep_email = $userInfo["User"]["sales_rep_email"];
$user_email = $userInfo["User"]["primary_contact_email"];
$virtual_account = $userInfo["User"]["virtual_account"];
if($data['payment_method']=="RTGS Payment"){
$orderData['Order']['invoice_no'] = 0;
$orderData['Order']['invoice_prefix'] = "INV-2015-00";
$orderData['Order']['user_id'] = $userInfo['User']['id'];
$orderData['Order']['name'] = $userInfo['User']['name'];
$orderData['Order']['email'] = $userInfo['User']['primary_contact_email'];
$orderData['Order']['phone'] = $userInfo['User']['primary_contact_number'];
$orderData['Order']['billing_address'] = $userInfo['User']['address'].", ".$userInfo['User']['city'].", ".$userInfo['User']['district'].", ".$userInfo['User']['state']."-".$userInfo['User']['pin_code'];
$orderData['Order']['order_item_count'] = $shop['Order']['quantity'];
$orderData['Order']['shipping'] = $data['shipping_method'];
$orderData['Order']['total'] = $shop['Order']['total'];
$orderData['Order']['payment_method'] = $data['payment_method'];
if($data['shipping_method']=="Express Delivery"){
$orderData['Order']['delivery_charges'] = 400;
}
if($data['payment_method']=="RTGS Payment"){
$orderData['Order']['status'] = 'open';
$orderData['Order']['temp_status'] = 'rtgs';
}else if($data['payment_method']=="COD"){
$orderData['Order']['status'] = 'open';
$orderData['Order']['temp_status'] = 'cod';
$orderData['Order']['customer_status'] = 'unconfirmed';
}else{
$orderData['Order']['status'] = 'open';
$orderData['Order']['temp_status'] = 'open';
}
$this->Order->save($orderData);
$id = $this->Order->getLastInsertId();
$orderupdateData['Order']['orderid'] = date("Y").date("m").'-'.$id;
$orderupdateData['Order']['temporary_order'] = "TO".'-'.$id;
$orderupdateData['Order']['id'] = $id;
$this->Order->save($orderupdateData);
$orderItemData = array();
foreach($shop['OrderItem'] as $key=>$item){
$quantityNewCheckOut = 0;
if(!empty($data['payment_method'])){
$this->manageInventory($item['Product']['smb_code'],$item['quantity']);
}
$orderItemData['OrderItem']['order_id'] = $id;
$orderItemData['OrderItem']['sku_id'] = $key;
$inventoryData = $this->Inventory->find("first",array("conditions"=>array("Inventory.smb_item_code"=>$item['Product']['smb_code'])));
$quantityNewCheckOut = (int)$inventoryData["Inventory"]["quantity"];
if($quantityNewCheckOut<=0){
$orderItemData["OrderItem"]["mod_name"] = "back";
}else if($quantityNewCheckOut>0){
$orderItemData["OrderItem"]["mod_name"] = "available";
}
$orderItemData['OrderItem']['name'] = $item['Product']['smb_code'];
$orderItemData['OrderItem']['quantity'] = $item['quantity'];
$orderItemData['OrderItem']['price'] = $item['price'];
if(!empty($item['discount_amount'])){
$orderItemData['OrderItem']['discount_amount'] = $item['discount_amount'];
}
$orderItemData['OrderItem']['subtotal'] = $item['subtotal'];
$orderItemData['OrderItem']['status'] = "open";
$this->OrderItem->save($orderItemData);
$this->OrderItem->create();
unset($orderItemData);
}
$orderDetails = $this->OrderItem->find("all",array("conditions"=>array("OrderItem.order_id"=>$id),'recursive'=>2));
$content = "<b>Order Date:</b>".date("d F Y H:i:s")."<br/>";
$content .= "<b>Temporary Order Number:</b>"."TO".'-'.$id."<br/><br/><br/>";
$content .= "<table border='1'><thead><th>Company Name</th><th>Brand</th><th>SMB Item Code</th><th>Mfg Code</th><th>Product Description</th><th>UOM</th><th>MRP</th><th>Unit Price</th><th>Qty</th><th>Subtotal</th><th>Tax%</th><th>Total</th></thead><tbody>";
foreach($orderDetails as $orderItem){
$content .= "<tr>";
$content .= "<td>".$orderItem["Sku"]["Company"]["name"]."</td>";
$content .= "<td>".$orderItem["Sku"]["Brand"]["name"]."</td>";
$content .= "<td>".$orderItem["Sku"]["smb_code"]."</td>";
$content .= "<td>".$orderItem["Sku"]["title"]."</td>";
$content .= "<td>".$orderItem["Sku"]["description"]."</td>";
$content .= "<td>".$orderItem["Sku"]["uom"]."</td>";
$content .= "<td>"."Rs.".$orderItem["Sku"]["mrp"]."</td>";
$content .= "<td>"."Rs.".$orderItem["OrderItem"]["price"]."</td>";
$content .= "<td>".$orderItem["OrderItem"]["quantity"]."</td>";
$content .= "<td>"."Rs.".sprintf('%01.2f', $orderItem["OrderItem"]["price"] * $orderItem["OrderItem"]["quantity"])."</td>";
$content .= "<td>".$orderItem["Sku"]["Product"]["tax"]."</td>";
$content .= "<td>"."Rs.".$orderItem["OrderItem"]["subtotal"]."</td>";
$content.= "</tr>";
}
if($data['shipping_method']=="Express Delivery"){
$totalAmount = ($orderItem["Order"]["total"])+400;
$content .= "<tr><td style='text-align:right' colspan='10'>Delivery Charges:</td><td style='text-align:right'colspan='2'>"."Rs. 400</td></tr>";
$content .= "<tr><td style='text-align:right' colspan='10'>Grand Total:</td><td style='text-align:right'colspan='2'>"."Rs. ".$totalAmount."</td></tr>";
}else{
$content .= "<tr><td style='text-align:right' colspan='10'>Grand Total:</td><td style='text-align:right'colspan='2'>"."Rs. ".$orderItem["Order"]["total"]."</td></tr>";
}
$content .= "</tbody></table>";
$emailTemplate = $this->EmailTemplate->find('first',array('conditions'=>array('EmailTemplate.id'=>'23')));
$emailContent = $emailTemplate['EmailTemplate']['html_content'];
$subject = $emailTemplate['EmailTemplate']['subject']."TO".'-'.$id;
$template_info = str_replace(array('$temp_order','$virtual_id','$content','$salesrep'),array("TO".'-'.$id,$virtual_account,$content,$sales_rep_email),$emailContent);
$email = new CakeEmail();
$email->template('email_template');
$email->emailFormat('both');
$email->viewVars(array('emailContent' => $template_info));
$to = array($user_email);//$to = '';
$from = '';
$email->to($to);
$email->bcc("");
$email->cc($sales_rep_email);
$email->from(array($from=>''));
$email->subject($subject);
$email->smtpOptions = array(
'port'=>'25',
'timeout'=>'30',
'host' => '',
'username'=>'',
'password'=>'',
);
//Set delivery method
$email->delivery = 'smtp';
//pry($email);
$email->send();
$this->redirect(array('action'=>"successOrderRTGS"));
}else{
$paymentMethod = $data['payment_method'];
$shippingMethod = $data['shipping_method'];
if(!empty($paymentMethod)){
$this->Session->write("User.payment_method",$paymentMethod);
$this->Session->write("User.shipping_method",$shippingMethod);
}
$orderData['Order']['total'] = $shop['Order']['total'];
if($data['shipping_method']=="Express Delivery"){
$orderData['Order']['delivery_charges'] = 400;
$amount =($shop['Order']['total'])+400;
}else{
$amount =($shop['Order']['total']);
}
$this->pay_page( array ( 'key' => '', 'txnid' => uniqid( 'test' ), 'amount' => $amount,
'firstname' => $userInfo['User']['name'], 'email' => $userInfo['User']['primary_contact_email'], 'phone' => $userInfo['User']['primary_contact_number'],
'productinfo' => 'Product Info', 'surl' => 'payment_success', 'furl' => 'payment_failure'), '' );
}
}
The reason your code is sending out the email despite not saving the Order data in the database is because you are not checking whether the save() is successful or not. It's probably failing due to validation errors, but your code won't do anything about it.
The proper way of handling this is by wrapping the save() method inside an if condition:
if ($this->Order->save($orderData)) {
//send email
//redirect
} else {
Debugger::log($this->Order->validationErrors);
$this->Flash->set('Order could not be saved');
}
You should also refactor your action to reduce its size. The main purpose of using a MVC framework is to make life easier by separating business logic, control logic and views. If you find yourself writing HTML in your controller, you are probably doing something wrong.
Interesting read: Fat models, skinny controllers and the MVC design pattern

PHP create User in moodle via Webservice

I want so connect an external website with a moodle-system. I've already set up the webService and created a token to get access.
I've followed http://www.rumours.co.nz/manuals/using_moodle_web_services.htm set up but in contrast i wanted to realise the connection via REST as in https://github.com/moodlehq/sample-ws-clients/find/master
My approach is to have a moodle class which will handle the data exchange. In first place i just wanted to try to create some new hard coded Users via the webService but it fails with the Moodle-Response:
"invalidrecord Can not find data record in database table external_functions. "
Which seems to me as if i the call was successfully but moodle has a problem to find the "core_user_create_users" function. I've checked the local moodle Database and in the table external_functions is an entry for "core_user_create_users" so i'm kind of confused where moodle doesn't know what to do.
Thats my class:
require_once (DOCUMENT_ROOT.'/tcm/api/moodle/curl.php');
class Moodle {
private $token;
private $domainName; // 'local.moodle.dev';
private $serverUrl;
public function __construct($token, $domainName) {
$this->token = $token;
$this->domainName = $domainName;
$this->serverUrl = $this->domainName . '/webservice/rest/server.php' . '?wstoken=' . $this->token;
echo "initialize Service: $this->serverUrl </br>";
}
public function createUser() {
$functionName = 'core_user_create_users';
/// PARAMETERS - NEED TO BE CHANGED IF YOU CALL A DIFFERENT FUNCTION
$user1 = new stdClass();
$user1->username = 'testusername1';
$user1->password = 'testpassword1';
$user1->firstname = 'testfirstname1';
$user1->lastname = 'testlastname1';
$user1->email = 'testemail1#moodle.com';
$user1->auth = 'manual';
$user1->idnumber = 'testidnumber1';
$user1->lang = 'en';
$user1->theme = 'standard';
$user1->timezone = '-12.5';
$user1->mailformat = 0;
$user1->description = 'Hello World!';
$user1->city = 'testcity1';
$user1->country = 'au';
$preferencename1 = 'preference1';
$preferencename2 = 'preference2';
$user1->preferences = array(
array('type' => $preferencename1, 'value' => 'preferencevalue1'),
array('type' => $preferencename2, 'value' => 'preferencevalue2'));
$user2 = new stdClass();
$user2->username = 'testusername2';
$user2->password = 'testpassword2';
$user2->firstname = 'testfirstname2';
$user2->lastname = 'testlastname2';
$user2->email = 'testemail2#moodle.com';
$user2->timezone = 'Pacific/Port_Moresby';
$users = array($user1, $user2);
$params = array('users' => $users);
/// REST CALL
$serverurl = $this->serverUrl . '&wsfunction=' . $functionName;
require_once (DOCUMENT_ROOT.'/tcm/api/moodle/curl.php');
$curl = new curl;
//if rest format == 'xml', then we do not add the param for backward compatibility with Moodle < 2.2
$restformat = "json";
$resp = $curl->post($serverurl . $restformat, $params);
//print_r($resp);
echo '</br>*************Server Response*************</br>';
var_dump($resp);
}
}
I'm using the curl class from the same github-project which i posted above - moodle is linkng to it in their Documentation..
docs.moodle.org/dev/Creating_a_web_service_client
The entry point of my call is hardcoded right now:
<?php
include_once (DOCUMENT_ROOT.'/tcm/api/moodle/moodle.php');
//entry point of code
if (isset($_POST)){
//token and domain would be in $_POST
$bla = new Moodle('0b5a1e98061c5f7fb70fc3b42af6bfc4', 'local.moodle.dev');
$bla->createUser();
}
Does anyone know how to solve the "invalidrecord Can not find data record in database table external_functions" error or has a different approach/suggestion how i can create my users remotely??
Thanks in advance
I got it finally working with the following code:
class Moodle {
private $token; //'0b5a1e98061c5f7fb70fc3b42af6bfc4';
private $domainName; // 'http://local.moodle.dev';
private $serverUrl;
public $error;
public function __construct($token, $domainName) {
$this->token = $token;
$this->domainName = $domainName;
$this->serverUrl = $this->domainName . '/webservice/rest/server.php' . '?wstoken=' . $this->token;
echo "initialize Service: $this->serverUrl </br>";
}
public function createUser() {
$functionName = 'core_user_create_users';
$user1 = new stdClass();
$user1->username = 'testusername1';
$user1->password = 'Uk3#0d5w';
$user1->firstname = 'testfirstname1';
$user1->lastname = 'testlastname1';
$user1->email = 'testemail1#moodle.com';
$user1->auth = 'manual';
$user1->idnumber = '';
$user1->lang = 'en';
$user1->timezone = 'Australia/Sydney';
$user1->mailformat = 0;
$user1->description = '';
$user1->city = '';
$user1->country = 'AU'; //list of abrevations is in yourmoodle/lang/en/countries
$preferencename1 = 'auth_forcepasswordchange';
$user1->preferences = array(
array('type' => $preferencename1, 'value' => 'true')
);
$users = array($user1);
$params = array('users' => $users);
/// REST CALL
$restformat = "json";
$serverurl = $this->serverUrl . '&wsfunction=' . $functionName. '&moodlewsrestformat=' . $restformat;
require_once (DOCUMENT_ROOT . '/tcm/api/moodle/curl.php');
$curl = new curl();
$resp = $curl->post($serverurl, $params);
echo '</br>************************** Server Response createUser()**************************</br></br>';
echo $serverurl . '</br></br>';
var_dump($resp);
}
}
Info:
For all moodle beginners.. Activating the moodle Debug messages helps a bit. You'll receive an additional error information in the response returned form the server.
Moodle -> Site Administration -> Development -> Debugging -> Debug Messages
Select: DEVELOPER:extra Moodle debug messages for developers

Google Sheets API - Insert a row with PHP

So I created a Spreadsheet class that is a combination of a few solutions I found online for accessing Google Sheets API with PHP. It works.
class Spreadsheet {
private $token;
private $spreadsheet;
private $worksheet;
private $spreadsheetid;
private $worksheetid;
private $client_id = '<client id>';
private $service_account_name = '<service_account>'; // email address
private $key_file_location = 'key.p12'; //key.p12
private $client;
private $service;
public function __construct() {
$this->client = new Google_Client();
$this->client->setApplicationName("Sheets API Testing");
$this->service = new Google_Service_Drive($this->client);
$this->authenticate();
}
public function authenticate()
{
if (isset($_SESSION['service_token'])) {
$this->client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($this->key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$this->service_account_name,
array('https://www.googleapis.com/auth/drive', 'https://spreadsheets.google.com/feeds'), $key
);
$this->client->setAssertionCredentials($cred);
if ($this->client->getAuth()->isAccessTokenExpired()) {
$this->client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $this->client->getAccessToken();
// Get access token for spreadsheets API calls
$resultArray = json_decode($_SESSION['service_token']);
$this->token = $resultArray->access_token;
}
public function setSpreadsheet($title) {
$this->spreadsheet = $title;
return $this;
}
public function setSpreadsheetId($id) {
$this->spreadsheetid = $id;
return $this;
}
public function setWorksheet($title) {
$this->worksheet = $title;
return $this;
}
public function insert() {
if (!empty($this->token)) {
$url = $this->getPostUrl();
} else {
echo "Authentication Failed";
}
}
public function add($data) {
if(!empty($this->token)) {
$url = $this->getPostUrl();
if(!empty($url)) {
$columnIDs = $this->getColumnIDs();
if($columnIDs) {
$fields = '<entry xmlns="http://www.w3.org/2005/Atom" xmlns:gsx="http://schemas.google.com/spreadsheets/2006/extended">';
foreach($data as $key => $value) {
$key = $this->formatColumnID($key);
if(in_array($key, $columnIDs)) {
$fields .= "<gsx:$key><![CDATA[$value]]></gsx:$key>";
}
}
$fields .= '</entry>';
$headers = [
"Authorization" => "Bearer $this->token",
'Content-Type' => 'application/atom+xml'
];
$method = 'POST';
$req = new Google_Http_Request($url, $method, $headers, $fields);
$curl = new Google_IO_Curl($this->client);
$results = $curl->executeRequest($req);
var_dump($results);
}
}
}
}
private function getColumnIDs() {
$url = "https://spreadsheets.google.com/feeds/cells/" . $this->spreadsheetid . "/" . $this->worksheetid . "/private/full?max-row=1";
$headers = array(
"Authorization" => "Bearer $this->token",
"GData-Version: 3.0"
);
$method = "GET";
$req = new Google_Http_Request($url, $method, $headers);
$curl = new Google_IO_Curl($this->client);
$results = $curl->executeRequest($req);
if($results[2] == 200) {
$columnIDs = array();
$xml = simplexml_load_string($results[0]);
if($xml->entry) {
$columnSize = sizeof($xml->entry);
for($c = 0; $c < $columnSize; ++$c) {
$columnIDs[] = $this->formatColumnID($xml->entry[$c]->content);
}
}
return $columnIDs;
}
return "";
}
private function getPostUrl() {
if (empty($this->spreadsheetid)){
#find the id based on the spreadsheet name
$url = "https://spreadsheets.google.com/feeds/spreadsheets/private/full?title=" . urlencode($this->spreadsheet);
$method = 'GET';
$headers = ["Authorization" => "Bearer $this->token"];
$req = new Google_Http_Request($url, $method, $headers);
$curl = new Google_IO_Curl($this->client);
$results = $curl->executeRequest($req);
if($results[2] == 200) {
$spreadsheetXml = simplexml_load_string($results[0]);
if($spreadsheetXml->entry) {
$this->spreadsheetid = basename(trim($spreadsheetXml->entry[0]->id));
$url = "https://spreadsheets.google.com/feeds/worksheets/" . $this->spreadsheetid . "/private/full";
if(!empty($this->worksheet)) {
$url .= "?title=" . $this->worksheet;
}
$req = new Google_Http_Request($url, $method, $headers);
$response = $curl->executeRequest($req);
if($response[2] == 200) {
$worksheetXml = simplexml_load_string($response[0]);
if($worksheetXml->entry) {
$this->worksheetid = basename(trim($worksheetXml->entry[0]->id));
}
}
}
}
}
if(!empty($this->spreadsheetid) && !empty($this->worksheetid)) {
return "https://spreadsheets.google.com/feeds/list/" . $this->spreadsheetid . "/" . $this->worksheetid . "/private/full";
}
return "";
}
private function formatColumnID($val) {
return preg_replace("/[^a-zA-Z0-9.-]/", "", strtolower($val));
}
}
I then use this test php file to add rows to to my spreadsheet:
$Spreadsheet = new Spreadsheet();
$Spreadsheet->
setSpreadsheet("test spreadsheet")->
setWorksheet("Sheet1")->
add(array("name" => "Cell 1", "email" => "Cell 2"));
With this I can delete a row / update a row and append a row. However, the MAIN reason I needed this was to INSERT a row. Has anyone figured out a way to do this? Any language is fine although id prefer a php solution.
You can call an Apps Script stand alone script from PHP using an HTTPS GET or POST request. PHP can make a GET or POST request, and Apps Script can obviously insert the row anywhere using SpreadsheetApp service. You'll probably want to use Content Service also inside of the Apps Script code to get a return confirmation back that the code completed.
You might want to use a POST request for better security. So, again, you can use Apps Script as an intermediary between your PHP and your spreadsheet. The doPost() in the Apps Script file will need an event handler, normally assigned to the letter "e":
doPost(e) {
//Get e and retrieve what the code should do
//Insert the row
};
Also, see this answer:
Stackoverflow - Call a custom GAS function from external URL

Categories