I am using opencart 3 browser close customer logout, how to stop customer logout even browser is close - opencart

I am using opencart 3 my issue is that when customer close browser and open again customer is logout, i want to change this behavior, i need when customer once login he/she should not logout until he/she click logout button, even if he/she close the browser and open again he/she should remain login.

You have to modify 3 files in OpenCart to accomplish this.
/catalog/controller/account/login.php
During login process, you have to store customer ID and email in cookie. It worth to store them encrypted. Email is not enough, because you have to check that stored customer ID belongs to stored email.
public function index() {
[...]
if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) {
// Unset guest
unset($this->session->data['guest']);
// store customer ID and email encrypted
$my_customer_id = $this->customer->getId();
$my_customer_id_crypted = $this->encrypt($my_customer_id, "your_key_for_customer_id_encryption");
$my_email = $this->request->post['email'];
$my_email_crypted = $this->encrypt($this->request->post['email'], "your_key_for_email_encryption");
setcookie("MyCustomerID", $my_customer_id_crypted , time() + (365 * 24 * 60 * 60) , "/");
setcookie("MyEmail", $my_email_crypted , time() + (365 * 24 * 60 * 60) , "/");
[...]
}
[...]
}
[...]
// https://www.phpcluster.com/simple-two-way-encryption-in-php/
// you can use other encryption if you want, just an example
protected function encrypt($plainText, $key) {
$secretKey = md5($key);
$iv = substr( hash( 'sha256', "aaaabbbbcccccddddeweee" ), 0, 16 );
$encryptedText = openssl_encrypt($plainText, 'AES-128-CBC', $secretKey, OPENSSL_RAW_DATA, $iv);
return base64_encode($encryptedText);
}
/catalog/controller/account/logout.php
During logout process, you have to delete customer ID and email cookies
public function index() {
if ($this->customer->isLogged()) {
$this->customer->logout();
// delete cookies
unset($_COOKIE['MyCustomerID']);
unset($_COOKIE['MyEmail']);
setcookie("MyCustomerID", "", 0, "/");
setcookie("MyEmail", "", 0, "/");
[...]
}
[...]
}
/catalog/controller/common/footer.php
In this file you can auto login customer if everything is OK and extend cookie lifetime, footer is used on every page load so it is a good way I mean
public function index() {
[...]
$data['scripts'] = $this->document->getScripts('footer');
$data['styles'] = $this->document->getStyles('footer');
if (isset($_COOKIE["MyCustomerID"]) && isset($_COOKIE["MyEmail"]) && $_COOKIE["MyCustomerID"] != '' && $_COOKIE["MyEmail"] != '') {
$my_customer_id_crypted = $_COOKIE["MyCustomerID"];
$my_customer_id = $this->decrypt($my_customer_id_crypted, "your_key_for_customer_id_encryption");
$my_email_crypted = $_COOKIE["MyEmail"];
$my_email = $this->decrypt($my_email_crypted, "your_key_for_email_encryption");
$config = new Config();
$config->load('default');
if ( $my_customer_id != "" && $my_email != "" && $my_customer_id == (int)$my_customer_id ) {
if ( !$this->customer->isLogged() ) {
if ( $my_customer_id == $this->getCustomerIdByEmailAddress( $my_email ) ) { // auto login, when customer ID belongs to this email address
$this->customer->login($my_email, "", true); // we use OpenCart override log in method
//$this->log->write('customer logged in automatically');
$this->load->model('account/address');
if ($this->config->get('config_tax_customer') == 'payment') {
$this->session->data['payment_address'] = $this->model_account_address->getAddress($this->customer->getAddressId());
}
if ($this->config->get('config_tax_customer') == 'shipping') {
$this->session->data['shipping_address'] = $this->model_account_address->getAddress($this->customer->getAddressId());
}
// extend cookies lifetime
setcookie("MyCustomerID", $my_customer_id_crypted , time() + (365 * 24 * 60 * 60) , "/");
setcookie("MyEmail", $my_email_crypted , time() + (365 * 24 * 60 * 60) , "/");
$this->response->redirect($_SERVER['REQUEST_URI']);
}
}
}
}
[...]
}
// https://www.phpcluster.com/simple-two-way-encryption-in-php/
// decrypt function for previous used encryption
protected function decrypt($encryptedText, $key) {
$key = md5($key);
$iv = substr( hash( 'sha256', "aaaabbbbcccccddddeweee" ), 0, 16 );
$decryptedText = openssl_decrypt(base64_decode($encryptedText), 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $iv);
return $decryptedText;
}
protected function getCustomerIdByEmailAddress($email) {
$sql_txt = "";
$sql_txt .= "SELECT customer_id";
$sql_txt .= " FROM ".DB_PREFIX."customer";
$sql_txt .= " WHERE LOWER(email) = '".$this->db->escape(utf8_strtolower($email))."'";
$customer_query = $this->db->query($sql_txt);
if ($customer_query->num_rows)
{
return $customer_query->row['customer_id'];
}
else
{
return -1;
}
}
You can refine this code if you want, currently I use this method to auto login customer

Related

Amazon Gift Card Load Amazon Balance Api Integration In Php Laravel

