I'm trying to connect to a SOAP web service but I'm getting an error.
This is the error I'm getting:
Fatal error: Uncaught SoapFault exception: [Client] SoapClient::SoapClient(): Invalid parameters in /public_html/wp-content/themes/startuply-child/functions.php:901
Here is the code:
if(isset($_POST['input_1']))
{
require_once('lib/nusoap.php');
$proxyhost = '';
$proxyport = '';
$proxyusername = '';
$proxypassword = '';
$client = new soapclient('http://abr.business.gov.au/abrxmlsearch/ABRXMLSearch.asmx?WSDL', 'true', $proxyhost, $proxyport, $proxyusername, $proxypassword);
$err = $client->getError();
if ($err)
{
echo '<h2>Constructor error</h2><pre>' . $err . '</pre>';
}
// Doc/lit parameters get wrapped
$param = array('searchString' => '',
'includeHistoricalDetails' => 'N',
'authenticationGuid' => '');
$result = $client->call('ABRSearchByABN', array('parameters' => $param), '', '', false, true);
// Check for a fault
if ($client->fault)
{
echo '<h2>Fault</h2><pre>';
print_r($result);
echo '</pre>';
} else
{
// Check for errors
$err = $client->getError();
if ($err)
{
// Display the error
echo '<h2>Error</h2><pre>' . $err . '</pre>';
} else
{
$OutputGUID = $result['ABRPayloadSearchResults']['request']['identifierSearchRequest']['authenticationGUID'];
$OutputABN = $result['ABRPayloadSearchResults']['response']['businessEntity']['ABN']['identifierValue'];
$OutputABNStatus = $result['ABRPayloadSearchResults']['response']['businessEntity']['entityStatus']['entityStatusCode'];
$OutputASICNumber = $result['ABRPayloadSearchResults']['response']['businessEntity']['ASICNumber'];
$OutputEntityName = $result['ABRPayloadSearchResults']['response']['businessEntity']['mainName']['organisationName'];
$OutputTradingName = $result['ABRPayloadSearchResults']['response']['businessEntity']['mainTradingName']['organisationName'];
$OutputLegalName = $result['ABRPayloadSearchResults']['response']['businessEntity']['legalName']['givenName'] . " " .
$result['ABRPayloadSearchResults']['response']['businessEntity']['legalName']['otherGivenName'] . " " .
$result['ABRPayloadSearchResults']['response']['businessEntity']['legalName']['familyName'];
$OutputOrganisationType = $result['ABRPayloadSearchResults']['response']['businessEntity']['entityType']['entityDescription'];
$OutputState = $result['ABRPayloadSearchResults']['response']['businessEntity']['mainBusinessPhysicalAddress']['stateCode'];
$OutputPostcode = $result['ABRPayloadSearchResults']['response'] ['businessEntity']['mainBusinessPhysicalAddress']['postcode'];
echo $OutputEntityName;
}
}
}
I'm trying to make a form which sends an ABN to the ABN lookup tool and then returns certain fields but I can't seem to connect to it. I think it is something to do with the Proxy log in details. I don't know if i am meant to set these as something. I have SOAP installed on the server but I am using nuSOAP.
Any help would be greatly appreciated.
Cheers,
Jordan
You are using nuSOAP, update here -
From:
$client = new soapclient('http://abr.business.gov.au/abrxmlsearch/ABRXMLSearch.asmx?WSDL',
'true', $proxyhost, $proxyport, $proxyusername, $proxypassword);
To:
$client = new nusoap_client('http://abr.business.gov.au/abrxmlsearch/ABRXMLSearch.asmx?WSDL',
'true', $proxyhost, $proxyport, $proxyusername, $proxypassword);
Related
I have this way of handling exceptions for some time now, but lately has been bothering me.
protected function sendPostmarkBatch($envios_preparados)
{
try {
$client = new PostmarkClient($this->postmarkToken());
$sendResult = $client->sendEmailBatchWithTemplate($envios_preparados);
} catch (PostmarkException $e) {
log_message('error', 'HTTP: ' . $e->httpStatusCode . ' MESSAGE: ' . $e->message . ' ERROR CODE: ' . $e->postmarkApiErrorCode);
$sendResult = new stdClass();
$sendResult->ErrorCode = $e->postmarkApiErrorCode;
} catch (Exception $generalException) {
log_message('error', 'GENERAL EXCEPTION: ' . $generalException);
$sendResult = new stdClass();
$sendResult->ErrorCode = '1';
}
return $sendResult;
}
Is it really necessary to create the object or variable $sendResult at 'catch' to return it or it's already created even if 'try' fails? Is there a better way of doing it?
Thanks!
It's necessary.
I'm not sure if it's suits your logic, but you can do something like this:
protected function sendPostmarkBatch($envios_preparados)
{
$sendResult = new stdClass();
try {
$client = new PostmarkClient($this->postmarkToken());
$sendResult = $client->sendEmailBatchWithTemplate($envios_preparados);
} catch (PostmarkException $e) {
log_message('error', 'HTTP: ' . $e->httpStatusCode . ' MESSAGE: ' . $e->message . ' ERROR CODE: ' . $e->postmarkApiErrorCode);
$sendResult->ErrorCode = $e->postmarkApiErrorCode;
} catch (Exception $generalException) {
log_message('error', 'GENERAL EXCEPTION: ' . $generalException);
$sendResult->ErrorCode = '1';
}
return $sendResult;
}
If $client->sendEmailBatchWithTemplate($envios_preparados) fails, your $sendResult variable won't be overwrited.
This is more like a debugging problem than an actual question. I have a login script in PHP which should check for user information from a local database and if present, then display them. Or else, redirect them to the Google OAuth2 Login process. The following php files concern the login flow :
google_login.php
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
require('http.php');
require('oauth_client.php');
require('../config.php');
require('StructuredQuery.php');
define("SCOPE", 'https://www.googleapis.com/auth/userinfo.email '.
'https://www.googleapis.com/auth/userinfo.profile' );
$client = new oauth_client_class;
$sq= new StructuredQuery();
// set the offline access only if you need to call an API
// when the user is not present and the token may expire
$client->offline = FALSE;
$client->debug = false;
$client->debug_http = true;
$client->redirect_uri = GOOGLE_REDIRECT_URL;
$client->client_id = GOOGLE_CLIENT_ID;
$application_line = __LINE__;
$client->client_secret = GOOGLE_CLIENT_SECRET;
if (strlen($client->client_id) == 0 || strlen($client->client_secret) == 0)
die('Please go to Google APIs console page ' .
'http://code.google.com/apis/console in the API access tab, ' .
'create a new client ID, and in the line ' . $application_line .
' set the client_id to Client ID and client_secret with Client Secret. ' .
'The callback URL must be ' . $client->redirect_uri . ' but make sure ' .
'the domain is valid and can be resolved by a public DNS.');
/* API permissions
*/
$client->scope = SCOPE;
if (($success = $client->Initialize())) {
if (($success = $client->Process())) {
if (strlen($client->authorization_error)) {
$client->error = $client->authorization_error;
$success = false;
} elseif (strlen($client->access_token)) {
$success = $client->CallAPI(
'https://www.googleapis.com/oauth2/v1/userinfo', 'GET', array(), array('FailOnAccessError' => true), $user);
}
}
$success = $client->Finalize($success);
}
if ($client->exit)
exit;
if ($success) {
// Now check if user exist with same email ID
try {
$result = $sq->getUserInfo($user->id);
if ($result["count"] > 0) {
// User Exist
$_SESSION["name"] = $result["name"];
$_SESSION["email"] = $result["email"];
$_SESSION["clevel"]=$result["clevel"];
$_SESSION["new_user"] = "no";
} else {
// New user, Insert in database
$result = $sq->putNewUserInfo($user->id,$user->name,$user->email);
if ($result===true) {
$_SESSION["name"] = $user->name;
$_SESSION["email"] = $user->email;
$_SESSION["new_user"] = "yes";
$_SESSION["e_msg"] = "";
}
}
$_SESSION["login_type"]="Google";
} catch (Exception $ex) {
$_SESSION["e_msg"] = $ex->getMessage();
}>
$_SESSION["user_id"] = $user->id;
} else {
$_SESSION["e_msg"] = $client->error;
}
header("Location: ".ROOT_DIR."homepage.php");
exit;
?>
StructuredQuery.php
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
require_once 'config.php';
class StructuredQuery{
var $opt;
var $pdo;
function __construct(){
$opt = [
PDO::ATTR_PERSISTENT => FALSE,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$this->pdo = new PDO(DB_DRIVER.":host=".DB_SERVER.";dbname=".DB_NAME, DB_SERVER_USERNAME, DB_SERVER_PASSWORD, $opt);
}
// Cross Site Script & Code Injection Sanitization
function xss_cleaner($input_str) {
$return_str = str_replace( array('<',';','|','&','>',"'",'"',')','('), array('<',':','|','&','>',''','"',')','('), $input_str );
$return_str = str_ireplace( '%3Cscript', '', $return_str );
return $return_str;
}
//SQLInjection detect
function sql_injection_detect($input_query){
try{
$blacklist=array('SELECT','WHERE','UPDATE','DELETE','INSERT','FROM','DROP','MERGE','SET','INSERT','REMOVE','REPLACE','QUERY');
$err_level=0;
foreach($blacklist as $blacklist_item){
if(stripos($input_query,$blacklist_item)!==false){
$err_level++; //Counter for number of blacklist words used. 2 means dangerous. Terminate immediately.
if($err_level==2){
die('Was that an IT joke? Cause I am a 12th grader, not an IT Pro.');
}
}
}
return true;
}catch(Exception $e){
echo 'Exception Occured:',$e->getMessage(),"\n";
die('You\'ve been Terminated');
}
}
function getUserInfo($user_id){
$user_id=xss_cleaner($user_id);
if(sql_injection_detect($user_id)){
$query=$pdo->prepare("select statement");
$query->bindParam(":user_id",$user_id,PDO::PARAM_STR);
$query->execute();
$result=$query->fetch();
$result["count"]=$query->rowCount();
return $result;
}
}
function putNewUserInfo($user_id,$name,$email){
$user_id=$this->xss_cleaner($user_id);
$name=xss_cleaner($name);
$email=xss_cleaner($email);
if(sql_injection_detect($user_id) && sql_injection_detect($name) && sql_injection_detect($email)){
$query=$pdo->prepare("insert statement");
$query->bindParam(":user_id",$user_id,PDO::PARAM_STR);
$query->bindParam(":name",$name,PDO::PARAM_STR);
$query->bindParam(":email",$email,PDO::PARAM_STR);
$query->execute();
return true;
}else{
return false;
}
}
function modifyUserInfo($user_id,$name,$email,$clevel){
$user_id=xss_cleaner($user_id);
$name=xss_cleaner($name);
$email=xss_cleaner($email);
$clevel=xss_cleaner($clevel);
if(sql_injection_detect($user_id) && sql_injection_detect($name) && sql_injection_detect($email) && sql_injection_detect($clevel)){
$query=$pdo->prepare("update statement");
$query->bindParam(":user_id",$user_id,PDO::PARAM_STR);
$query->bindParam(":name",$name,PDO::PARAM_STR);
$query->bindParam(":email",$email,PDO::PARAM_STR);
$query->bindParam(":clevel",$clevel,PDO::PARAM_INT);
$query->execute();
return true;
}else{
return false;
}
}
}
Now the issue that bothers me is this- whenever i press Login With Google, it redirects to google_login.php, well and fine. And then, directly to the homepage as if I am already logged in even though I am not. Even weirder is that it displays my e-mail and my username as blank, even though it says that I am an existing user.
P.S. No, the database does not contain any blank entries and it works fine, I double-checked.
I want to send data as xml from client to server using nusoap in php webservice. I am able to send it as an array. this is my code.
Client
<?php
$name='admin';
$pass='admin';
if(isset($_POST['submit'])){
require_once('lib/nusoap.php');
$client = new nusoap_client('http://localhost/web_service/server.php?wsdl', true);
$err = $client->getError();
if ($err) {
echo '<h2>Constructor error</h2><pre>' . $err . '</pre>';
}
$result = $client->call('login', array('name' => $name,'pass'=>$pass));
if ($client->fault) {
echo '<h2>Fault</h2><pre>';
print_r($result);
echo '</pre>';
} else {
$err = $client->getError();
if ($err) {
echo '<h2>Error</h2><pre>' . $err . '</pre>';
} else {
echo '<h2>Result</h2><pre>';
print_r($result);
echo '</pre>';
}
}
}
?>
Server
<?php
require_once('lib/nusoap.php');
$server = new soap_server();
$server->configureWSDL('server', 'urn:server');
$server->register('login',
array('name' => 'xsd:string','pass'=>'xsd:string'),
array('return' => 'xsd:string'),
'urn:server',
'urn:server#login',
'rpc',
'encoded',
'Login Authentication'
);
function login($name,$pass) {
if($name && $pass == 'admin'){
return 'Welcome, ' . $name;
}
else{
return '<h2>Oops,</h2> looks like something went wrong. Please try again';
}
}
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$server->service($HTTP_RAW_POST_DATA);
?>
I am looking to send the variables $name & $pass to server as xml and need the server to parse the xml and get the values. Is this possible.
I wrote a simple authentication plugin that uses a SOAP webservice to check the username and the password. That works fine.
I wanted to have some parameter like the SOAP password in the admin of joomla. So I have added the params in the xml, it shows fine in the admin. When I try to get the value of it the php, I get:
Fatal error: Call to a member function get() on a non-object
So I compared with other authentication and I do it exactly the same way.... I do not understand why it is so.
Here is the code of the Plugin:
public function __construct() {
$nusoap = JPATH_SITE . '/plugins/authentication/ers/nusoap/lib/nusoap.php';
if (! file_exists ( $nusoap )){
$response->error_message = "No such file";
return;
}
require_once ($nusoap);
}
function onUserAuthenticate($credentials, $options, &$response)
{
//Without defaults (the plugin crashes on the first get() bellow)
$webservice = $this->params->get('webservice', '');
$group = $this->params->get('group', '');
$whitepaw = $this->params->get('whitepaw', '');
JRequest::checkToken() or die( 'Invalid Token' );
// For JLog
$response->type = 'ERS SOAP Webservice';
// MyCompany does not like blank passwords (So does Joomla ;))
if (empty($credentials['password'])) {
$response->status = JAuthentication::STATUS_FAILURE;
$response->error_message = JText::_('JGLOBAL_AUTH_EMPTY_PASS_NOT_ALLOWED');
return false;
}
if (empty($credentials['username'])) {
$response->status = JAuthentication::STATUS_FAILURE;
$response->error_message = JText::_('Please enter a username');
return false;
}
// Add a user to joomla
function addJoomlaUser($name, $username, $password, $email, $group) {
$data = array(
"name"=>$name,
"username"=>$username,
"password"=>$password,
"password2"=>$password,
"email"=>$email,
"block"=>0,
"groups"=>array("1","2", $group) // the uer is added into the group "public" and "registered" as well as a group of the user's choice.
);
$user = clone(JFactory::getUser());
//Write to database
if(!$user->bind($data)) {
throw new Exception("Could not bind data. Error: " . $user->getError());
}
if (!$user->save()) {
throw new Exception("Could not save user. Error: " . $user->getError());
}
return $user->id;
}
// Pour supprimer le cache du web-service
ini_set('soap.wsdl_cache_enabled', 0);
// Nouveau Client SOAP
try {
// Nouvelle instance de la classe soapClient
$client = new SoapClient($webservice, array('trace' => true));
$username = $credentials['username'];
$password = $credentials['password'];
$result = $client->CheckLogin(array('whitepaw'=>$whitepaw, 'username'=>$username, 'password'=>$password));
if($result->isInDB){
$name = $result->fname.' '.$result->lname;
$email = $result->email;
$response->error_message = $username.'<br>'.$password.'<br>'.$name.'<br>'.$email."<br><br>".
"<b>Request :</b><br>".htmlentities($client->__getLastRequest())."<br><br>".
"<b>RESPONSE :</b><br>".htmlentities($client->__getLastResponse())."<br><br>";
if(!$result->email == '' || empty ($result)) {
//Todo: check if the user is already in joomla db
$user_id = addJoomlaUser($name, $username, $password, $email,$group);
$response->status = JAuthentication::STATUS_SUCCESS;
//for testing purposes
$response->error_message = $user_id;
} else {
$response->error_message = "The webservice did not return data".$email.'did you see it?';
}
} else {
$response->status = JAuthentication::STATUS_FAILURE;
$response->error_message = 'You do not have yet an account in myers. Please register.<br>';
$response->error_message .= $result->isInDB;
}
} catch (Exception $fault) {
$response->error_message = $fault->getMessage();
}
}
}
Since you have your own constructor, you need to call the parent constructor like this:
public function __construct(& $subject, $params = array()) {
$nusoap = JPATH_SITE . '/plugins/authentication/ers/nusoap/lib/nusoap.php';
if (! file_exists ( $nusoap )){
$response->error_message = "No such file";
return;
}
require_once ($nusoap);
// call the parent constructor
parent::__construct($subject, $params);
}
The parent constructor is where the $this->params object gets set, so if you don't call it then $this->params is never set. That's why you get the error saying params is not an object.
I'm trying to use mongodb with PHP.
For that, I have created a MongoHQ instance, but for some reasons when I try to insert something or any other operation from my php server I get the following error:
Fatal error: Uncaught exception 'MongoCursorException' with message 'unauthorized for db [datab] lock type: -1 ' in C:\Program Files\EasyPHP5.3.0\www\application\controllers\Stat.ctrl.php:56
Stack trace:
#0 C:\Program Files\EasyPHP5.3.0\www\application\controllers\Stat.ctrl.php(56): MongoCursor->rewind()
#1 C:\Program Files\EasyPHP5.3.0\www\index.php(105): Stat->index()
#2 {main} thrown in C:\Program Files\EasyPHP5.3.0\www\application\controllers\Stat.ctrl.php on line 56
Does anyone know where it can be coming from?
This is the php code I'm using:
$username = 'test';
$password = 'test';
try
{
$link = new Mongo( "flame.mongohq.com:27022/datab -u <".$username."> -p <".$password.">" );
//MongoDB::authenticate ( $username , $password )
//$link = new Mongo();
}
catch(MongoConnectionException $e)
{
die('Could not connect. Check to make sure MongoDB is running.');
}
$db = $link->datab;
$col = $db->order;
try
{
// Insert a document (row) into the collection (table)
$doc = array('login' => 'jsmith', 'password' => ' 5f4dcc3b5aa765', 'email' => 'jsmith#example.com');
$col->insert($doc, true);
$doc = array('login' => 'psmith', 'password' => ' 5f4dcc3b', 'email' => 'psmith#example.com');
$col->insert($doc, true);
}
catch(MongoCursorException $e)
{
echo 'Je suis la!';
}
// Get the id of last insert
$id = $doc['_id'];
// Get all documents
$res = $col->find();
echo 'All documents:<br/>';
foreach($res as $doc)
{
echo '<pre>';
print_r($doc);
echo '</pre>';
}
// Query for the document matching the last insert ID
$doc = $col->findone(array('_id' => $id));
echo 'Single document (_id = $id):<br/><pre>';
print_r($doc);
// Update a document
$col->update(array('_id' => $id), array('$set' => array('password' => 'b497dd1a701a33033620780d')));
// Query the updated docuemnt
$doc = $col->findone(array('_id' => $id));
echo 'Updated docuement:<br/><pre>';
print_r($doc);
echo '</pre>';
That is not the connection format MongoDB uses. See http://www.php.net/manual/en/mongo.construct.php.
You probably need to change it to something like:
$m = new Mongo("mongodb://$username:$password#flame.mongohq.com:27022/datab");