magento custom payment gateway for National Bank Greece - php

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.

Related

Error: Cannot use object of type Symfony\Component\HttpFoundation\Request as array

When I showed it in a browser when upgrading to symfony3, I had a title error (line 25).
I had questions on similar mistakes in StackOverflow, but I think it's a different trend.
I want to know how it can be improved.
Stack Trace
[1] Symfony\Component\Debug\Exception\FatalErrorException: Error:
Cannot use object of type Symfony\Component\HttpFoundation\Request as array
at n/a
in /Symfony/.../Bundle/Listener/PortalListener.php line 25
Code
PortalListener.php
<?php
namespace Ahi\Sp\PublicBundle\Listener;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Ahi\Sp\PublicBundle\Controller\BaseController;
use Ahi\Sp\PublicBundle\Model\Service\AhiCookieService;
use Symfony\Component\HttpFoundation\Request;
/**
*/
class PortalListener
{
/*
*
* #param FilterControllerEvent $event
*/
public function preControllerExecute(FilterControllerEvent $event, Request $request)
{
if (HttpKernelInterface::MASTER_REQUEST === $event->getRequestType()) {
$_controller = $event->getRequest();
if (isset($_controller[0])) { //line25
$controller = $_controller[0];
if (method_exists($controller, 'preExecute')) {
$controller->preExecute($request);
}
}
}
}
BaseController.php
<?php
namespace Ahi\Sp\PublicBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\HttpException;
/ **
* Front controller.
* /
abstract class BaseController extends Controller
{
const MAX_ITEM_COUNT = 4; // Maximum number to get the item part number from the coordination. (You can get up to 4)
protected $parameters = array();
protected $response = null;
protected $cookie = null;
public function preExecute (Request $request) {
$this->cookie = $this->get('public.ahiCookieService');
// ---------------------------------------
// Gender (The order is the member's gender → portal top gender button → brand → shop → MEN'S $LADIE'S button)
$this->gender = $this->cookie->get('gender');
// Get the brand and overwrite the gender of the brand
$this->brand = null;
$brandDir = null;
$brandDirUrlParam = $request->attributes->get('brandDir');
$brandDirGetParam = $request->query->get('brandDir');
if ($brandDirUrlParam) {
$brandDir = $brandDirUrlParam;
} elseif ($brandDirGetParam) {
$brandDir = $brandDirGetParam;
}
$brandService = $this->get('public.brandService');
if ($brandDir) {
$brand = $brandService->getBrand($brandDir);
if (!$brand) {
throw $this->createBrandNotFoundException();
}
if(!$this->isPreview() && !$brand->getDispFlg()) {
throw $this->createBrandNotFoundException();
}
$brandSex = $brand->getBrandSex();
if ($brandSex != 2) {
$this->gender = $brandSex;
}
$this->brand = $brand;
}
// shop --------------------------------->
$this->shop = null;
$shopDir = null;
$shopDirUrlParam = $request->attributes->get('shopDir');
$shopDirGetParam = $request->query->get('shopDir');
if ($shopDirUrlParam) {
$shopDir = $shopDirUrlParam;
} elseif ($shopDirGetParam) {
$shopDir = $shopDirGetParam;
}
$this->shopDir = $shopDir;
$shopService = $this->get('public.shopService');
if ($shopDir) {
$shop = $shopService->getShop($shopDir);
if (!$shop) {
throw $this->createShopNotFoundException();
}
if (!$this->isPreview() && !$shop->getDispFlg()) {
if ($shop->getRedirectFlg() == true) {
$redirectUrl = $shop->getRedirectUrl();
if (empty($redirectUrl)) {
$redirectUrl = $this->generateUrl('ahi_sp_public_brand_top', array('brandDir' => $shop->getBrand()->getDirName()));
}
throw new ShopRedirectException($redirectUrl);
} else {
throw $this->createShopNotFoundException();
}
}
$shopSex = $shop->getShopSex();
if ($shopSex != 2) {
$this->gender = $shopSex;
}
$this->shop = $shop;
}
// shop <---------------------------------
$gender = $request->query->get('gender');
if ($gender !== null) {
$this->gender = $gender;
}
if ($this->getRequest()->get('_route') !== 'ahi_sp_public_portal_top') {
$gender = $request->query->get('gender');
if ($gender !== null) {
$this->gender = $gender;
}
}
if ($this->gender !== null) {
$this->gender = intval($this->gender);
$this->cookie->set('gender', $this->gender, 30);
$this->cookie->set('ec_gender', $this->gender, 30);
}
if ($this->gender === 0 or $this->gender === 1) {
$this->paramsSex = array('sex'=> array($this->gender, 2));
} else {
$this->paramsSex = array('sex'=> array(0, 1, 2));
}
$mid = $this->cookie->get('member_id');
$session = $request->getSession();
if ($mid && !$session->has('favoriteShops')) {
$route = $this->container->getParameter('ats_http');
$list = $this->container->getParameter('favorite_shop_list');
$url = $route . $list . $mid;
$ahiStoreIdList = file_get_contents($url);
$favoriteShops = array();
if ($ahiStoreIdList !=='') {
$ahiStoreIdArray = explode(",", $ahiStoreIdList);
$shopService = $this->get("public.shopService");
$sortKey = array();
foreach ($ahiStoreIdArray as $key => $storeId) {
$id = explode(':', $storeId);
$shop = $shopService->getShopById($id[1]);
if ($shop) {
$favoriteShops[$key]['shopName'] = $shop->getShopName();
$favoriteShops[$key]['shopDir'] = $shop->getDirName();
$sortKey[$key] = $shop->getShopName();
}
}
array_multisort($sortKey, SORT_ASC, $favoriteShops);
}
$session->set('favoriteShops', $favoriteShops);
}
$trend_tag_list_limit = $this->container->getParameter("trend_tag_list_limit");
if(!$brandDirUrlParam and !$shopDirUrlParam){
$this->parameters['brandPrefectures'] = $this->service('coordinate')->getPrefExistBrand();
$this->parameters['prefBrands'] = $this->service('coordinate')->getBrandPerPref();
$this->parameters['shopBrandPrefectures'] = $this->service('brand')->getPrefExistBrand();
$this->parameters['shopPrefBrands'] = $this->service('brand')->getBrandPerPref();
$this->parameters['trendTags'] = $this->service('ecTrendTag','common')->getTrendTag($this->paramsSex,false,$trend_tag_list_limit);
}elseif($brandDirUrlParam){
$this->parameters['brandPrefectures'] = $this->service('coordinate')->getPrefExistBrand($brandDirUrlParam);
$this->parameters['trendTags'] = $this->service('ecTrendTag','common')->getTrendTag($this->brand,false,$trend_tag_list_limit);
}else{
$this->parameters['coordinateCount'] = $this->service('coordinate')->getCountArticle(
$this->brand,
$this->shop
);
$this->parameters['trendTags'] = $this->service('ecTrendTag','common')->getTrendTag($this->shop->getBrand(),false,$trend_tag_list_limit);
}
}
Version
Cent OS 6.7
PHP 5.6
Symfony3.0.9
The error was resolved when I fixed it as follows.
public function preControllerExecute(FilterControllerEvent $event)
{
if (HttpKernelInterface::MASTER_REQUEST === $event->getRequestType()) {
$request = $event->getRequest();
$_controller = $event->getController();
if (isset($_controller[0])) {
$controller = $_controller[0];
if (method_exists($controller, 'preExecute')) {
$controller->preExecute($request);
}
}
}
}

paypal ipn notify_url working correctly but it shows nothing on my return url that is set

I am up and running my E-Commerce website on a server. I use Paypal IPN notifications to send customers with notifications about payments made by them.
I am currently using Paypal sandbox for testing.
I proceed to checkout => paypal developer account => make payment => i receive message in my paypal account as ipn request is sent but i don't get the values of ipn request in my orders table in the database.
What could be the reason for this ?
I have set my IPN details as in the screenshot below.
and
I also have the screenshot of IPN history of my Paypal developer account.
Can anyone please help me and tell me the reason why the values in my database are not updated ?
Following is my code:
classes/Paypal.php
<?php
class PayPal {
private $_environment = 'sandbox';
private $_url_production = 'https://www.paypal.com/cgi-bin/webscr';
private $_url_sandbox = 'https://www.sandbox.paypal.com/cgi-bin/webscr';
private $_url;
private $_cmd;
private $_products = array();
private $_fields = array();
private $_business = 'xxx-xxx#gmail.com';
private $_page_style = 'null';
private $_return;
private $_cancel_payment;
private $_notify_url;
private $_currency_code = 'GBP';
public $_tax_cart = 0;
public $_tax = 0;
public $_populate = array();
private $_ipn_data = array();
private $_log_file = null;
private $_ipn_result;
public function __construct($cmd = '_cart') {
$this->_url = $this->_environment == 'sandbox' ?
$this->_url_sandbox :
$this->_url_production;
$this->_cmd = $cmd;
$this->_return = SITE_URL."/?page=return";
$this->_cancel_payment = SITE_URL."/?page=cancel";
$this->_notify_url = SITE_URL."/?page=ipn";
$this->_log_file = ROOT_PATH.DS."log".DS."ipn.log";
}
public function addProduct($number, $name, $price = 0, $qty = 1) {
switch($this->_cmd) {
case '_cart':
$id = count($this->_products) + 1;
$this->_products[$id]['item_number_'.$id] = $number;
$this->_products[$id]['item_name_'.$id] = $name;
$this->_products[$id]['amount_'.$id] = $price;
$this->_products[$id]['quantity_'.$id] = $qty;
break;
case '_xclick':
if (empty($this->_products)) {
$this->_products[0]['item_number'] = $number;
$this->_products[0]['item_name'] = $name;
$this->_products[0]['amount'] = $price;
$this->_products[0]['quantity'] = $qty;
}
break;
}
}
private function addField($name = null, $value = null) {
if (!empty($name) && !empty($value)) {
$field = '<input type="hidden" name="'.$name.'" ';
$field .= 'value="'.$value.'" />';
$this->_fields[] = $field;
}
}
private function standardFields() {
$this->addField('cmd', $this->_cmd);
$this->addField('business', $this->_business);
if ($this->_page_style != null) {
$this->addField('page_style', $this->_page_style);
}
$this->addField('return', $this->_return);
$this->addField('notify_url', $this->_notify_url);
$this->addField('cancel_payment', $this->_cancel_payment);
$this->addField('currency_code', $this->_currency_code);
$this->addField('rm', 2);
switch($this->_cmd) {
case '_cart':
if ($this->_tax_cart != 0) {
$this->addField('tax_cart', $this->_tax_cart);
}
$this->addField('upload', 1);
break;
case '_xclick':
if ($this->_tax != 0) {
$this->addField('tax', $this->_tax);
}
break;
}
}
private function prePopulate() {
if (!empty($this->_populate)) {
foreach($this->_populate as $key => $value) {
$this->addField($key, $value);
}
}
}
private function processFields() {
$this->standardFields();
if (!empty($this->_products)) {
foreach($this->_products as $product) {
foreach($product as $key => $value) {
$this->addField($key, $value);
}
}
}
$this->prePopulate();
}
private function getFields() {
$this->processFields();
if (!empty($this->_fields)) {
return implode("", $this->_fields);
}
}
private function render() {
$out = '<form action="'.$this->_url.'" method="post" id="frm_paypal">';
$out .= $this->getFields();
$out .= '<input type="submit" value="Submit" />';
$out .= '</form>';
return $out;
}
public function run($transaction_id = null) {
if (!empty($transaction_id)) {
$this->addField('custom', $transaction_id);
}
return $this->render();
}
private function validateIpn() {
$hostname = gethostbyaddr($_SERVER['REMOTE_ADDR']);
if (!preg_match('/paypal\.com$/', $hostname)) {
return false;
}
$objForm = new Form();
$this->_ipn_data = $objForm->getPostArray();
if (
!empty($this->_ipn_data) &&
array_key_exists('receiver_email', $this->_ipn_data) &&
strtolower($this->_ipn_data['receiver_email']) !=
strtolower($this->_business)
) {
return false;
}
return true;
}
private function getReturnParams() {
$out = array('cmd=_notify-validate');
if (!empty($this->_ipn_data)) {
foreach($this->_ipn_data as $key => $value) {
$value = function_exists('get_magic_quotes_gpc') ?
urlencode(stripslashes($value)) :
urlencode($value);
$out[] = "{$key}={$value}";
}
}
return implode("&", $out);
}
private function sendCurl() {
$response = $this->getReturnParams();
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $response);
curl_setopt($ch, T_HEADER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type: application/x-www-form-urlencoded",
"Content-Length: " . strlen($response)
));
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$this->_ipn_result = curl_exec($ch);
curl_close($ch);
}
public function ipn() {
if ($this->validateIpn()) {
$this->sendCurl();
if (strcmp($this->_ipn_result, "VERIFIED") == 0) {
$objOrder = new Order();
if (!empty($this->_ipn_data)) {
$objOrder->approve(
$this->_ipn_data,
$this->_ipn_result
);
}
}
}
}
}
mod/paypal.php
<?php
require_once('../inc/autoload.php');
$token2 = Session::getSession('token2');
$objForm = new Form();
$token1 = $objForm->getPost('token');
if ($token2 == Login::string2hash($token1)) {
// create order
$objOrder = new Order();
if ($objOrder->createOrder()) {
// populate order details
$order = $objOrder->getOrder();
$items = $objOrder->getOrderItems();
if (!empty($order) && !empty($items)) {
$objBasket = new Basket();
$objCatalogue = new Catalogue();
$objPayPal = new PayPal();
foreach($items as $item) {
$product = $objCatalogue->getProduct($item['product']);
$objPayPal->addProduct(
$item['product'],
$product['name'],
$item['price'],
$item['qty']
);
}
$objPayPal->_tax_cart = $objBasket->_vat;
// populate client's details
$objUser = new User();
$user = $objUser->getUser($order['client']);
if (!empty($user)) {
$objCountry = new Country();
$country = $objCountry->getCountry($user['country']);
$objPayPal->_populate = array(
'address1' => $user['address_1'],
'address2' => $user['address_2'],
'city' => $user['town'],
'state' => $user['county'],
'zip' => $user['post_code'],
'country' => $country['code'],
'email' => $user['email'],
'first_name' => $user['first_name'],
'last_name' => $user['last_name']
);
// redirect client to PayPal
echo $objPayPal->run($order['id']);
}
}
}
}
IPN settings
IPN Details
Please help me with this .
IPN is not related to your return URL. If you're adding your code that you expect to run when IPNs are triggered to your return URL you will not get the expected result.
To get data to your return URL you would need to use PDT which is very similar to IPN but is intended to be sent to the return URL. IPN goes to your notify URL, which should not match your return URL.