I want to reward users on signing up to my app by giving them gift card balance in their amazon account and to do that i have used Load Amazon Balance api which is similar to Amazon Incentive api.
Amazon requires a digitally signed authorization payload in order to access the api. I've compared my code to amazon's process of digitally signing using aws secret key and aws access key. But its still giving me
"The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details."
I'm attaching the code of my class in the post. Can anyone help me out by looking at the code and telling if there is any mistake in the process i'm performing for sending information to the api. Thanks.
<?php
/**
* Created by PhpStorm.
*
* Date: 07-09-2018
* Time: 01:18 PM
*/
namespace App;
use App\AppConstant\AppConstant;
use App\Entities\Models\User;
use Illuminate\Support\Facades\Auth;
class AmazonReward
{
/**
* This is the bulk of the logic for making AGCOD calls.
*/
//Constants
public static $apikey;
public static $clientId = env("client_id");
public static $clientSecret = env("client_secret");
public static $awsSecretKey = env("client_secret");
public static $partnerId = env("partner_id");
public static $SERVICE_NAME = "AGCODService";
public static $ACCEPT_HEADER = "accept";
public static $CONTENT_HEADER = "content-type";
public static $HOST_HEADER = "host";
public static $XAMZDATE_HEADER = "x-amz-date";
public static $XAMZTARGET_HEADER = "x-amz-target";
public static $AUTHORIZATION_HEADER = "Authorization";
public static $AWS_SHA256_ALGORITHM = "AWS4-HMAC-SHA256";
public static $KEY_QUALIFIER = "AWS4";
public static $TERMINATION_STRING = "aws4_request";
const SERVICE_NAME = "AGCODService";
const ACCEPT_HEADER = "accept";
const CONTENT_HEADER = "content-type";
const HOST_HEADER = "host";
const XAMZDATE_HEADER = "x-amz-date";
const XAMZTARGET_HEADER = "x-amz-target";
const AUTHORIZATION_HEADER = "Authorization";
const AWS_SHA256_ALGORITHM = "AWS4-HMAC-SHA256";
const KEY_QUALIFIER = "AWS4";
const TERMINATION_STRING = "aws4_request";
const ENDPOINT ='agcod-v2.amazon.com';
// const ENDPOINT ='agcod-v2-gamma.amazon.com';
public static function get_paypload_giftcard($partnerId, $gcRequestId, $currencyCode, $gcAmount, $customer_id)
{
$amount = trim($gcAmount);
$payload = array(
"loadBalanceRequestId" => $gcRequestId,
"partnerId" => $partnerId,
"amount" =>
array(
"currencyCode" => $currencyCode,
"value" => floatval($amount)
),
"account" =>
array(
"id" => $customer_id,
"type" => "2"
),
"timestamp" => time(),
// "transactionSource" => [
// "sourceId" => ""
// ],
"externalReference" => "",
"notificationDetails" => [
"notificationMessage" => ""
]
);
return json_encode($payload);
}
/**
* Builds the "formal" request that can be hashed to verify the contents of the request.
* The request does not get sent to the server in this format, but the hash of this is.
*
* #return The formal request
*/
public static function buildCanonicalRequest($serviceOperation, $payloadHash, $customer_id) {
$ACCEPT_HEADER = self::ACCEPT_HEADER;
$HOST_HEADER = self::HOST_HEADER;
$XAMZDATE_HEADER = self::XAMZDATE_HEADER;
$XAMZTARGET_HEADER = self::XAMZTARGET_HEADER;
$ACCEPT_HEADER = self::ACCEPT_HEADER;
$dateTimeString = Self::getTimeStamp();
$header1 = Self::header1($serviceOperation);
$canonicalRequest = "POST\n/$serviceOperation HTTP/1.1\n\n$header1\n\n$ACCEPT_HEADER;$HOST_HEADER;$XAMZDATE_HEADER;$XAMZTARGET_HEADER\n$payloadHash";
return $canonicalRequest;
}
/**
* Returns part of the header used in the canonical request.
*
* #return the portion of the header.
*/
public static function header1($serviceOperation) {
$ACCEPT_HEADER = self::ACCEPT_HEADER;
$XAMZDATE_HEADER = self::XAMZDATE_HEADER;
$XAMZTARGET_HEADER = self::XAMZTARGET_HEADER;
$HOST_HEADER = Self::HOST_HEADER;
$dateTimeString = Self::getTimeStamp();
$endpoint = self::ENDPOINT;
$contentType = Self::getContentType();
return
"$ACCEPT_HEADER:$contentType\n$HOST_HEADER:$endpoint\n$XAMZDATE_HEADER:$dateTimeString\n$XAMZTARGET_HEADER:com.amazonaws.agcod.AGCODService.$serviceOperation";
}
public static function disburseFunds($customer_id){
$apiString = "https://" . Self::ENDPOINT . "/LoadAmazonBalance";
$ch = curl_init();
$xAmzDateTime = gmdate('Ymd\THis\Z');
$xAmzDate = substr($xAmzDateTime, 0, 8);
$xAmzTarget = "com.amazonaws.agcod.AGCODService.LoadAmazonBalance";
$region = "us-east-1";
$serviceOperation = "LoadAmazonBalance";
// $canonicalRequestHash = Self::myHash($canonicalRequest);
$payload = Self::get_paypload_giftcard( Self::$partnerId, Self::$partnerId . time(), "USD", 5.00, $customer_id);
$payloadHash = Self::myHash($payload);
$canonicalRequest = Self::buildCanonicalRequest($serviceOperation, $payloadHash , $customer_id);
$dateTimeString = Self::getTimeStamp();
$curl_response = Self::invokeRequest($payload, $xAmzDateTime,$canonicalRequest, $serviceOperation);
echo "<pre>";
print_r($curl_response);
exit;
$json = json_decode($curl_response);
if ( isset($json->message) || ! isset($json->cardInfo) )
{
echo "<pre>";
print_r($json);
exit;
$ret = array();
$ret['success']=false;
$ret['errorCode'] = time();
return $ret;
}
$ret = array();
$ret['success']=true;
$ret['gcValue']= $json->cardInfo->value->amount;
$ret["gcCode"]= $json->gcClaimCode;
$ret["gcResponseId"]= $json->gcId; ////done
$ret["gcRequestId"]=$json->creationRequestId;
echo "<pre>";
print_r($ret);
exit;
return $ret;
// echo "<pre>";
// print_r($canonicalRequestHash);
// exit;
// // $canonicalRequestHash = myHash($canonicalRequest);
// // $stringToSign = buildStringToSign($canonicalRequestHash);
// echo "<pre>";
// print_r($this->buildAuthSignature($stringToSign));
// exit;
// $authotization = "AWS4-HMAC-SHA256 Credential=AKIAIGHKAVYIDBOH3O3A/" . $xAmzTarget . "/" . $region . "/AGCODService/aws4_request,SignedHeaders=accept;host;x-amz-date;x-amz-target, Signature=ec86661c1d39f74b5891666505bb7656b172b0d060d911bee3b6a1c29ae17657";
// /*$post = http_build_query([
// ["Authorization" => "DEMO1"],
// ["x-amz-date" => $xAmzDate],
// ["x-amz-target" => $xAmzTarget],
// ["Accept" => "application/json"],
// ["Host" => "agcod-v2-gamma.amazon.com"]
// ]);*/
// // $post = [];
// $post = [];
// $post["loadBalanceRequestId"] = "Amazon123456";
// $post["partnerId"] = "";
// $post["amount"] = [];
// $post["amount"]["currencyCode"] = "";
// $post["amount"]["value"] = "";
// $post["account"] = [];
// $post["account"]["id"] = "F2044";
// $post["account"]["type"] = "0";
// $post["transactionSource"] = [];
// $post["transactionSource"]["sourceId"] = "";
// $post["externalReference"] = "";
// $post["notificationDetails"] = [];
// $post["notificationDetails"]["notificationMessage"] = "";
// $customHeaders = [
// "Authorization" => "Amazon",
// "x-amz-date" => $xAmzDateTime,
// "x-amz-target" => $xAmzTarget,
// "Accept" => "application/json",
// "Host" => "agcod-v2-gamma.amazon.com"
// ];
// curl_setopt($ch, CURLOPT_URL, $apiString);
// curl_setopt($ch, CURLOPT_POST, 1);
// curl_setopt($ch, CURLOPT_POSTFIELDS,$post);
// curl_setopt($ch, CURLOPT_HTTPHEADER, $customHeaders);
// curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// $server_output = curl_exec($ch);
// curl_close ($ch);
// // Further processing ...
// if ($server_output == "OK") {
// }else{
// }
}
/**
* Builds the authenication string used to prove that the request is allowed and made by the right party.
*
* #param $stringToSign The string to sign.
* #return The authenication signature.
*/
public static function buildAuthSignature($dateString, $stringToSign) {
$AWS_SHA256_ALGORITHM = Self::AWS_SHA256_ALGORITHM;
$SERVICE_NAME = Self::SERVICE_NAME;
$TERMINATION_STRING = Self::TERMINATION_STRING;
$ACCEPT_HEADER = Self::ACCEPT_HEADER;
$HOST_HEADER = Self::HOST_HEADER;
$XAMZDATE_HEADER = Self::XAMZDATE_HEADER;
$XAMZTARGET_HEADER = Self::XAMZTARGET_HEADER;
$awsKeyId = Self::$clientId;
$regionName= Self::getRegion();
$derivedKey = Self::buildDerivedKey(Self::getDateString($dateString));
$derivedKey_lower = Self::buildDerivedKey(Self::getDateString($dateString), false);
$dateString = Self::getDateString($dateString);
// Calculate signature per http://docs.aws.amazon.com/general/latest/gr/sigv4-calculate-signature.html
$finalSignature = Self::hmac($stringToSign, $derivedKey, false);
// Assemble Authorization Header with signing information
// per http://docs.aws.amazon.com/general/latest/gr/sigv4-add-signature-to-request.html
$authorizationValue =
$AWS_SHA256_ALGORITHM
. " Credential=" . $awsKeyId
. "/" . $dateString . "/" . $regionName . "/" . $SERVICE_NAME . "/" . $TERMINATION_STRING . ","
. " SignedHeaders="
. $ACCEPT_HEADER . ";" . $HOST_HEADER . ";" . $XAMZDATE_HEADER . ";" . $XAMZTARGET_HEADER . ","
. " Signature="
. $finalSignature;
return $authorizationValue;
}
/**
* Hashes the string using sha256, the standard AWS hash.
*
* #param $data a string to sign
* #return a string hash of $data
*/
public static function myHash($data) {
return hash("sha256",$data);
}
/**
* Builds the string that gets hashed and used in the authenication.
*
* #param $canonicalRequestHash The hash of the canonicalRequest
* #return The string to sign.
*/
public static function buildStringToSign($canonicalRequestHash){
$AWS_SHA256_ALGORITHM = Self::AWS_SHA256_ALGORITHM;
$TERMINATION_STRING = Self::TERMINATION_STRING;
$SERVICE_NAME = Self::SERVICE_NAME;
$awsSecretKey = Self::$awsSecretKey;
$regionName = Self::getRegion();
$dateTimeString = Self::getTimeStamp();
$dateString = Self::getDateString($dateTimeString);
$stringToSign = "$AWS_SHA256_ALGORITHM\n$dateTimeString\n$dateString/$regionName/$SERVICE_NAME/$TERMINATION_STRING\n$canonicalRequestHash";
return $stringToSign;
}
/**
* Gets the time stamp used to make the request. If not set by the client it is set to the current time on the first call to this function.
*
* #return The time stamp
*/
public static function getTimeStamp() {
global $timeStamp;
if(!isset($timeStamp)) {
//GMT time. Format is YYYYMMDDTHHmmssZ where T and Z are literals, YYYY is 4 digit year, MM is 2 digit month, DD is 2 digit day, HH is 2 digit hour (24 hour clock) mm is 2 digit minute, ss is 2 digit second.
$timeStamp = gmdate('Ymd\THis\Z');
}
return $timeStamp;
}
/**
* Get the format that we will make the request in. This tells the server how to parse the request.
* This value is retrieved from the client and can either be json or xml.
*
* #return The request format as to be passed to the AGCOD server.
*/
public static function getContentType() {
return "application/json"; //Request in JSON format
}
/**
* Makes the service call to the AGCOD server.
*
* #return The repsonse from the server (in XML or JSON format) with HTML character escaped.
*/
public static function invokeRequest($payload, $dateTimeString,$canonicalRequest, $serviceOperation) {
$KEY_QUALIFIER = self::KEY_QUALIFIER;
$ACCEPT_HEADER = self::ACCEPT_HEADER;
$CONTENT_HEADER = self::CONTENT_HEADER;
$HOST_HEADER = self::HOST_HEADER;
$XAMZDATE_HEADER = self::XAMZDATE_HEADER;
$XAMZTARGET_HEADER = self::XAMZTARGET_HEADER;
$AUTHORIZATION_HEADER = self::AUTHORIZATION_HEADER;
$canonicalRequestHash = Self::myHash($canonicalRequest);
$stringToSign = Self::buildStringToSign($canonicalRequestHash);
$authorizationValue = Self::buildAuthSignature($dateTimeString, $stringToSign);
$endpoint = Self::ENDPOINT;
$regionName = Self::getRegion();
$SERVICE_NAME = "AGCODService";
$serviceTarget = "com.amazonaws.agcod." . $SERVICE_NAME . "." . $serviceOperation;
$contentType = Self::getContentType();
$url = "https://" . Self::ENDPOINT . "/" . $serviceOperation;
// print_r($url);
// exit;
//Prepare to send the data to the server
$handle = curl_init($url);
//Yes, do POST not GET
curl_setopt($handle, CURLOPT_POST, true);
//This is header, not post fields
curl_setopt($handle, CURLOPT_HTTPHEADER , array(
"Content-Type:$contentType",
'Content-Length: ' . strlen($payload),
$AUTHORIZATION_HEADER. ":" . $authorizationValue,
$XAMZDATE_HEADER . ":" . $dateTimeString,
$XAMZTARGET_HEADER . ":" . $serviceTarget,
"host:" . Self::ENDPOINT,
$ACCEPT_HEADER . ":" . $contentType
));
curl_setopt($handle, CURLOPT_POSTFIELDS, $payload);
//Yes, don't print the result to the web page, just give it to us in a string.
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
//Do the request
$result = curl_exec($handle);
if (empty($result)) {
// some kind of an error happened
die(curl_error($handle));
curl_close($handle); // close cURL handler
}
//Free the resource
curl_close($handle);
$signaturePos = strpos($authorizationValue, "Signature=");
if($signaturePos == FALSE || $signaturePos + 10 >= strlen($authorizationValue)) {
$signatureStr = "Malformed";
}
else {
$signatureStr = substr($authorizationValue, $signaturePos + 10);
}
print_r($result);
exit;
return $result;
}
/**
* Gets the region based on the server we connect too.
*
* #return The region.
*/
public static function getRegion() {
$endpoint = Self::ENDPOINT;
$regionName = "us-east-1";
if ($endpoint == "agcod-v2-eu.amazon.com" || $endpoint == "agcod-v2-eu-gamma.amazon.com") {
$regionName = "eu-west-1";
}
else if ($endpoint == "agcod-v2-fe.amazon.com" || $endpoint == "agcod-v2-fe-gamma.amazon.com") {
$regionName = "us-west-2";
}
return $regionName;
}
/**
* Performs a hmac hash using sha256, which is what AWS uses.
*
* #param $data The data to sign.
* #param $key The key to sign the data with.
* #param $raw true to provide a raw ascii string, false to use a hex string.
* #return the hash of $data
*/
public static function hmac($data, $key, $raw = true) {
return hash_hmac("sha256", $data, $key, $raw);
}
/**
* Gets the date for the request, which is either what the client passed in, or today if none was given.
*
* #return The date in YYYYMMDD format.
*/
public static function getDateString($dateTimeString) {
// $dateTimeString = Self::getTimeStamp();
return substr($dateTimeString, 0, 8);
}
/**
* Builds the derived key, which is used for authorizating the request.
*
* #param $rawOutput true to return an ascii string using raw byes, false to return a hex string
*/
public static function buildDerivedKey($dateString, $rawOutput = true) {
$KEY_QUALIFIER = Self::KEY_QUALIFIER;
$TERMINATION_STRING = Self::TERMINATION_STRING;
$SERVICE_NAME= Self::SERVICE_NAME;
// Get pasted AWS Secret Key from user input
$awsSecretKey = Self::$awsSecretKey;
// Append Key Qaulifier, "AWS4", to secret key per http://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html
$signatureAWSKey = $KEY_QUALIFIER . $awsSecretKey;
$regionName = Self::getRegion();
// $dateString = Self::getDateString();
$kDate = Self::hmac($dateString, $signatureAWSKey);
$kRegion = Self::hmac($regionName, $kDate);
$kService = Self::hmac($SERVICE_NAME, $kRegion);
// Derived the Signing key (derivedKey aka kSigning)
$derivedKey = Self::hmac($TERMINATION_STRING, $kService, $rawOutput);
return $derivedKey;
}
}

