I am currently writing a Prestashop Payment module which uses the Paypal Adaptive Payments SDK.
When I try to install my module, I get the following error:
[PrestaShop] Fatal error in module Configuration:
Cannot redeclare class Configuration
here is my code.
the paypal sdk is installed correctly and working.
config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<module>
<name>MyPayments</name>
<displayName><![CDATA[My module]]></displayName>
<version><![CDATA[1.0]]></version>
<description><![CDATA[Description of my module.]]></description>
<author></author>
<tab><![CDATA[payments_gateways]]></tab>
<confirmUninstall>Are you sure you want to uninstall? You will lose all your settings!</confirmUninstall>
<is_configurable>0</is_configurable>
<need_instance>0</need_instance>
<limited_countries></limited_countries>
</module>
mypayments.php
<?php
if (!defined('_PS_VERSION_'))
exit;
//include paypal adaptive payments sdk lib
require(_PS_MODULE_DIR_.'/mypayments/samples/PPBootStrap.php');
class MyPayments extends PaymentModule {
public function __construct() {
$this->name = 'mypayments';
$this->tab = 'payments_gateways';
$this->version = '0.1';
$this->need_instance = 0;
$this->ps_versions_compliancy = array('min' => '1.5', 'max' => '1.6');
$this->bootstrap = true;
parent::__construct();
#$this->page = basename(__FILE__, '.php');
$this->displayName = $this->l('Adaptive Payments');
$this->description = $this->l('Paypal Adaptive Payments');
$this->confirmUninstall = $this->l('Are you sure you want to uninstall?');
if (!Configuration::get('MYMODULE_NAME'))
$this->warning = $this->l('No name provided');
}
public function install() {
if (!parent::install()
OR !$this->registerHook('payment')
OR !Configuration::updateValue('MYMODULE_NAME', 'My Payments')
)
return false;
return true;
}
public function uninstall() {
if (!parent::uninstall() ||
!Configuration::deleteByName('MYMODULE_NAME')
)
return false;
return true;
}
//output the current payment method to the choice list of available methods on the checkout pages
function hookPayment($params){
if(!$this->active) return;
global $smarty;
//checks if all products in cart are valid
foreach ($params['cart']->getProducts() AS $product)
if (Validate::isUnsignedInt(ProductDownload::getIdFromIdProduct(intval($product['id_product']))))
return false;
//assign smarty paths
$smarty->assign(array(
'this_path' => $this->_path,
'this_path_ssl' => (Configuration::get('PS_SSL_ENABLED') ? 'https://' :'http://').htmlspecialchars($_SERVER['HTTP_HOST'], ENT_COMPAT, 'UTF-8').__PS_BASE_URI__.'modules/'.$this->name.'/'
));
//return the template file to render the payment option
return $this->display(__FILE__, 'payment.tpl');
}
public function paypalPayCall($Email1, $Email2, $totalAmount){
$Email3;
$Payment1 = $totalAmount/2;
$Payment2 = $totalAmount/4;
$Payment3 = $totalAmount/4;
$payRequest = new PayRequest();
$receiver = array();
$receiver[0] = new Receiver();
$receiver[0]->amount = $Payment1;
$receiver[0]->email = $Email1;
$receiver[0]->primary = "true";
$receiver[1] = new Receiver();
$receiver[1]->amount = $Payment2;
$receiver[1]->email = $Email2;
$receiver[2] = new Receiver();
$receiver[2]->amount = $Payment3;
$receiver[2]->email = $Email3;
$receiverList = new ReceiverList($receiver);
$payRequest->receiverList = $receiverList;
$requestEnvelope = new RequestEnvelope("en_US");
$payRequest->requestEnvelope = $requestEnvelope;
$payRequest->actionType = "PAY";
$payRequest->cancelUrl = "http://www.google.at/";
$payRequest->returnUrl = dirname(__FILE__)."validation.php";
$payRequest->currencyCode = "EUR";
//CONFIGURATION - now sandbox
$sdkConfig = array(
"mode" => "sandbox",
"acct1.UserName" => "xxx",
"acct1.Password" => "xxx",
"acct1.Signature" => "xxx",
"acct1.AppId" => "xxx"
);
/* the payment call */
$adaptivePaymentsService = new AdaptivePaymentsService($sdkConfig);
$payResponse = $adaptivePaymentsService->Pay($payRequest);
//read response
$response = json_decode($payResponse);
$payKey = $response->payKey;
//check if acknowledged
if (strtoupper($response->responseEnvelope->ack) == 'SUCCESS')
{
$payUrl = "https://www.sandbox.paypal.com/webscr?cmd=_ap-payment&paykey=" . $payKey;
return $payUrl;
}
else
{
return false;
}
}
}
?>
payment.php
<?php
include(dirname(__FILE__).'/../../config/config.inc.php');
include(dirname(__FILE__).'/../../header.php');
include(dirname(__FILE__).'/mypayments.php');
if (!$cookie->isLogged())
Tools::redirect('authentication.php?back=order.php');
$paypalImgUrl = dirname(__FILE__).'/img/default_logos/default_logo.gif';
//create new instance of my payment class
$myPayments = new MyPayments();
//get cart total
$total = floatval(number_format($cart->getOrderTotal(true, 3), 2, '.', ''));
$Email1;
$Email2;
//call method from my payment class
$payUrl = $myPayments->paypalPayCall($Email1, $Email2, $total);
if ($payUrl == false)
{
echo "<center>Error generating payment link</center>";
}
else
{
//show link to buy with paypal
echo '<center><img src="'.$paypalImgUrl.'" alt="Pay with Paypal"/></center>';
}
include_once(dirname(__FILE__).'/../../footer.php');
?>
validation.php
<?php
//PAYPALS RETURN URL REDIRECTS HERE TO VALIDATE AND PLACE THE ORDER
include(dirname(__FILE__).'/../../config/config.inc.php');
include(dirname(__FILE__).'/../../header.php');
include(dirname(__FILE__).'/mypayments.php');
$total = floatval(number_format($cart->getOrderTotal(true, 3), 2, '.', ''));
$myPayments->validateOrder(intval($cart->id), _PS_OS_PREPARATION_, $total, $myPayments->displayName);
$order = new Order(intval($myPayments->currentOrder));
echo "<center> Thank you! Your order is being processed </center>";
include(dirname(__FILE__).'/../../footer.php');
?>
payment.tpl
<p class="payment_module">
<a href="{$this_path}payment.php" title="{l s='Pay with Paypal' mod='mypayments'}">
<img src="{$this_path}paypal.png" alt="{l s='Pay with Paypal' mod='mypayments'}" />
{l s='Pay with Paypal' mod='mypayments'}
</a>
</p>
Any help is much appreciated!
...the Paypal SDK had its own Configuration class
very trivial mistake after all -.-
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.
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
I want so connect an external website with a moodle-system. I've already set up the webService and created a token to get access.
I've followed http://www.rumours.co.nz/manuals/using_moodle_web_services.htm set up but in contrast i wanted to realise the connection via REST as in https://github.com/moodlehq/sample-ws-clients/find/master
My approach is to have a moodle class which will handle the data exchange. In first place i just wanted to try to create some new hard coded Users via the webService but it fails with the Moodle-Response:
"invalidrecord Can not find data record in database table external_functions. "
Which seems to me as if i the call was successfully but moodle has a problem to find the "core_user_create_users" function. I've checked the local moodle Database and in the table external_functions is an entry for "core_user_create_users" so i'm kind of confused where moodle doesn't know what to do.
Thats my class:
require_once (DOCUMENT_ROOT.'/tcm/api/moodle/curl.php');
class Moodle {
private $token;
private $domainName; // 'local.moodle.dev';
private $serverUrl;
public function __construct($token, $domainName) {
$this->token = $token;
$this->domainName = $domainName;
$this->serverUrl = $this->domainName . '/webservice/rest/server.php' . '?wstoken=' . $this->token;
echo "initialize Service: $this->serverUrl </br>";
}
public function createUser() {
$functionName = 'core_user_create_users';
/// PARAMETERS - NEED TO BE CHANGED IF YOU CALL A DIFFERENT FUNCTION
$user1 = new stdClass();
$user1->username = 'testusername1';
$user1->password = 'testpassword1';
$user1->firstname = 'testfirstname1';
$user1->lastname = 'testlastname1';
$user1->email = 'testemail1#moodle.com';
$user1->auth = 'manual';
$user1->idnumber = 'testidnumber1';
$user1->lang = 'en';
$user1->theme = 'standard';
$user1->timezone = '-12.5';
$user1->mailformat = 0;
$user1->description = 'Hello World!';
$user1->city = 'testcity1';
$user1->country = 'au';
$preferencename1 = 'preference1';
$preferencename2 = 'preference2';
$user1->preferences = array(
array('type' => $preferencename1, 'value' => 'preferencevalue1'),
array('type' => $preferencename2, 'value' => 'preferencevalue2'));
$user2 = new stdClass();
$user2->username = 'testusername2';
$user2->password = 'testpassword2';
$user2->firstname = 'testfirstname2';
$user2->lastname = 'testlastname2';
$user2->email = 'testemail2#moodle.com';
$user2->timezone = 'Pacific/Port_Moresby';
$users = array($user1, $user2);
$params = array('users' => $users);
/// REST CALL
$serverurl = $this->serverUrl . '&wsfunction=' . $functionName;
require_once (DOCUMENT_ROOT.'/tcm/api/moodle/curl.php');
$curl = new curl;
//if rest format == 'xml', then we do not add the param for backward compatibility with Moodle < 2.2
$restformat = "json";
$resp = $curl->post($serverurl . $restformat, $params);
//print_r($resp);
echo '</br>*************Server Response*************</br>';
var_dump($resp);
}
}
I'm using the curl class from the same github-project which i posted above - moodle is linkng to it in their Documentation..
docs.moodle.org/dev/Creating_a_web_service_client
The entry point of my call is hardcoded right now:
<?php
include_once (DOCUMENT_ROOT.'/tcm/api/moodle/moodle.php');
//entry point of code
if (isset($_POST)){
//token and domain would be in $_POST
$bla = new Moodle('0b5a1e98061c5f7fb70fc3b42af6bfc4', 'local.moodle.dev');
$bla->createUser();
}
Does anyone know how to solve the "invalidrecord Can not find data record in database table external_functions" error or has a different approach/suggestion how i can create my users remotely??
Thanks in advance
I got it finally working with the following code:
class Moodle {
private $token; //'0b5a1e98061c5f7fb70fc3b42af6bfc4';
private $domainName; // 'http://local.moodle.dev';
private $serverUrl;
public $error;
public function __construct($token, $domainName) {
$this->token = $token;
$this->domainName = $domainName;
$this->serverUrl = $this->domainName . '/webservice/rest/server.php' . '?wstoken=' . $this->token;
echo "initialize Service: $this->serverUrl </br>";
}
public function createUser() {
$functionName = 'core_user_create_users';
$user1 = new stdClass();
$user1->username = 'testusername1';
$user1->password = 'Uk3#0d5w';
$user1->firstname = 'testfirstname1';
$user1->lastname = 'testlastname1';
$user1->email = 'testemail1#moodle.com';
$user1->auth = 'manual';
$user1->idnumber = '';
$user1->lang = 'en';
$user1->timezone = 'Australia/Sydney';
$user1->mailformat = 0;
$user1->description = '';
$user1->city = '';
$user1->country = 'AU'; //list of abrevations is in yourmoodle/lang/en/countries
$preferencename1 = 'auth_forcepasswordchange';
$user1->preferences = array(
array('type' => $preferencename1, 'value' => 'true')
);
$users = array($user1);
$params = array('users' => $users);
/// REST CALL
$restformat = "json";
$serverurl = $this->serverUrl . '&wsfunction=' . $functionName. '&moodlewsrestformat=' . $restformat;
require_once (DOCUMENT_ROOT . '/tcm/api/moodle/curl.php');
$curl = new curl();
$resp = $curl->post($serverurl, $params);
echo '</br>************************** Server Response createUser()**************************</br></br>';
echo $serverurl . '</br></br>';
var_dump($resp);
}
}
Info:
For all moodle beginners.. Activating the moodle Debug messages helps a bit. You'll receive an additional error information in the response returned form the server.
Moodle -> Site Administration -> Development -> Debugging -> Debug Messages
Select: DEVELOPER:extra Moodle debug messages for developers
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have created a registration form and it works my only issues is I want to be able to hide the post info in the url if you click submit and the validation fails it does this
register.php?action=signup
is there a mod rewrite for this?
so that the url remains
register.php
removing the ?action=signup
I have searched every where but have came up with nothing
php code for register page
<?php
//Error reporting #1-8F636958
error_reporting(E_ALL | E_STRICT);
//End Error reporting
//Include Common Files #1-EDC1CE42
define("RelativePath", ".");
define("PathToCurrentPage", "/");
define("FileName", "NewPage1.php");
include_once(RelativePath . "/Common.php");
include_once(RelativePath . "/Template.php");
include_once(RelativePath . "/Sorter.php");
include_once(RelativePath . "/Navigator.php");
//End Include Common Files
class clsRecordusers { //users Class #2-9BE1AF6F
//Variables #2-9E315808
// Public variables
public $ComponentType = "Record";
public $ComponentName;
public $Parent;
public $HTMLFormAction;
public $PressedButton;
public $Errors;
public $ErrorBlock;
public $FormSubmitted;
public $FormEnctype;
public $Visible;
public $IsEmpty;
public $CCSEvents = "";
public $CCSEventResult;
public $RelativePath = "";
public $InsertAllowed = false;
public $UpdateAllowed = false;
public $DeleteAllowed = false;
public $ReadAllowed = false;
public $EditMode = false;
public $ds;
public $DataSource;
public $ValidatingControls;
public $Controls;
public $Attributes;
// Class variables
//End Variables
//Class_Initialize Event #2-627C035C
function clsRecordusers($RelativePath, & $Parent)
{
global $FileName;
global $CCSLocales;
global $DefaultDateFormat;
$this->Visible = true;
$this->Parent = & $Parent;
$this->RelativePath = $RelativePath;
$this->Errors = new clsErrors();
$this->ErrorBlock = "Record users/Error";
$this->DataSource = new clsusersDataSource($this);
$this->ds = & $this->DataSource;
$this->InsertAllowed = true;
if($this->Visible)
{
$this->ComponentName = "users";
$this->Attributes = new clsAttributes($this->ComponentName . ":");
$CCSForm = explode(":", CCGetFromGet("ccsForm", ""), 2);
if(sizeof($CCSForm) == 1)
$CCSForm[1] = "";
list($FormName, $FormMethod) = $CCSForm;
$this->EditMode = ($FormMethod == "Edit");
$this->FormEnctype = "application/x-www-form-urlencoded";
$this->FormSubmitted = ($FormName == $this->ComponentName);
$Method = $this->FormSubmitted ? ccsPost : ccsGet;
$this->btn_register = new clsButton("btn_register", $Method, $this);
$this->username = new clsControl(ccsTextBox, "username", "Soldier", ccsText, "", CCGetRequestParam("username", $Method, NULL), $this);
$this->username->Required = true;
$this->user_email = new clsControl(ccsTextBox, "user_email", "User Email", ccsText, "", CCGetRequestParam("user_email", $Method, NULL), $this);
$this->user_email->Required = true;
$this->user_birthdate = new clsControl(ccsTextBox, "user_birthdate", "User Birthdate", ccsText, "", CCGetRequestParam("user_birthdate", $Method, NULL), $this);
$this->user_birthdate->Required = true;
}
}
//End Class_Initialize Event
//Initialize Method #2-052CBF13
function Initialize()
{
if(!$this->Visible)
return;
$this->DataSource->Parameters["urluid"] = CCGetFromGet("uid", NULL);
}
//End Initialize Method
//Validate Method #2-B7C6592D
function Validate()
{
global $CCSLocales;
$Validation = true;
$Where = "";
$Validation = ($this->username->Validate() && $Validation);
$Validation = ($this->user_email->Validate() && $Validation);
$Validation = ($this->user_birthdate->Validate() && $Validation);
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "OnValidate", $this);
$Validation = $Validation && ($this->username->Errors->Count() == 0);
$Validation = $Validation && ($this->user_email->Errors->Count() == 0);
$Validation = $Validation && ($this->user_birthdate->Errors->Count() == 0);
return (($this->Errors->Count() == 0) && $Validation);
}
//End Validate Method
//CheckErrors Method #2-E8847328
function CheckErrors()
{
$errors = false;
$errors = ($errors || $this->username->Errors->Count());
$errors = ($errors || $this->user_email->Errors->Count());
$errors = ($errors || $this->user_birthdate->Errors->Count());
$errors = ($errors || $this->Errors->Count());
$errors = ($errors || $this->DataSource->Errors->Count());
return $errors;
}
//End CheckErrors Method
//Operation Method #2-6BA9892D
function Operation()
{
if(!$this->Visible)
return;
global $Redirect;
global $FileName;
$this->DataSource->Prepare();
if(!$this->FormSubmitted) {
$this->EditMode = $this->DataSource->AllParametersSet;
return;
}
if($this->FormSubmitted) {
$this->PressedButton = "btn_register";
if($this->btn_register->Pressed) {
$this->PressedButton = "btn_register";
}
}
$Redirect = $FileName . "?" . CCGetQueryString("QueryString", array("ccsForm"));
if($this->Validate()) {
if($this->PressedButton == "btn_register") {
if(!CCGetEvent($this->btn_register->CCSEvents, "OnClick", $this->btn_register) || !$this->InsertRow()) {
$Redirect = "";
}
}
} else {
$Redirect = "";
}
if ($Redirect)
$this->DataSource->close();
}
//End Operation Method
//InsertRow Method #2-C62BC29D
function InsertRow()
{
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "BeforeInsert", $this);
if(!$this->InsertAllowed) return false;
$this->DataSource->username->SetValue($this->username->GetValue(true));
$this->DataSource->user_email->SetValue($this->user_email->GetValue(true));
$this->DataSource->user_birthdate->SetValue($this->user_birthdate->GetValue(true));
$this->DataSource->Insert();
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "AfterInsert", $this);
return (!$this->CheckErrors());
}
//End InsertRow Method
//Show Method #2-AE9867B3
function Show()
{
global $CCSUseAmp;
$Tpl = CCGetTemplate($this);
global $FileName;
global $CCSLocales;
$Error = "";
if(!$this->Visible)
return;
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "BeforeSelect", $this);
$RecordBlock = "Record " . $this->ComponentName;
$ParentPath = $Tpl->block_path;
$Tpl->block_path = $ParentPath . "/" . $RecordBlock;
$this->EditMode = $this->EditMode && $this->ReadAllowed;
if($this->EditMode) {
if($this->DataSource->Errors->Count()){
$this->Errors->AddErrors($this->DataSource->Errors);
$this->DataSource->Errors->clear();
}
$this->DataSource->Open();
if($this->DataSource->Errors->Count() == 0 && $this->DataSource->next_record()) {
$this->DataSource->SetValues();
if(!$this->FormSubmitted){
$this->username->SetValue($this->DataSource->username->GetValue());
$this->user_email->SetValue($this->DataSource->user_email->GetValue());
$this->user_birthdate->SetValue($this->DataSource->user_birthdate->GetValue());
}
} else {
$this->EditMode = false;
}
}
if($this->FormSubmitted || $this->CheckErrors()) {
$Error = "";
$Error = ComposeStrings($Error, $this->username->Errors->ToString());
$Error = ComposeStrings($Error, $this->user_email->Errors->ToString());
$Error = ComposeStrings($Error, $this->user_birthdate->Errors->ToString());
$Error = ComposeStrings($Error, $this->Errors->ToString());
$Error = ComposeStrings($Error, $this->DataSource->Errors->ToString());
$Tpl->SetVar("Error", $Error);
$Tpl->Parse("Error", false);
}
$CCSForm = $this->EditMode ? $this->ComponentName . ":" . "Edit" : $this->ComponentName;
$this->HTMLFormAction = $FileName . "?" . CCAddParam(CCGetQueryString("QueryString", ""), "ccsForm", $CCSForm);
$Tpl->SetVar("Action", !$CCSUseAmp ? $this->HTMLFormAction : str_replace("&", "&", $this->HTMLFormAction));
$Tpl->SetVar("HTMLFormName", $this->ComponentName);
$Tpl->SetVar("HTMLFormEnctype", $this->FormEnctype);
$this->btn_register->Visible = !$this->EditMode && $this->InsertAllowed;
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "BeforeShow", $this);
$this->Attributes->Show();
if(!$this->Visible) {
$Tpl->block_path = $ParentPath;
return;
}
$this->btn_register->Show();
$this->username->Show();
$this->user_email->Show();
$this->user_birthdate->Show();
$Tpl->parse();
$Tpl->block_path = $ParentPath;
$this->DataSource->close();
}
//End Show Method
} //End users Class #2-FCB6E20C
class clsusersDataSource extends clsDBlocalhost { //usersDataSource Class #2-5EDEDCFF
//DataSource Variables #2-8A9D7D42
public $Parent = "";
public $CCSEvents = "";
public $CCSEventResult;
public $ErrorBlock;
public $CmdExecution;
public $InsertParameters;
public $wp;
public $AllParametersSet;
public $InsertFields = array();
// Datasource fields
public $username;
public $user_email;
public $user_birthdate;
//End DataSource Variables
//DataSourceClass_Initialize Event #2-56B8B1F7
function clsusersDataSource(& $Parent)
{
$this->Parent = & $Parent;
$this->ErrorBlock = "Record users/Error";
$this->Initialize();
$this->username = new clsField("username", ccsText, "");
$this->user_email = new clsField("user_email", ccsText, "");
$this->user_birthdate = new clsField("user_birthdate", ccsText, "");
$this->InsertFields["soldier"] = array("Name" => "soldier", "Value" => "", "DataType" => ccsText, "OmitIfEmpty" => 1);
$this->InsertFields["user_email"] = array("Name" => "user_email", "Value" => "", "DataType" => ccsText, "OmitIfEmpty" => 1);
$this->InsertFields["user_birthdate"] = array("Name" => "user_birthdate", "Value" => "", "DataType" => ccsText, "OmitIfEmpty" => 1);
}
//End DataSourceClass_Initialize Event
//Prepare Method #2-DC2F5FB8
function Prepare()
{
global $CCSLocales;
global $DefaultDateFormat;
$this->wp = new clsSQLParameters($this->ErrorBlock);
$this->wp->AddParameter("1", "urluid", ccsInteger, "", "", $this->Parameters["urluid"], "", false);
$this->AllParametersSet = $this->wp->AllParamsSet();
$this->wp->Criterion[1] = $this->wp->Operation(opEqual, "uid", $this->wp->GetDBValue("1"), $this->ToSQL($this->wp->GetDBValue("1"), ccsInteger),false);
$this->Where =
$this->wp->Criterion[1];
}
//End Prepare Method
//Open Method #2-B071412E
function Open()
{
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "BeforeBuildSelect", $this->Parent);
$this->SQL = "SELECT * \n\n" .
"FROM users {SQL_Where} {SQL_OrderBy}";
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "BeforeExecuteSelect", $this->Parent);
$this->query(CCBuildSQL($this->SQL, $this->Where, $this->Order));
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "AfterExecuteSelect", $this->Parent);
}
//End Open Method
//SetValues Method #2-1C83BB75
function SetValues()
{
$this->username->SetDBValue($this->f("soldier"));
$this->user_email->SetDBValue($this->f("user_email"));
$this->user_birthdate->SetDBValue($this->f("user_birthdate"));
}
//End SetValues Method
//Insert Method #2-D2F97CD9
function Insert()
{
global $CCSLocales;
global $DefaultDateFormat;
$this->CmdExecution = true;
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "BeforeBuildInsert", $this->Parent);
$this->InsertFields["soldier"]["Value"] = $this->username->GetDBValue(true);
$this->InsertFields["user_email"]["Value"] = $this->user_email->GetDBValue(true);
$this->InsertFields["user_birthdate"]["Value"] = $this->user_birthdate->GetDBValue(true);
$this->SQL = CCBuildInsert("users", $this->InsertFields, $this);
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "BeforeExecuteInsert", $this->Parent);
if($this->Errors->Count() == 0 && $this->CmdExecution) {
$this->query($this->SQL);
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "AfterExecuteInsert", $this->Parent);
}
}
//End Insert Method
} //End usersDataSource Class #2-FCB6E20C
//Initialize Page #1-2A4101A9
// Variables
$FileName = "";
$Redirect = "";
$Tpl = "";
$TemplateFileName = "";
$BlockToParse = "";
$ComponentName = "";
$Attributes = "";
// Events;
$CCSEvents = "";
$CCSEventResult = "";
$TemplateSource = "";
$FileName = FileName;
$Redirect = "";
$TemplateFileName = "NewPage1.html";
$BlockToParse = "main";
$TemplateEncoding = "UTF-8";
$ContentType = "text/html";
$PathToRoot = "./";
$PathToRootOpt = "";
$Scripts = "|";
$Charset = $Charset ? $Charset : "utf-8";
//End Initialize Page
//Before Initialize #1-E870CEBC
$CCSEventResult = CCGetEvent($CCSEvents, "BeforeInitialize", $MainPage);
//End Before Initialize
//Initialize Objects #1-1F103AC9
$DBlocalhost = new clsDBlocalhost();
$MainPage->Connections["localhost"] = & $DBlocalhost;
$Attributes = new clsAttributes("page:");
$Attributes->SetValue("pathToRoot", $PathToRoot);
$MainPage->Attributes = & $Attributes;
// Controls
$users = new clsRecordusers("", $MainPage);
$MainPage->users = & $users;
$users->Initialize();
$ScriptIncludes = "";
$SList = explode("|", $Scripts);
foreach ($SList as $Script) {
if ($Script != "") $ScriptIncludes = $ScriptIncludes . "<script src=\"" . $PathToRoot . $Script . "\" type=\"text/javascript\"></script>\n";
}
$Attributes->SetValue("scriptIncludes", $ScriptIncludes);
$CCSEventResult = CCGetEvent($CCSEvents, "AfterInitialize", $MainPage);
if ($Charset) {
header("Content-Type: " . $ContentType . "; charset=" . $Charset);
} else {
header("Content-Type: " . $ContentType);
}
//End Initialize Objects
//Initialize HTML Template #1-28F2FDD6
$CCSEventResult = CCGetEvent($CCSEvents, "OnInitializeView", $MainPage);
$Tpl = new clsTemplate($FileEncoding, $TemplateEncoding);
if (strlen($TemplateSource)) {
$Tpl->LoadTemplateFromStr($TemplateSource, $BlockToParse, "UTF-8");
} else {
$Tpl->LoadTemplate(PathToCurrentPage . $TemplateFileName, $BlockToParse, "UTF-8");
}
$Tpl->SetVar("CCS_PathToRoot", $PathToRoot);
$Tpl->block_path = "/$BlockToParse";
$CCSEventResult = CCGetEvent($CCSEvents, "BeforeShow", $MainPage);
$Attributes->SetValue("pathToRoot", "");
$Attributes->Show();
//End Initialize HTML Template
//Execute Components #1-0C9864E9
$users->Operation();
//End Execute Components
//Go to destination page #1-810C207B
if($Redirect)
{
$CCSEventResult = CCGetEvent($CCSEvents, "BeforeUnload", $MainPage);
$DBlocalhost->close();
header("Location: " . $Redirect);
unset($users);
unset($Tpl);
exit;
}
//End Go to destination page
//Show Page #1-E3A8594F
$users->Show();
$Tpl->block_path = "";
$Tpl->Parse($BlockToParse, false);
if (!isset($main_block)) $main_block = $Tpl->GetVar($BlockToParse);
$main_block = CCConvertEncoding($main_block, $FileEncoding, $TemplateEncoding);
$CCSEventResult = CCGetEvent($CCSEvents, "BeforeOutput", $MainPage);
if ($CCSEventResult) echo $main_block;
//End Show Page
//Unload Page #1-4215F8E1
$CCSEventResult = CCGetEvent ($CCSEvents, "BeforeUnload", $MainPage);
$DBlocalhost->close();
unset($users);
unset($Tpl);
//End Unload Page
?>
You can submit the information via POST. The way you are submitting the data across is from a GET HTTP request. The best thing to do is submit it over via post data. I am assuming your frontend call is using ajax for the form submission? if not and using a simple form change method to POST. If it is using ajax, I would need to know if you are using something like jquery or crafting the XHR request yourself, but if you are doing it that way I would assume you would know the difference.
<form action="action_page.php" method="POST">
I get a 520009 error (Account xx#xx.com is restricted) when trying to make a parallel payment. My code worked fine using the sandbox but I switched to the live endpoint and it began failing. The account in question is a valid paypal account and I am using "feespayer=SENDER". Am I missing something? Shouldn't the pay call go through even if the payee is a basic account? Why would this occur?
Here is my code for reference
function deposit($config) {
try {
if (isset($config['return_url']))
$this->return_url = $config['return_url'];
else
return 'Return URL should be set';
if (isset($config['return_url']))
$this->cancel_url = $config['cancel_url'];
else
return 'Cancel URL should be set';
if (isset($config['email']))
$this->sender_email = $config['email'];
else
return 'Email should be defined';
if (isset($config['amount']))
$this->amount = $config['amount'];
else
return 'Amount should be defined';
$returnURL = $this->return_url;
$cancelURL = $this->cancel_url;
$currencyCode = 'USD';
$memo = 'Deposit to ' . $this->ci->config->item('site_name');
$feesPayer = 'SENDER';
$payRequest = new PayRequest();
$payRequest->actionType = "PAY";
$payRequest->cancelUrl = $cancelURL;
$payRequest->returnUrl = $returnURL;
$payRequest->clientDetails = new ClientDetailsType();
$payRequest->clientDetails->applicationId = $this->ci->config->item('application_id');
$payRequest->clientDetails->deviceId = $this->ci->config->item('device_id');
$payRequest->clientDetails->ipAddress = $this->ci->input->ip_address();
$payRequest->currencyCode = $currencyCode;
//$payRequest->senderEmail = $this->sender_email;
$payRequest->requestEnvelope = new RequestEnvelope();
$payRequest->requestEnvelope->errorLanguage = "en_US";
$receivers = array();
$receiver = new receiver();
$receiver->email = $this->ci->config->item('moneyfan_account');
$receiver->amount = $this->amount;
$receiver->primary = 'false';
$receivers[] = $receiver;
$payRequest->receiverList = $receivers;
$payRequest->feesPayer = $feesPayer;
$payRequest->memo = $memo;
$ap = new AdaptivePayments();
$response = $ap->Pay($payRequest);
if (strtoupper($ap->isSuccess) == 'FAILURE') {
$this->ci->session->set_userdata('FAULTMSG', $ap->getLastError());
return json_encode(array('status' => 'false', 'msg' => $ap->getLastError()->error->errorId .' : '. $ap->getLastError()->error->message));
//redirect(site_url('home/api_error'));
} else {
$this->ci->session->set_userdata('payKey', $response->payKey);
if ($response->paymentExecStatus == "COMPLETED") {
redirect($returnURL);
} else {
$token = $response->payKey;
$payPalURL = PAYPAL_REDIRECT_URL . '_ap-payment&paykey=' . $token;
return json_encode(array('status' => 'true', 'msg' => $payPalURL));
//header("Location: " . $payPalURL);
}
}
} catch (Exception $ex) {
$fault = new FaultMessage();
$errorData = new ErrorData();
$errorData->errorId = $ex->getFile();
$errorData->message = $ex->getMessage();
$fault->error = $errorData;
$this->ci->session->set_userdata('FAULTMSG', $fault);
redirect(site_url('home/api_error'));
}
}
No! You cannot do that with a basic account.
For API to work you need to have a VERIFIED Business Account.
In their API it says:
NOTE:
The application owner must have a PayPal Business account.
There are two sources of reference for the PayPal API:
cms.paypal.com pages like the one referenced by Mihai Iorga, and
www.x.com pages like this one:
https://www.x.com/developers/paypal/documentation-tools/going-live-with-your-application
On x.com, it says you must have a verified business account, even though it is unclear from cms.paypal.com that this is the case.