Getting PHP warnings in SOAP response along with success response in PHP

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

Session data changed in php

This is my code
class WcfClient {
public $wcfClient = null;
public $user = null;
public function __construct(){
if(isset($_SESSION['APIClient']) && $_SESSION['APIClient'] != null){
$this->wcfClient = $_SESSION['APIClient'];
}
}
public function __destruct(){
}
// Authanticate
private function Authenticate(){
global $_sogh_soapUrl, $_isDebug, $_sogh_header;
$wcargs = array();
$consumerAuthTicket = null;
if($this->wcfClient == null){
$args = array(
'clubname'=>'Wellness Institute at Seven Oaks',
'consumerName'=>'api',
'consumerPassword'=>'api'
);
try{
$wcargs = array(
'soap_version'=>SOAP_1_2
);
if($_isDebug){
$wcargs = array(
'soap_version'=>SOAP_1_2,
'proxy_host'=>"192.168.0.1",
'proxy_port'=>8080
);
}
// Connect to the API with soapclient
$soapAPIClient = new SoapClient($_sogh_soapUrl, $wcargs);
$response = $soapAPIClient->AuthenticateClubConsumer($args);
if(isset($response->AuthenticateClubConsumerResult)){
if(isset($response->AuthenticateClubConsumerResult->IsException) && $response->AuthenticateClubConsumerResult->IsException == true){
// some error occur
$this->wcfClient = null;
$_SESSION['APIClient'] = $this->wcfClient;
} else{
// set consumer ticket
$consumerAuthTicket = $response->AuthenticateClubConsumerResult->Value->AuthTicket;
// $loginData = $responseCode->ReturnValueOfConsumerLoginData;
$headers = array();
$headers[] = new SoapHeader($_sogh_header, "ConsumerAuthTicket", $consumerAuthTicket);
$soapAPIClient->__setSoapHeaders($headers);
// add to session
$this->wcfClient = $soapAPIClient;
$_SESSION['APIClient'] = $this->wcfClient;
}
}
} catch(SoapFault $fault){
$this->error('Fault: ' . $fault->faultcode . ' - ' . $fault->faultstring);
} catch(Exception $e){
$this->error('Error: ' . $e->getMessage());
}
}
return $this->wcfClient;
}
I store the soap client object in $_SESSION['APIClient'], but second times when run some data has been changed in session, I am use this class in drupal 7, I want to save the time using session, because authenticating takes long time.
Please help
Thank in advance

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