Cannot logout from facebook in a windows8 phone app using phonegap. how can I solve this?

Hello guys I am implementing logout from facebook functionality in my windows 8 phone application. By using the given below code I am able to logout from the facebook but when I again click on the facebook login button, then it automatically logged in without asking for the email and password.
var redir_url1 = "http://www.facebook.com/connect/logout_success.html";
//redir_url1 is used to redirect it
alert("inside prototype logout");
//store the value of accesstoken locally in finalAccessTokens
var finalAccessToken1 = window.localStorage.getItem("finalAccessTokens");
alert("finalAccessToken1" + finalAccessToken1);
var authorize_url = "https://www.facebook.com/logout.php?confirm=1";
//alert("authorize_url" + authorize_url);
authorize_url += "next=" + redir_url1;
authorize_url += "&access_token=" + finalAccessToken1;
alert("logout url: " + authorize_url);
resetSession();
showWebPage1(authorize_url);
//call a function to open the webpage
}
function showWebPage1(loc) {
alert("logout loc" + loc);
// var locs=this.loc;
cordova.exec(success1, error1, "InAppBrowser", "ShowInAppBrowser", loc);
}
function success1(e) {
alert("logout success");
//var accessToken = window.localStorage.getItem("finalAccessTokens");
// var url = 'https://graph.facebook.com/me?access_token=' + accessToken;
//localStorage.removeItem(cookies);
//localStorage.removeItem(finalAccessTokens);
// closeAndClearTokenInformation;
//ClearInternetCacheAsync();
alert("After removing access token" + `enter code here`window.localStorage.getItem("finalAccessTokens"));
//finalAccessTokens is used to locally store the value of access token
window.localStorage.clear();
alert("success" + JSON.stringify(e));
var successLogout = JSON.stringify(e);
if ((successLogout.indexOf('https://www.facebook.com/home.php') != -1) &&
(successLogout.indexOf('loadstop') != -1)) {
alert("sss in close");
cordova.exec(null, null, "InAppBrowser", "close", []);
alert("after the handle is closed.....");
this.resetSession();
//to reset the session
}
}
function error1() {
alert("err");
}
FBConnect.prototype.resetSession = function () {
alert("session reset");
this.status = "unknown";
this.session = {};
alert("clear access token/////");
this.session.access_token = null;
alert(this.session.access_token);
this.session.expires = new Date().valueOf() - 1000;
this.session.secret = null;
this.session.session_key = null;
this.session.sig = null;
this.session.uid = null;
alert(this.session.uid);
}
You have to remove WebBrowser cookies after you logout. I am not sure how you can do that using PhoneGap, but in a C#/XAML app you can remove them like this:
await new WebBrowser().ClearCookiesAsync();

