<?php
Class Instagram
{
public $username;
public $password;
private $guid;
private $my_uid;
private $userAgent = 'Instagram 6.21.2 Android (19/4.4.2; 480dpi; 1152x1920; Meizu; MX4; mx4; mt6595; en_US)';
private $instaSignature ='25eace5393646842f0d0c3fb2ac7d3cfa15c052436ee86b5406a8433f54d24a5';
private $instagramUrl = 'https://i.instagram.com/api/v1/';
public function Login($username, $password) {
$this->username = $username;
$this->password = $password;
$this->guid = $this->GenerateGuid();
$device_id = "android-" . $this->guid;
$data = '{"device_id":"'.$device_id.'","guid":"'.$this->guid.'","username":"'. $this->username.'","password":"'.$this->password.'","Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"}';
$sig = $this->GenerateSignature($data);
$data = 'signed_body='.$sig.'.'.urlencode($data).'&ig_sig_key_version=6';
$myid = $this->Request('accounts/login/', true, $data, false);
$decode = json_decode($myid[1], true);
$this->my_uid = $decode['logged_in_user']['pk'];
print_r($this->my_uid);
return $myid;
}
public function PostFollow($user_id) {
$device_id = "android-".$this->guid;
$data = '{"device_id":"'.$device_id.'","guid":"'. $this->guid .'","uid":"'.$this->my_uid.'","module_name":"feed_timeline","user_id":"'.$user_id.'","source_type":"5","filter_type":"0","extra":"{}","Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"}';
$sig = $this->GenerateSignature($data);
$new_data = 'signed_body='.$sig.'.'.urlencode($data).'&ig_sig_key_version=6';
return $this->Request('friendships/create/'.$user_id.'/', true, $new_data, true);
}
public function PostUnFollow($user_id) {
$device_id = "android-".$this->guid;
$data = '{"device_id":"'.$device_id.'","guid":"'. $this->guid .'","uid":"'.$this->my_uid.'","module_name":"feed_timeline","user_id":"'.$user_id.'","source_type":"5","filter_type":"0","extra":"{}","Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"}';
$sig = $this->GenerateSignature($data);
$new_data = 'signed_body='.$sig.'.'.urlencode($data).'&ig_sig_key_version=6';
return $this->Request('friendships/create/'.$user_id.'/', false, $new_data, true);
}
}
?>
return $this->Request('friendships/create/'.$user_id.'/', false, $new_data, true) - is this a correct cURL request?
Please refer to postfollow function (my follow code).
I want that the postUnfollow function will trigger auto unfollow users.
Please check my below code and check it's work or not
public function PostUnFollow($user_id,$username) {
$device_id = "android-".$this->guid;
$data = '{"device_id":"'.$device_id.'","guid":"'. $this->guid .'","uid":"'.$this->my_uid.'","module_name":"feed_timeline","user_id":"'.$user_id.'","source_type":"5","filter_type":"0","extra":"{}","Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"}';
$sig = $this->GenerateSignature($data);
$new_data = 'signed_body='.$sig.'.'.urlencode($data).'&ig_sig_key_version=6';
return $this->Request('friendships/destroy/'.$user_id.'/', true, $new_data, true,$username);
}
Related
I am using KBariotis module to integrate magento with National Bank of Greece.
I tried everything but it's not working.
At first, it would not recognise the module.
So I changed protected $_formBlockType = 'nbp/form_nbp'; on /model/standard.php to
protected $_formBlockType = 'nbp/form_NBP';
Now it recognises it as a valid payment option.
But on checkout, it redirects me to /checkout/onepage/failure
edit:
In the code model/NBP.php I see that getRedirectUrl() returns false and not what it should. Here is the code
<?php
class KBariotis_NBP_Model_NBP extends Mage_Core_Model_Abstract
{
private $proxyPayEndPoint = null;
private $merchantID = null;
private $merchantSecret = null;
private $newOrderStatus = null;
private $pageSetId = null;
private $enable3dSecure = null;
protected function _Construct()
{
$this->merchantID = Mage::getStoreConfig('payment/nbp/merchant_id');
$this->proxyPayEndPoint = Mage::getStoreConfig('payment/nbp/proxy_pay_endpoint');
$this->merchantSecret = Mage::getStoreConfig('payment/nbp/merchant_confirmation_pwd');
$this->pageSetId = Mage::getStoreConfig('payment/nbp/page_set_id');
$this->newOrderStatus = Mage::getStoreConfig('payment/nbp/order_status');
$this->enable3dSecure = Mage::getStoreConfig('payment/nbp/enable_3d_secure');
}
public function getRedirectUrl()
{
$order = new Mage_Sales_Model_Order();
$orderId = Mage::getSingleton('checkout/session')
->getLastRealOrderId();
$order->loadByIncrementId($orderId);
$orderTotal = $order->getBaseGrandTotal();
$successUrl = Mage::getUrl('nbp/payment/success/');
$request = $this->createXMLRequestPreTransaction($orderId, $orderTotal, $successUrl);
if ($response = $this->makeRequest($request))
return $response->HpsTxn->hps_url . '?HPS_SessionID=' . $response->HpsTxn->session_id;
else
return false;
}
private function createXMLRequestPreTransaction($orderId, $orderTotal, $successUrl)
{
$request = new SimpleXMLElement("<Request></Request>");
$request->addAttribute("version", "2");
$auth = $request->addChild("Authentication");
$auth->addChild("password", $this->merchantSecret);
$auth->addChild("client", $this->merchantID);
$transaction = $request->addChild("Transaction");
$txnDetails = $transaction->addChild("TxnDetails");
$txnDetails
->addChild("merchantreference", $orderId);
if ($this->enable3dSecure) {
$threeDSecure = $txnDetails->addChild("ThreeDSecure");
$browser = $threeDSecure->addChild("Browser");
$browser->addChild("device_category", 0);
$browser->addChild("accept_headers", "*/*");
$browser->addChild("user_agent", "IE/6.0");
$threeDSecure->addChild("purchase_datetime", date('Ymd H:i:s'));
$threeDSecure->addChild("purchase_desc", $orderId);
$threeDSecure->addChild("verify", "yes");
}
$txnDetails
->addChild("amount", $orderTotal)
->addAttribute("currency", "EUR");
$txnDetails
->addChild("capturemethod", "ecomm");
$hpsTxn = $transaction->addChild("HpsTxn");
$hpsTxn
->addChild("method", "setup_full");
$hpsTxn
->addChild("page_set_id", $this->pageSetId);
$hpsTxn
->addChild("return_url", $successUrl);
$hpsTxn
->addChild("expiry_url", Mage::getUrl(''));
$cardTxn = $transaction->addChild('CardTxn');
$cardTxn
->addChild("method", "auth");
return $request;
}
public function queryRefTransaction($ref)
{
$request = $this->createXMLRequestPostTransaction($ref);
if ($response = $this->makeRequest($request))
return $response->merchantreference;
return false;
}
private function createXMLRequestPostTransaction($ref)
{
$request = new SimpleXMLElement("<Request></Request>");
$request->addAttribute("version", "2");
$auth = $request->addChild("Authentication");
$auth->addChild("password", $this->merchantSecret);
$auth->addChild("client", $this->merchantID);
$transaction = $request->addChild("Transaction");
$historicTxn = $transaction->addChild("HistoricTxn");
$historicTxn
->addChild("method", "query");
$historicTxn
->addChild("reference", $ref);
return $request;
}
private function makeRequest($request)
{
$client = new Varien_Http_Client($this->proxyPayEndPoint);
$client->setMethod(Zend_Http_Client::POST);
$client->setRawData($request->asXML());
$response = $client->request();
if (!$response->isSuccessful())
throw new Mage_Payment_Exception('Could not communicate to payment server');
$responseBody = $response->getBody();
$response = simplexml_load_string($responseBody);
$status = intval($response->status);
if ($status != 1 && $status != 7)
Mage::log('Error from the Bank : ' . $responseBody);
if ($status == 7)
Mage::log('Bank refused the payment : ' . $responseBody);
if ($status == 1)
return $response;
return false;
}
public function getNewOrderStatus()
{
return $this->newOrderStatus;
}
}
Although, it's been 4 months since you posted this question I am answering.
Check that your proxyPayEndPoint is the correct valid url.
The page Set ID should be filled. (An id of an existed page that you you are using for validation).
In case you have 3DSecure enabled, you should have the elements correctly filled.
$browser->addChild("device_category", 0);
$headers = apache_request_headers();
$browser->addChild("accept_headers", ($headers['Accept']?(string)$headers['Accept']:"*/*"));
$browser->addChild("user_agent", (string)$_SERVER['HTTP_USER_AGENT']);
You could print the xml request (your_website_url/nbp/payment/redirect/) and see the response and what is probably missing from your structure.
i make a telegram bot with telegram botfather and i make my bot as admin in my public telegram channel , now i want to send message in channel by bot, this is my code for this work :
send.php code is :
<?php
require('telegram-bot-api.php');
$token = '10**************************************jM';
$bot = new telegram_bot($token);
$to = '#myChannel';
$rs = $bot->send_message($to , 'test' , null, null);
print_r($rs);
?>
and telegram-bot-api.php code is :
<?php
class ReplyKeyboardMarkup{
public $keyboard;
public $resize_keyboard;
public $one_time_keyboard;
public $selective;
function __construct($resize_keyboard=FALSE, $one_time_keyboard = FALSE, $selective=FALSE){
$this->keyboard=array();
$this->keyboard[0]=array();
$this->resize_keyboard=$resize_keyboard;
$this->one_time_keyboard=$one_time_keyboard;
$this->selective=$selective;
}
public function add_option($option){
$this->keyboard = $option;
}
}
class ReplyKeyboardHide{
public $hide_keyboard;
public $selective;
function __construct($hide_keyboard=TRUE, $selective = FALSE){
$this->hide_keyboard=$hide_keyboard;
$this->selective=$selective;
}
}
class ForceReply{
public $force_reply;
public $selective;
function __construct($force_reply=TRUE, $selective = FALSE){
$this->force_reply=$force_reply;
$this->selective=$selective;
}
}
class telegram_bot{
private $token;
private function open_url($url, $method="GET", $data=null){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
if($method==="POST"){
if(isset($data)){
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
}
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
return curl_exec($ch);
}
private function control_api($action, $data=NULL){
$token = $this->token;
$response = json_decode($this->open_url("https://api.telegram.org/bot$token$action", "POST", $data));
return $response;
}
function __construct($token){
$this->token=$token;
}
public function status(){
$response = $this->control_api("/getme");
return($response);
}
public function get_updates(){
$response = $this->control_api("/getUpdates");
return($response);
}
public function send_action($to, $action){
$data = array();
$data["chat_id"]=$to;
$data["action"]=$action;
$response = $this->control_api("/sendChatAction", $data);
return $response;
}
public function send_message($to, $msg, $id_msg=null, $reply=null){
$data = array();
$data["chat_id"]=$to;
$data["text"]=$msg;
$data["disable_web_page_preview"]="true";
if(isset($id_msg))
$data["reply_to_message_id"]=$id_msg;
if(isset($reply))
$data["reply_markup"]=$reply;
$response = $this->control_api("/sendMessage", $data);
return $response;
}
public function send_location($to, $lat, $lon, $id_msg=null, $reply=null){
$data = array();
$data["chat_id"]=$to;
$data["latitude"]=$lat;
$data["longitude"]=$lon;
if(isset($id_msg))
$data["reply_to_message_id"]=$id_msg;
if(isset($reply))
$data["reply_markup"]=$reply;
$response = $this->control_api("/sendLocation", $data);
return $response;
}
public function send_sticker($to, $sticker, $id_msg=null, $reply=null){
$data = array();
$data["chat_id"]=$to;
if(file_exists($sticker))$sticker="#".$sticker;
$data["sticker"]=$sticker;
if(isset($id_msg))
$data["reply_to_message_id"]=$id_msg;
if(isset($reply))
$data["reply_markup"]=$reply;
$response = $this->control_api("/sendSticker", $data);
return $response;
}
public function send_video($to, $video, $id_msg=null, $reply=null){
$data = array();
$data["chat_id"]=$to;
if(file_exists($video))$video="#".$video;
$data["video"]=$video;
if(isset($id_msg))
$data["reply_to_message_id"]=$id_msg;
if(isset($reply))
$data["reply_markup"]=$reply;
$response = $this->control_api("/sendVideo", $data);
return $response;
}
public function send_photo($to, $photo, $caption, $id_msg=null, $reply=null){
$data = array();
$data["chat_id"]=$to;
if(file_exists($photo))$photo="#".$photo;
$data["photo"]=$photo;
if(isset($caption)){
$data["caption"]=$caption;
}
if(isset($id_msg)){
$data["reply_to_message_id"]=$id_msg;
}
if(isset($reply))
$data["reply_markup"]=$reply;
$response = $this->control_api("/sendPhoto", $data);
return $response;
}
public function send_audio($to, $audio, $id_msg=null, $reply=null){
$data = array();
$data["chat_id"]=$to;
if(file_exists($audio))$audio="#".$audio;
$data["audio"]=$audio;
if(isset($id_msg)){
$data["reply_to_message_id"]=$id_msg;
}
if(isset($reply))
$data["reply_markup"]=$reply;
$response = $this->control_api("/sendAudio", $data);
return $response;
}
public function send_document($to, $document, $id_msg=null, $reply=null){
$data = array();
$data["chat_id"]=$to;
if(file_exists($audio))$document="#".$audio;
$data["document"]=$document;
if(isset($id_msg)){
$data["reply_to_message_id"]=$id_msg;
}
if(isset($reply))
$data["reply_markup"]=$reply;
$response = $this->control_api("/sendDocument", $data);
return $response;
}
public function forward_message($to, $from, $msg_id){
$data = array();
$data["chat_id"]=$to;
$data["from_chat_id"]=$from;
$data["message_id"]=$msg_id;
$response = $this->control_api("/forwardMessage", $data);
return $response;
}
public function set_webhook($url=null){
$data = array();
$data["url"]=$url;
$response = $this->control_api("/setWebhook", $data);
return $response;
}
public function get_user_profile_photos($id_user, $offset=null, $limit=null){
$data = array();
$data["user_id"]=$id_user;
if(isset($offset)){
$data["offset"]=$offset;
}
if(isset($limit)){
$data["limit"]=$limit;
}
$response = $this->control_api("/getUserProfilePhotos", $data);
return $response;
}
public function read_post_message(){
return json_decode(file_get_contents('php://input'));
}
}
?>
but when run send.php not send message to channel but when i replace chat_id with private chat_id or group chat_id , this code done very cool and send a message to group or my contact
Excuse me for my English language , sory :)
solved , i tested with httpRequster plugin for send a post request to this link :
https://api.telegram.org/bot1*******************************M/sendMessage
and posted parameters is :
chat_id = #myChannel_username
text = myMessage
i don't know why not worked my old code but work this request :D
any way thanks.
Bot has to be an admin of the channel for it to be able to send messages. None of the clients can help you make a bot an admin of a channel. Are you sure your bot is an admin of the channel?
Source: https://core.telegram.org/bots/api-changelog#october-8-2015
curl has this problem for SSL.
add this code to Solve problem :
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
You can also use numeric chat_id of your channel/group/account to make bot sent messages.
Easy way to get chat_id is to forward any message from your channel to bot called #userinfobot.
When I am testing my SOAP sever, I am getting the PHP warning html message with success response.
The SOAP server is like below:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
ini_set("soap.wsdl_cache_enabled", "0"); // disabling WSDL cache
ini_set("allow_url_fopen", "On");
$server = new SoapServer("../billerwebservice/BillerWS.wsdl"); // WSDL file for function definitions
$server->setClass("Payment");
//$server->addFunction(array("payAccount","confirmRequest","voidRequest")); // Same func name as in our WSDL XML, and below
$server->handle();
class payAccountResponse {
public $return;
}
class confirmResponse {
public $return;
}
class voidResponse {
public $return;
}
class Payment extends CI_Controller {
/*function __construct(){
parent::__construct();
$this->load->library("nusoap");
}*/
public function index(){
//url for this page is base_url('api/payment')
//http://tuition24.net/admin/api/payment
//this file is in tuition24 server => /admin/application/controllers/api/Payment.php
//ini_set('display_errors', 0);
/*$l_oServer = new soap_server();
// wsdl generation
$l_oServer->debug_flag=false;
$l_oServer->configureWSDL('BillerWS', 'http://billerwebservice.co.za');
$l_oServer->wsdl->schemaTargetNamespace = 'http://billerwebservice.co.za';
// add complex type
$l_oServer->wsdl->addComplexType(
'userData',
'complexType',
'struct',
'all',
''
);
// register method
$l_oServer->register('payAccount', array(
'login' => 'xsd:string',
'password'=>'xsd:string',
'verifyOnly'=>'xsd:boolean',
'amount'=>'xsd:string',
'transid'=>'xsd:string'
),
array('return'=>'tns:userData'),
'http://billerwebservice.co.za');*/
// pass incoming (posted) data
//$l_oServer->service(file_get_contents('php://input'));
}
public function payAccount ($parameters){
/*if($verifyOnly){
if($this->checklogin($login,$password)){
return $this->enquiry($username);
}else{
}
}else{*/
$return_array = new ArrayObject();
$parameters = get_object_vars($parameters); // Pull parameters from SOAP connection
// Sort out the parameters and grab their data
$loginId = $parameters['LoginID'];
$pwd = $parameters['Password'];
$paymentRefNumber = $parameters['PayRefNo'];
$amountDue = $parameters['AmountDue'];
$code = $this->generatecode($paymentRefNumber,$amountDue);
if($this->checklogin($loginId,$pwd)){
$params = new StdClass();
$params->RespCode = '200';
$params->RespDesc = 'Success';
$params->Code = $code;
$params->PayRefNo = $paymentRefNumber;
$currentDateTime = date("y-m-d h:i:s");
//update database
$this->db->insert('payment_transactions',array(
'datetime'=>$currentDateTime,
'transactionid'=>$paymentRefNumber,
'tokennumber'=>$code,
'status'=>'Success',
'amount'=>$amountDue
));
$response = new payAccountResponse();
$response->return = $params;
return $response;
}else{
}
//}
}
public function confirmRequest($parameters){
$return_array = new ArrayObject();
$parameters = get_object_vars($parameters); // Pull parameters from SOAP connection
// Sort out the parameters and grab their data
$loginId = $parameters['LoginID'];
$pwd = $parameters['Password'];
$paymentRefNumber = $parameters['PayRefNo'];
if($this->checklogin($loginId,$pwd)){
$params = new StdClass();
$params->messageCode = '200';
$params->messageDescription = 'ConfirmOK';
$currentDateTime = date("y-m-d h:i:s");
$data = $this->db->query("select * from payment_transactions where transactionid='$paymentRefNumber'")->row_array();
$tokennumber = $data['tokennumber'];
$this->db->insert('payment_transactions',array(
'datetime'=>$currentDateTime,
'transactionid'=>$paymentRefNumber,
'tokennumber'=>$tokennumber,
'status'=>'ConfirmOK',
'amount'=>$data['amount'],
));
//$this->confirm($paymentRefNumber,$tokennumber,$loginId);
$response = new confirmResponse();
$response->return = $params;
return $response;
}else{
}
}
public function voidRequest($parameters){
$return_array = new ArrayObject();
$parameters = get_object_vars($parameters); // Pull parameters from SOAP connection
// Sort out the parameters and grab their data
$loginId = $parameters['LoginID'];
$pwd = $parameters['Password'];
$paymentRefNumber = $parameters['PayRefNo'];
$currentDateTime = date("y-m-d h:i:s");
$params = new StdClass();
$params->messageCode = '200';
$params->messageDescription = 'VoidOK';
$data = $this->db->query("select * from payment_transactions where transactionid='$paymentRefNumber'")->row_array();
$this->db->insert('payment_transactions',array(
'datetime'=>$currentDateTime,
'transactionid'=>$paymentRefNumber,
'tokennumber'=>$data['tokennumber'],
'status'=>'VoidOK',
'amount'=>$data['amount'],
));
$this->cancel($paymentRefNumber);
$response = new voidResponse();
$response->return = $params;
return $response;
}
private function checklogin($username,$password){
$data = $this->db->query("select * from payment_user where username='$username' and password='$password'")->row_array();
if($data)
return true;
else
return false;
}
private function enquiry($username){
$data = $this->db->query("select balance from user where username='$username'")->row_array();
if($data)
return $data['balance'];
}
private function generatecode($transid,$amount){
$r = rand(100000000000,999999999999);
if(!$this->db->insert('code',array('code_no'=>$r,'amount'=>$amount,'transaction_id'=>$transid))){
return $this->generatecode($transid,$amount);
}
return $r;
}
private function cancel($transid){
$this->db->delete('code',array('transaction_id'=>$transid));
}
private function confirm($transid,$card_code,$username){
$data = $this->db->get_where('code',array('code_no'=>$card_code,'transaction_id'=>$transid,'active'=>1))->row_array();
if(!$data)
return false;
$card_amount = $data['amount'];
$user_id = $this->db->get_where('user',array('username'=>$username))->row_array()['id'];
$this->db->query("UPDATE user SET balance=balance+$card_amount where username='$username'");
$this->db->insert('transaction',array(
'user_id'=>$user_id,
'reason'=>'Credited '.$card_amount.' using #'.$card_code,
'type'=>3,
'amount'=>$card_amount,
'params'=>$card_code.' '.$transid
));
$this->db->update('code',array('active'=>0),array('code_no'=>$card_code));
$bal = $this->db->get_where('user',array('id'=>$user_id))->result()[0]->balance;
return $bal;
}
}
Please let me know why I am getting these warnings.
The image attached has error shown
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
I am making a simple twitter based login/signup system using the tutorial here. I get the oauth_token as well as oauth token secret every time I get the user to login. However, even when the user is already logged in, he is being asked to login again. I just wanted to know how do I check if the user is already logged in?
Do I need to store the oauth_token and oauth token secret in session? If I do store these in a session, how do i authenticate if they are valid?
The library used has something like this:
<?php
session_start();
class EpiOAuth
{
public $version = '1.0';
protected $requestTokenUrl;
protected $accessTokenUrl;
protected $authorizeUrl;
protected $consumerKey;
protected $consumerSecret;
protected $token;
protected $tokenSecret;
protected $signatureMethod;
public function getAccessToken()
{
$resp = $this->httpRequest('GET', $this->accessTokenUrl);
return new EpiOAuthResponse($resp);
}
public function getAuthorizationUrl()
{
$retval = "{$this->authorizeUrl}?";
$token = $this->getRequestToken();
return $this->authorizeUrl . '?oauth_token=' . $token->oauth_token;
}
public function getRequestToken()
{
$resp = $this->httpRequest('GET', $this->requestTokenUrl);
return new EpiOAuthResponse($resp);
}
public function httpRequest($method = null, $url = null, $params = null)
{
if(empty($method) || empty($url))
return false;
if(empty($params['oauth_signature']))
$params = $this->prepareParameters($method, $url, $params);
switch($method)
{
case 'GET':
return $this->httpGet($url, $params);
break;
case 'POST':
return $this->httpPost($url, $params);
break;
}
}
public function setToken($token = null, $secret = null)
{
$params = func_get_args();
$this->token = $token;
$this->tokenSecret = $secret;
}
public function encode($string)
{
return rawurlencode(utf8_encode($string));
}
protected function addOAuthHeaders(&$ch, $url, $oauthHeaders)
{
$_h = array('Expect:');
$urlParts = parse_url($url);
$oauth = 'Authorization: OAuth realm="' . $urlParts['path'] . '",';
foreach($oauthHeaders as $name => $value)
{
$oauth .= "{$name}=\"{$value}\",";
}
$_h[] = substr($oauth, 0, -1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $_h);
}
protected function generateNonce()
{
if(isset($this->nonce)) // for unit testing
return $this->nonce;
return md5(uniqid(rand(), true));
}
protected function generateSignature($method = null, $url = null, $params = null)
{
if(empty($method) || empty($url))
return false;
// concatenating
$concatenatedParams = '';
foreach($params as $k => $v)
{
$v = $this->encode($v);
$concatenatedParams .= "{$k}={$v}&";
}
$concatenatedParams = $this->encode(substr($concatenatedParams, 0, -1));
// normalize url
$normalizedUrl = $this->encode($this->normalizeUrl($url));
$method = $this->encode($method); // don't need this but why not?
$signatureBaseString = "{$method}&{$normalizedUrl}&{$concatenatedParams}";
return $this->signString($signatureBaseString);
}
protected function httpGet($url, $params = null)
{
if(count($params['request']) > 0)
{
$url .= '?';
foreach($params['request'] as $k => $v)
{
$url .= "{$k}={$v}&";
}
$url = substr($url, 0, -1);
}
$ch = curl_init($url);
$this->addOAuthHeaders($ch, $url, $params['oauth']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$resp = $this->curl->addCurl($ch);
return $resp;
}
protected function httpPost($url, $params = null)
{
$ch = curl_init($url);
$this->addOAuthHeaders($ch, $url, $params['oauth']);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params['request']));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$resp = $this->curl->addCurl($ch);
return $resp;
}
protected function normalizeUrl($url = null)
{
$urlParts = parse_url($url);
$scheme = strtolower($urlParts['scheme']);
$host = strtolower($urlParts['host']);
$port = intval($urlParts['port']);
$retval = "{$scheme}://{$host}";
if($port > 0 && ($scheme === 'http' && $port !== 80) || ($scheme === 'https' && $port !== 443))
{
$retval .= ":{$port}";
}
$retval .= $urlParts['path'];
if(!empty($urlParts['query']))
{
$retval .= "?{$urlParts['query']}";
}
return $retval;
}
protected function prepareParameters($method = null, $url = null, $params = null)
{
if(empty($method) || empty($url))
return false;
$oauth['oauth_consumer_key'] = $this->consumerKey;
$oauth['oauth_token'] = $this->token;
$oauth['oauth_nonce'] = $this->generateNonce();
$oauth['oauth_timestamp'] = !isset($this->timestamp) ? time() : $this->timestamp; // for unit test
$oauth['oauth_signature_method'] = $this->signatureMethod;
$oauth['oauth_version'] = $this->version;
// encoding
array_walk($oauth, array($this, 'encode'));
if(is_array($params))
array_walk($params, array($this, 'encode'));
$encodedParams = array_merge($oauth, (array)$params);
// sorting
ksort($encodedParams);
// signing
$oauth['oauth_signature'] = $this->encode($this->generateSignature($method, $url, $encodedParams));
return array('request' => $params, 'oauth' => $oauth);
}
protected function signString($string = null)
{
$retval = false;
switch($this->signatureMethod)
{
case 'HMAC-SHA1':
$key = $this->encode($this->consumerSecret) . '&' . $this->encode($this->tokenSecret);
$retval = base64_encode(hash_hmac('sha1', $string, $key, true));
break;
}
return $retval;
}
public function __construct($consumerKey, $consumerSecret, $signatureMethod='HMAC-SHA1')
{
$this->consumerKey = $consumerKey;
$this->consumerSecret = $consumerSecret;
$this->signatureMethod = $signatureMethod;
$this->curl = EpiCurl::getInstance();
}
}
class EpiOAuthResponse
{
private $__resp;
public function __construct($resp)
{
$this->__resp = $resp;
}
public function __get($name)
{
if($this->__resp->code < 200 || $this->__resp->code > 299)
return false;
parse_str($this->__resp->data, $result);
foreach($result as $k => $v)
{
$this->$k = $v;
}
return $result[$name];
}
}
The normal flow dictates that applications send request tokens to oauth/authorize in Twitter's implementation of the OAuth Specification. To take advantage of "Sign in with Twitter", applications should send request tokens received in the oauth_token parameter to oauth/authenticate instead.
(c) https://dev.twitter.com/docs/auth/sign-in-with-twitter
So find where their library (or your code) performs request to /authorize endpoint and replace it with /authenticate
About tokens: as long as you've received user tokens - store it in some persistent storage (database, file, etc) since that tokens are permanent (they will be valid until user haven't revoked them manually).
Enable option "Sign in with Twitter" for application OAuth Settings