Will PayPal Pro processor work for PayPal Advance Payments?

I am working with CiviCRM in a Wordpress install, and it has a payment processor written for PayPal Pro. However, we need to use PayPal Advanced instead. Does anyone know if the processor / API for PayPal Pro is somehow backwards compatible for PayPal Advanced Payments?
Here is the current IPN code:
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.3 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2013 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* #package CRM
* #copyright CiviCRM LLC (c) 2004-2013
* $Id$
*
*/
class CRM_Core_Payment_PayPalProIPN extends CRM_Core_Payment_BaseIPN {
static $_paymentProcessor = NULL;
function __construct() {
parent::__construct();
}
function getValue($name, $abort = TRUE) {
if (!empty($_POST)) {
$rpInvoiceArray = array();
$value = NULL;
$rpInvoiceArray = explode('&', $_POST['rp_invoice_id']);
foreach ($rpInvoiceArray as $rpInvoiceValue) {
$rpValueArray = explode('=', $rpInvoiceValue);
if ($rpValueArray[0] == $name) {
$value = $rpValueArray[1];
}
}
if ($value == NULL && $abort) {
echo "Failure: Missing Parameter $name<p>";
exit();
}
else {
return $value;
}
}
else {
return NULL;
}
}
static function retrieve($name, $type, $location = 'POST', $abort = TRUE) {
static $store = NULL;
$value = CRM_Utils_Request::retrieve($name, $type, $store,
FALSE, NULL, $location
);
if ($abort && $value === NULL) {
CRM_Core_Error::debug_log_message("Could not find an entry for $name in $location");
echo "Failure: Missing Parameter<p>";
exit();
}
return $value;
}
function recur(&$input, &$ids, &$objects, $first) {
if (!isset($input['txnType'])) {
CRM_Core_Error::debug_log_message("Could not find txn_type in input request");
echo "Failure: Invalid parameters<p>";
return FALSE;
}
if ($input['txnType'] == 'recurring_payment' &&
$input['paymentStatus'] != 'Completed'
) {
CRM_Core_Error::debug_log_message("Ignore all IPN payments that are not completed");
echo "Failure: Invalid parameters<p>";
return FALSE;
}
$recur = &$objects['contributionRecur'];
// make sure the invoice ids match
// make sure the invoice is valid and matches what we have in
// the contribution record
if ($recur->invoice_id != $input['invoice']) {
CRM_Core_Error::debug_log_message("Invoice values dont match between database and IPN request recur is " . $recur->invoice_id . " input is " . $input['invoice']);
echo "Failure: Invoice values dont match between database and IPN request recur is " . $recur->invoice_id . " input is " . $input['invoice'];
return FALSE;
}
$now = date('YmdHis');
// fix dates that already exist
$dates = array('create', 'start', 'end', 'cancel', 'modified');
foreach ($dates as $date) {
$name = "{$date}_date";
if ($recur->$name) {
$recur->$name = CRM_Utils_Date::isoToMysql($recur->$name);
}
}
$sendNotification = FALSE;
$subscriptionPaymentStatus = NULL;
//List of Transaction Type
/*
recurring_payment_profile_created RP Profile Created
recurring_payment RP Sucessful Payment
recurring_payment_failed RP Failed Payment
recurring_payment_profile_cancel RP Profile Cancelled
recurring_payment_expired RP Profile Expired
recurring_payment_skipped RP Profile Skipped
recurring_payment_outstanding_payment RP Sucessful Outstanding Payment
recurring_payment_outstanding_payment_failed RP Failed Outstanding Payment
recurring_payment_suspended RP Profile Suspended
recurring_payment_suspended_due_to_max_failed_payment RP Profile Suspended due to Max Failed Payment
*/
//set transaction type
$txnType = $_POST['txn_type'];
//Changes for paypal pro recurring payment
switch ($txnType) {
case 'recurring_payment_profile_created':
$recur->create_date = $now;
$recur->contribution_status_id = 2;
$recur->processor_id = $_POST['recurring_payment_id'];
$recur->trxn_id = $recur->processor_id;
$subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_START;
$sendNotification = TRUE;
break;
case 'recurring_payment':
if ($first) {
$recur->start_date = $now;
}
else {
$recur->modified_date = $now;
}
//contribution installment is completed
if ($_POST['profile_status'] == 'Expired') {
$recur->contribution_status_id = 1;
$recur->end_date = $now;
$sendNotification = TRUE;
$subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_END;
}
// make sure the contribution status is not done
// since order of ipn's is unknown
if ($recur->contribution_status_id != 1) {
$recur->contribution_status_id = 5;
}
break;
}
$recur->save();
if ($sendNotification) {
$autoRenewMembership = FALSE;
if ($recur->id &&
isset($ids['membership']) && $ids['membership']
) {
$autoRenewMembership = TRUE;
}
//send recurring Notification email for user
CRM_Contribute_BAO_ContributionPage::recurringNotify($subscriptionPaymentStatus,
$ids['contact'],
$ids['contributionPage'],
$recur,
$autoRenewMembership
);
}
if ($txnType != 'recurring_payment') {
return;
}
if (!$first) {
//check if this contribution transaction is already processed
//if not create a contribution and then get it processed
$contribution = new CRM_Contribute_BAO_Contribution();
$contribution->trxn_id = $input['trxn_id'];
if ($contribution->trxn_id && $contribution->find()) {
CRM_Core_Error::debug_log_message("returning since contribution has already been handled");
echo "Success: Contribution has already been handled<p>";
return TRUE;
}
$contribution->contact_id = $ids['contact'];
$contribution->financial_type_id = $objects['contributionType']->id;
$contribution->contribution_page_id = $ids['contributionPage'];
$contribution->contribution_recur_id = $ids['contributionRecur'];
$contribution->receive_date = $now;
$contribution->currency = $objects['contribution']->currency;
$contribution->payment_instrument_id = $objects['contribution']->payment_instrument_id;
$contribution->amount_level = $objects['contribution']->amount_level;
$objects['contribution'] = &$contribution;
}
$this->single($input, $ids, $objects,
TRUE, $first
);
}
function single(&$input, &$ids, &$objects, $recur = FALSE, $first = FALSE) {
$contribution = &$objects['contribution'];
// make sure the invoice is valid and matches what we have in the contribution record
if ((!$recur) || ($recur && $first)) {
if ($contribution->invoice_id != $input['invoice']) {
CRM_Core_Error::debug_log_message("Invoice values dont match between database and IPN request");
echo "Failure: Invoice values dont match between database and IPN request<p>contribution is" . $contribution->invoice_id . " and input is " . $input['invoice'];
return FALSE;
}
}
else {
$contribution->invoice_id = md5(uniqid(rand(), TRUE));
}
if (!$recur) {
if ($contribution->total_amount != $input['amount']) {
CRM_Core_Error::debug_log_message("Amount values dont match between database and IPN request");
echo "Failure: Amount values dont match between database and IPN request<p>";
return FALSE;
}
}
else {
$contribution->total_amount = $input['amount'];
}
$transaction = new CRM_Core_Transaction();
// fix for CRM-2842
// if ( ! $this->createContact( $input, $ids, $objects ) ) {
// return false;
// }
$participant = &$objects['participant'];
$membership = &$objects['membership'];
$status = $input['paymentStatus'];
if ($status == 'Denied' || $status == 'Failed' || $status == 'Voided') {
return $this->failed($objects, $transaction);
}
elseif ($status == 'Pending') {
return $this->pending($objects, $transaction);
}
elseif ($status == 'Refunded' || $status == 'Reversed') {
return $this->cancelled($objects, $transaction);
}
elseif ($status != 'Completed') {
return $this->unhandled($objects, $transaction);
}
// check if contribution is already completed, if so we ignore this ipn
if ($contribution->contribution_status_id == 1) {
$transaction->commit();
CRM_Core_Error::debug_log_message("returning since contribution has already been handled");
echo "Success: Contribution has already been handled<p>";
return TRUE;
}
$this->completeTransaction($input, $ids, $objects, $transaction, $recur);
}
function main($component = 'contribute') {
CRM_Core_Error::debug_var('GET', $_GET, TRUE, TRUE);
CRM_Core_Error::debug_var('POST', $_POST, TRUE, TRUE);
$objects = $ids = $input = array();
$input['component'] = $component;
// get the contribution and contact ids from the GET params
$ids['contact'] = self::getValue('c', TRUE);
$ids['contribution'] = self::getValue('b', TRUE);
$this->getInput($input, $ids);
if ($component == 'event') {
$ids['event'] = self::getValue('e', TRUE);
$ids['participant'] = self::getValue('p', TRUE);
$ids['contributionRecur'] = self::getValue('r', FALSE);
}
else {
// get the optional ids
$ids['membership'] = self::retrieve('membershipID', 'Integer', 'GET', FALSE);
$ids['contributionRecur'] = self::getValue('r', FALSE);
$ids['contributionPage'] = self::getValue('p', FALSE);
$ids['related_contact'] = self::retrieve('relatedContactID', 'Integer', 'GET', FALSE);
$ids['onbehalf_dupe_alert'] = self::retrieve('onBehalfDupeAlert', 'Integer', 'GET', FALSE);
}
if (!$ids['membership'] && $ids['contributionRecur']) {
$sql = "
SELECT m.id
FROM civicrm_membership m
INNER JOIN civicrm_membership_payment mp ON m.id = mp.membership_id AND mp.contribution_id = %1
WHERE m.contribution_recur_id = %2
LIMIT 1";
$sqlParams = array(1 => array($ids['contribution'], 'Integer'),
2 => array($ids['contributionRecur'], 'Integer'),
);
if ($membershipId = CRM_Core_DAO::singleValueQuery($sql, $sqlParams)) {
$ids['membership'] = $membershipId;
}
}
$paymentProcessorID = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType',
'PayPal', 'id', 'name'
);
if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
return FALSE;
}
self::$_paymentProcessor = &$objects['paymentProcessor'];
if ($component == 'contribute' || $component == 'event') {
if ($ids['contributionRecur']) {
// check if first contribution is completed, else complete first contribution
$first = TRUE;
if ($objects['contribution']->contribution_status_id == 1) {
$first = FALSE;
}
return $this->recur($input, $ids, $objects, $first);
}
else {
return $this->single($input, $ids, $objects, FALSE, FALSE);
}
}
else {
return $this->single($input, $ids, $objects, FALSE, FALSE);
}
}
function getInput(&$input, &$ids) {
if (!$this->getBillingID($ids)) {
return FALSE;
}
$input['txnType'] = self::retrieve('txn_type', 'String', 'POST', FALSE);
$input['paymentStatus'] = self::retrieve('payment_status', 'String', 'POST', FALSE);
$input['invoice'] = self::getValue('i', TRUE);
$input['amount'] = self::retrieve('mc_gross', 'Money', 'POST', FALSE);
$input['reasonCode'] = self::retrieve('ReasonCode', 'String', 'POST', FALSE);
$billingID = $ids['billing'];
$lookup = array(
"first_name" => 'first_name',
"last_name" => 'last_name',
"street_address-{$billingID}" => 'address_street',
"city-{$billingID}" => 'address_city',
"state-{$billingID}" => 'address_state',
"postal_code-{$billingID}" => 'address_zip',
"country-{$billingID}" => 'address_country_code',
);
foreach ($lookup as $name => $paypalName) {
$value = self::retrieve($paypalName, 'String', 'POST', FALSE);
$input[$name] = $value ? $value : NULL;
}
$input['is_test'] = self::retrieve('test_ipn', 'Integer', 'POST', FALSE);
$input['fee_amount'] = self::retrieve('mc_fee', 'Money', 'POST', FALSE);
$input['net_amount'] = self::retrieve('settle_amount', 'Money', 'POST', FALSE);
$input['trxn_id'] = self::retrieve('txn_id', 'String', 'POST', FALSE);
}
}

Codeigniter web services

I'm using Codeigniter 1.7. Does anyone have any experience of creating web services with PHP, particularly within the CodeIgniter framework? What are security measures need to consider while implementing web services? How to provide authentication with API keys?
Any Ideas?
It depends on the kind of web service you are inquiring about. Is the web service going to be a daemon for example? or a typical online web service. For either of these you must implement a RESTful type. RESTful meaning a stateless connection. This is where API keys are used; to identity a user for example.
Luckily Codeigniter is one with many libraries and extensions. An example of such libraries can be here: https://github.com/philsturgeon/codeigniter-restserver
Now for security concerns: API keys would replace sessions or any state. You would have to make full checks on the api. Many sites that implement APIs offer different solutions to the same end result.
Authentication with API keys are simple. You would check it against a storage type(database).
Here is a tutorial using codeigniter and the library linked previously: http://net.tutsplus.com/tutorials/php/working-with-restful-services-in-codeigniter-2/
This might be somewhat vague, but since you dont have any specific problems or apparent needs its hard to be specific.
EDIT:
In that case it would be better implementing a RESTful interface so that your iphone app can also use all of the user functionalities that your service provides. The best way would be to make everything accessible in one way. Meaning not having different controllers / models for the iphone connections and web connections.
So for example you could have the following controller:
<?php
class Auth extends CI_Controller{
public function login(){
//Check if their accessing using a RESTful interface;
$restful = $this->rest->check();
if($restful){
//Check for the API keys;
$apiKey = $this->input->get('apiKey');
$secretKey = $this->input->get('secretKey');
//If you have any rules apon the keys you may check it (i.e. their lengths,
//character restrictions, etc...)
if(strlen($apiKey) == 10 and strlen($secretKey) == 14)
{
//Now check against the database if the keys are acceptable;
$this->db->where('apiKey', $apiKey);
$this->db->where('secretKey', $secretKey);
$this->db->limit(1);
$query = $this->db->get('keys');
if($this->db->count_all_results() == 1)
{
//It's accepted the keys now authenticate the user;
foreach ($query->result() as $row)
{
$user_id = $row->user_id;
//Now generate a response key;
$response_key = $this->somemodel->response_key($user_id);
//Now return the response key;
die(json_encode( array(
'response_key' => $response_key,
'user_id' => $user_id
)
)
);
} //End of Foreach
}//End of Result Count
}//End of length / character check;
} else {
//Perform your usual session login here...;
}
}
}
?>
Now this is just a small example for performing these types of requests. This could apply to any type of controller. Though there are a few options here. You could make every request pass the apikey, and the secret each time and verify it at each request. Or you could have some sort of whitelist that once you have been verified the first time each request after that would be whitelisted, and or black listed on the opposite.
Hope this helps,
Daniel
<?php
//First Create Api file in controller name Api.php
/*
api call in postman
login :
email , password
http://localhost/demo/api/login
https://prnt.sc/pbs2do
register (user): :
fullname , email , password , recipeunit
http://localhost/demo/api/signup
https://prnt.sc/pbs3cc
profile and list (user profile and all user ) :
View Profile : email, if all then pass blank
http://localhost/demo/api/userlist
change password :
http://localhost/demo/api/change_password
email ,password ,newpassword , conformnewpassword (if needed)
https://prnt.sc/pbs3rt
*/
if(!defined('BASEPATH')) exit('No direct script access allowed');
require APPPATH . '/libraries/BaseController.php'; // this file will download first and pest in library
class Api extends BaseController
{
/**
* This is default constructor of the class
*/
public function __construct()
{
parent::__construct();
$this->load->model('api/signup_model','signup_model');
}
/**
* Index Page for this controller.
*/
public function index()
{
}
public function signup()
{
$this->signup_model->signup();
}
public function login()
{
$this->signup_model->login();
}
public function userlist()
{
$this->signup_model->userlist();
}
public function edit_user()
{
$this->signup_model->edit_user();
}
public function change_password()
{
$this->signup_model->change_password();
}
public function testpass()
{
$this->signup_model->testpass();
}
}
// then create model in model folder create api folder create signup_model.php file
//after that
if (!defined('BASEPATH')) exit('No direct script access allowed');
class Signup_model extends CI_Model {
public function __construct()
{
parent::__construct();
$this->load->database(); /* load database library */
}
// User register (signin) process
public function signup($data = array())
{
// another db field update like dt_createddate
if(!array_key_exists('dt_createddate', $data)){
$data['dt_createddate'] = date("Y-m-d H:i:s");
}
if(!array_key_exists('dt_updateddate', $data)){
$data['dt_updateddate'] = date("Y-m-d H:i:s");
}
if(!array_key_exists('dt_updateddate', $data)){
$data['dt_updateddate'] = date("Y-m-d H:i:s");
}
$data['var_fullname'] = $this->input->post('fullname');
$data['var_email'] = $this->input->post('email');
$data['var_password'] =getHashedPassword($this->input->post('password')) ;
$data['int_recipeunit'] = $this->input->post('recipeunit');
// if(!empty($data['var_fullname']) && !empty($data['var_email']) && !empty($data['var_password']) ){ }
/* check emailid all ready exist or not */
$email_check=$this->input->post('email');
$this->db->select('var_email');
$this->db->from('tbl_user');
$this->db->where('var_email', $email_check);
$query = $this->db->get();
$user = $query->result();
if(!empty($user))
{
echo "{\"status\" : \"404\",\"message\" : \"Email all ready register\",\"data\":".str_replace("<p>","",'{}'). "}";
}
else
{
$insert = $this->db->insert('tbl_user', $data);
if($insert){
$this->db->select('var_email as email,var_fullname as fullname,dt_createddate as createdate');
$insert_id = $this->db->insert_id();
$query = $this->db->get_where('tbl_user', array('int_id' => $insert_id));
echo "{\"status\" : \"200\",\"message\" : \"User added sucessfully\",\"data\":".str_replace("<p>","",json_encode($query->row_array())). "}";
// return $this->db->insert_id();
}else
{
$message="Something Wrong";
echo "{\"status\" : \"400\",\"data\":".str_replace("<p>","",json_encode($message)). "}";
// return false;
}
}
}
/* Login user $email, $password*/
function login()
{
$email=$this->input->post('email');
$password=$this->input->post('password');
$this->db->select('int_id,var_email,var_password');
$this->db->from('tbl_user');
$this->db->where('var_email', $email);
$this->db->where('chr_status', 'A');
$query = $this->db->get();
$user = $query->result();
if(!empty($user))
{
if(verifyHashedPassword($password, $user[0]->var_password))
{
$this->db->select('var_email as email,var_fullname as fullname,dt_createddate as createdate');
$query = $this->db->get_where('tbl_user', array('var_email' => $email));
echo "{\"status\" : \"200\",\"message\" : \"Login sucessfully\",\"data\":".str_replace("<p>","",json_encode($query->row_array())). "}";
}
else
{
echo "{\"status\" : \"404\",\"message\" : \"Password does not match\",\"data\":".str_replace("<p>","",'{}'). "}";
}
}
else
{
echo "{\"status\" : \"404\",\"message\" : \"Invalid email \",\"data\":".str_replace("<p>","",'{}'). "}";
}
}
/* Fetch user data all or single */
function userlist()
{
$email=$this->input->post('email'); // post id of which user data you will get
if(!empty($email))
{
$email=$this->input->post('email');
$password=$this->input->post('password');
$this->db->select('int_id,var_email,var_password');
$this->db->from('tbl_user');
$this->db->where('var_email', $email);
$this->db->where('chr_status', 'A');
$query = $this->db->get();
$user = $query->result();
if(!empty($user))
{
$this->db->select('var_email as email,var_fullname as fullname,dt_createddate as createdate');
$query = $this->db->get_where('tbl_user', array('var_email' => $email));
$responce_json=json_encode($query->row_array());
echo "{\"status\" : \"200\",\"message\" : \"User data\",\"data\":".str_replace("<p>","",$responce_json). "}";
}
else
{
echo "{\"status\" : \"404\",\"message\" : \"Invalid email \",\"data\":".str_replace("<p>","",'{}'). "}";
}
}
else
{
$this->db->select('var_email as email,var_fullname as fullname,dt_createddate as createdate');
$query = $this->db->get('tbl_user');
$responce_json=json_encode($query->result_array());
echo "{\"status\" : \"200\",\"message\" : \"User data\",\"data\":".str_replace("<p>","",$responce_json). "}";
}
}
/* Update user data */
function edit_user($data = array()) {
$id = $this->input->post('id');
$data['first_name'] = $this->input->post('first_name');
/* $data['last_name'] = $this->input->post('last_name');
$data['email'] = $this->input->post('email');
$data['phone'] = $this->input->post('phone'); */
if(!empty($data) && !empty($id)){
if(!array_key_exists('modified', $data)){
$data['modified'] = date("Y-m-d H:i:s");
}
$update = $this->db->update('users', $data, array('id'=>$id));
if($update){
$message="User Update Sucessfully";
$responce_json=json_encode($message);
echo "{\"status\" : \"200\",\"data\":".str_replace("<p>","",$responce_json). "}";
}
}
else
{
return false;
}
}
/* change password */
function change_password()
{
$email=$this->input->post('email');
$password=$this->input->post('password');
$newpassword=$this->input->post('newpassword');
//$conformnewpassword=$this->input->post('conformnewpassword');
$this->db->select('int_id,var_email,var_password');
$this->db->from('tbl_user');
$this->db->where('var_email', $email);
$this->db->where('chr_status', 'A');
$query = $this->db->get();
$user = $query->result();
if(!empty($user))
{
if(verifyHashedPassword($password, $user[0]->var_password))
{
//if($newpassword==$conformnewpassword)
//{
$data['var_password'] = getHashedPassword($newpassword);
$update = $this->db->update('tbl_user', $data, array('var_email'=>$email));
$this->db->select('var_email as email,var_fullname as fullname,dt_createddate as createdate');
$query = $this->db->get_where('tbl_user', array('var_email' => $email));
echo "{\"status\" : \"200\",\"message\" : \"Password change sucessfully\",\"data\":".str_replace("<p>","",json_encode($query->row_array())). "}";
/* }
else
{
echo "{\"status\" : \"404\",\"message\" : \"New pass and conform pass does not match \",\"data\":".str_replace("<p>","",'{}'). "}";
} */
}
else
{
echo "{\"status\" : \"404\",\"message\" : \"Invalid old password \",\"data\":".str_replace("<p>","",'{}'). "}";
}
}
else
{
echo "{\"status\" : \"404\",\"message\" : \"Invalid email \",\"data\":".str_replace("<p>","",'{}'). "}";
}
}
/*
* Delete user data
*/
/* public function delete($id){
$delete = $this->db->delete('users',array('id'=>$id));
return $delete?true:false;
} */
}
?>

Google Friend Connect fcauth cookie in php

this may be easy for most of you .. but not me.
I am using some "sample" Google code - as it fits my purpose so why change what works - but for the life of me I cannot access/find/get etc the FCAuth cookie after a user is logged in.
Help please - thanks in advance.
Here is my code (the Site ID is in a set variable, and all the calls work todate. just need to find/get the FCAuth cookie.
var viewer, ownerFriends, activities;
google.friendconnect.container.setParentUrl('/api/' /* location of rpc_relay.html and canvas.html */);
google.friendconnect.container.loadOpenSocialApi({
site: SITE_ID,
onload: function() { initAllData(); }});
function initAllData() {
var params = {};
params[opensocial.DataRequest.PeopleRequestFields.PROFILE_DETAILS] =
[opensocial.Person.Field.ID,opensocial.Person.Field.NAME,opensocial.Person.Field.THUMBNAIL_URL,opensocial.Person.Field.PROFILE_URL];
var req = opensocial.newDataRequest();
req.add(req.newFetchPersonRequest('VIEWER', params), 'viewer');
req.add(req.newFetchPeopleRequest(
new opensocial.IdSpec({'userId' : 'OWNER', 'groupId' : 'FRIENDS'}), params),
'ownerFriends');
req.add(req.newFetchActivitiesRequest(new opensocial.IdSpec({'userId' : 'OWNER', 'groupId' : 'FRIENDS'})), 'activities');
var idspec = new opensocial.IdSpec({ 'userId' : 'VIEWER','groupId' : 'FRIENDS' });
req.add(req.newFetchPeopleRequest(idspec), 'viewer_friends');
req.send(onData);
req.send(setupData);
};
function setupData(data) {
ownerFriends = data.get('ownerFriends').getData().asArray();
var html = "";
for (var i = 0; i < ownerFriends.length && i < 8; i++) {
var person = ownerFriends[i];
html += "<a title='" + person.getField("displayName") + "' href='" + person.getField("profileUrl") + "'>";
html += "<img class='memberPhoto' src='" + person.getField("thumbnailUrl") + "' width='50px' alt='" + person.getField("displayName") + "'/>";
html += "</a> ";
};
document.getElementById('members').innerHTML = html;
viewer = data.get('viewer').getData();
if (viewer) {
document.getElementById('memberstate').innerHTML =
'<h2>' + viewer.getField("displayName") + ' welcome to the Yoga Council of Canada </h2>' ;
} else {
document.getElementById('memberstate').innerHTML =
'<h2>Join with one click</h2> After joining, you will automatically appear as a recent member.';
}
viewer = data.get('viewer').getData();
if (viewer) {
document.getElementById('profile').innerHTML =
'<img align="left" src="' + viewer.getField("thumbnailUrl") + '" style="margin-right: 20px;" >' +
'<strong>' + viewer.getField("displayName") + '</strong><br>' +
'Settings<br>' +
'Invite a friend<br>' +
'Sign out<br>';
} else {
google.friendconnect.renderSignInButton({ 'id': 'profile' });
}
};
function onData(data) {
if (!data.get("viewer_friends").hadError()) {
var site_friends = data.get("viewer_friends").getData();
var list = document.getElementById("friends-list");
list.innerHTML = "";
site_friends.each(function(friend) {
list.innerHTML += "<li>" + friend.getDisplayName() + "</li>";
});
}
};
OK, I am/was being totally thick, the cookie is automatically set as
$_COOKIE['fcauth<your appID>'];
So you can "just call it" i.e.
<?php if($_COOKIE['fcauth<your appID>']): do something endif; ?>