nusoap implementation for opencart - web-services

Hope that someone is familiar with OpenCart here. I have problem with my Nusoap implementation on OpenCart. This is my implementation
I created a new library file called ws.php (I have the entire nusoap folder in system/library/)
<?php
final class Ws {
public function __construct() {
require_once('nusoap/nusoap.php');
}
}
?>
I created a controller file in catalog/controller/webservice/ws.php
<?php
class ControllerWebserviceWs extends Controller {
private $error = array();
function __construct($registry) {
parent::__construct($registry);
$this->load->library('ws');
$ws = new Ws();
$this->nusoap_server = new soap_server();
$this->nusoap_server->configureWSDL("MemberWSDL",
"urn:MemberWSDL");
$this->nusoap_server->register(
"selectMemberInfo",
array(
"id" => "xsd:int",
),
array("return"=>"xsd:string"),
"urn:MemberWSDL",
"urn:MemberWSDL#selectMemberInfo",
"rpc",
"encoded",
"Get member's info"
);
}
function index(){
$this->nusoap_server->service(file_get_contents("php://input"));
}
function select_member_info() {
function selectMemberInfo($member_id) {
return 'hello';
}
$this->nusoap_server->service(file_get_contents("php://input"));
}
}
?>
This is my soap client residing on an application out of OpenCart
$nusoap_client=new
nusoap_client("http://localhost/opencart/index.php?route=webservice/ws");
$id = 90001; if($nusoap_client->fault)
{
$text = 'Error: '.$nusoap_client->fault;
}
else
{
if ($nusoap_client->getError())
{
$text = 'Error: '.$nusoap_client->getError();
}
else
{
$row = $nusoap_client->call(
'selectMemberInfo',
array($id),
'urn:MemberWSDL',
'urn:MemberWSDL#selectMemberInfo'
);
echo
''.htmlspecialchars($nusoap_client->response,
ENT_QUOTES).'';
}
}
?>
And this is what I get
HTTP/1.1 500 Internal Server Error Server: Microsoft-IIS/5.1 Date:
Tue, 04 Oct 2011 04:47:41 GMT Content-Type: text/xml;
charset=ISO-8859-1 X-Powered-By: PHP/5.3.1 Set-Cookie:
PHPSESSID=fas5fisb84rcs3g94njljhrhk4; path=/ Expires: Thu, 19 Nov 1981
08:52:00 GMT Cache-Control: no-store, no-cache, must-revalidate,
post-check=0, pre-check=0 Pragma: no-cache Set-Cookie: language=en;
expires=Thu, 03-Nov-2011 04:47:41 GMT; path=/; domain=localhost
Set-Cookie: currency=MYR; expires=Thu, 03-Nov-2011 04:47:41 GMT;
path=/; domain=localhost Server: NuSOAP Server v0.7.3 X-SOAP-Server:
NuSOAP/0.7.3 (1.114) Content-Length: 692
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/">
SOAP-ENV:Clientmethod &apos;selectMemberInfo&apos; not defined
in service
Have anyone tried to implement Nusoap/SOAP in OpenCart or any idea what goes wrong in my implementation?
Thanks in advance.

I have the same problem. But i realized that if you put the select_member_info() outside the main class, it is working!
I will write again as soon as i get a working solution.

Related

universal_cookie__WEBPACK_IMPORTED_MODULE_3__.default.remove is not a function

whenever am i trying to remove cookie its show me this error.
TypeError: universal_cookie__WEBPACK_IMPORTED_MODULE_3__.default.remove is not a function
this is my code
Logout = () =>{
var user = Cookies.get('shailuKiCookie');
// console.log(user);
if(user){
Cookies.remove("shailuKiCookie");
// alert("logout successfully");
window.location.reload(false);
}else{
window.location.reload(false);
}
}
enter image description here
function set_cookie(name, value) {
document.cookie = name +'='+ value +'; Path=/;';
}
function delete_cookie(name) {
document.cookie = name +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}
You don't have to specify a cookie value when you delete a cookie.
Just set the expires parameter to a past date:
note : HttpOnly cookies cannot be deleted with JavaScript on the client side.
you should create a Cookies object.
const cookies = new Cookies()
cookies.remove('cookie name')

Delete all cookies in page onUnload event

I try to use following code to delete all cookies in page unload event. However it doesn't seem to work in Chrome. Is there a better way to do it?
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var chip = cookies[i],
entry = chip.split("="),
name = entry[0];
document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT; domain=' + window.location.hostname + '; path=/ ';
}
From another post I got a hint. The cookies I want to delete has Host only flag. Therefore I can not set domain when I write cookie back. Here is a working copy.
ar cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var chip = cookies[i],
entry = chip.split("="),
name = entry[0];
document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT; path=/ ';
}

How to set that google translate cookie never expires?

Im using the google translate code on my page and it works good, but if I look at the cookie it says that it only have expiration during the session!? So I want to set it so it does´t expire, so that it is the same language when the user comes back as he choosed the first time.
Im using this now.
SOLVED! OK so with this the user can select a language and the next time he visit the page it is translated to the language he picked before!
var ckDomain;
function googleTranslateElementInit() {
function getCookie(name)
{
var re = new RegExp(name + "=([^;]+)");
var value = re.exec(document.cookie);
return (value != null) ? unescape(value[1]) : null;
}
var kakan;
var googkakan;
kakan=getCookie("googtrans22");
$$(document).on('change', '#google_translate_element', function (e) {
setTimeout(function(){
function getCookie(name)
{
var re = new RegExp(name + "=([^;]+)");
var value = re.exec(document.cookie);
return (value != null) ? unescape(value[1]) : null;
}
googkakan=getCookie("googtrans");
document.cookie = "googtrans22="+googkakan+"; expires=Thu, 07-Mar-2047 20:22:40 GMT; path=/" + ckDomain;
document.cookie = "googtrans22="+googkakan+"; expires=Thu, 07-Mar-2047 20:22:40 GMT; path=/";
},1000);
});
for (var ckDomain = window.location.hostname.split("."); 2 < ckDomain.length;){
ckDomain.shift();
}
ckDomain = ";domain=" + ckDomain.join(".");
// domain cookie
document.cookie = "googtrans="+kakan+"; expires=Thu, 07-Mar-2047 20:22:40 GMT; path=/" + ckDomain;
// host-only cookie (with no domain name definition)
document.cookie = "googtrans="+kakan+"; expires=Thu, 07-Mar-2047 20:22:40 GMT; path=/";
new google.translate.TranslateElement({
pageLanguage: 'sv',
autoDisplay: false,
layout: google.translate.TranslateElement
}, 'google_translate_element');
}
(function() {
var googleTranslateScript = document.createElement('script');
googleTranslateScript.type = 'text/javascript';
googleTranslateScript.async = true;
googleTranslateScript.src = 'https://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit';
( document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0] ).appendChild( googleTranslateScript );
})();
Apparently the library is forced to write over the cookie to make it expire at end of the session.
The good news is that before doing that it reads the existing cookie, so you can feed it before each initialization call.
To force the library to translate a Swedish page into English:
function googleTranslateElementInit() {
var ckDomain;
for (var ckDomain = window.location.hostname.split("."); 2 < ckDomain.length;){
ckDomain.shift();
}
ckDomain = ";domain=" + ckDomain.join(".");
// domain cookie
document.cookie = "googtrans=/sv/en; expires=Thu, 07-Mar-2047 20:22:40 GMT; path=/" + ckDomain;
// host-only cookie (with no domain name definition)
document.cookie = "googtrans=/sv/en; expires=Thu, 07-Mar-2047 20:22:40 GMT; path=/";
new google.translate.TranslateElement({
pageLanguage: 'sv',
autoDisplay: false,
layout: google.translate.TranslateElement
}, 'google_translate_element');
}

Testing ASP.NET Web API Multipart Form Data File upload

I am trying to use N-UNIT to test my web API application but I am unable to find a proper way to test my file upload method. Which would be the best approach to test the method?
Web API Controller:
[AcceptVerbs("post")]
public async Task<HttpResponseMessage> Validate()
{
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
return Request.CreateErrorResponse(HttpStatusCode.UnsupportedMediaType,"please submit a valid request");
}
var provider = new MultipartMemoryStreamProvider(); // this loads the file into memory for later on processing
try
{
await Request.Content.ReadAsMultipartAsync(provider);
var resp = new HttpResponseMessage(HttpStatusCode.OK);
foreach (var item in provider.Contents)
{
if (item.Headers.ContentDisposition.FileName != null)
{
Stream stream = item.ReadAsStreamAsync().Result;
// do some stuff and return response
resp.Content = new StringContent(result, Encoding.UTF8, "application/xml"); //text/plain "application/xml"
return resp;
}
}
return resp;
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
Based on your above comment, following is an example:
HttpClient client = new HttpClient();
MultipartFormDataContent formDataContent = new MultipartFormDataContent();
formDataContent.Add(new StringContent("Hello World!"),name: "greeting");
StreamContent file1 = new StreamContent(File.OpenRead(#"C:\Images\Image1.jpeg"));
file1.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
file1.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data");
file1.Headers.ContentDisposition.FileName = "Image1.jpeg";
formDataContent.Add(file1);
StreamContent file2 = new StreamContent(File.OpenRead(#"C:\Images\Image2.jpeg"));
file2.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
file2.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data");
file2.Headers.ContentDisposition.FileName = "Image1.jpeg";
formDataContent.Add(file2);
HttpResponseMessage response = client.PostAsync("http://loclhost:9095/api/fileuploads", formDataContent).Result;
The request over the wire would like:
POST http://localhost:9095/api/fileuploads HTTP/1.1
Content-Type: multipart/form-data; boundary="34d56c28-919b-42ab-8462-076b400bd03f"
Host: localhost:9095
Content-Length: 486
Expect: 100-continue
Connection: Keep-Alive
--34d56c28-919b-42ab-8462-076b400bd03f
Content-Type: text/plain; charset=utf-8
Content-Disposition: form-data; name=greeting
Hello World!
--34d56c28-919b-42ab-8462-076b400bd03f
Content-Type: image/jpeg
Content-Disposition: form-data; filename=Image1.jpeg
----Your Image here-------
--34d56c28-919b-42ab-8462-076b400bd03f
Content-Type: image/jpeg
Content-Disposition: form-data; filename=Image2.jpeg
----Your Image here-------
--34d56c28-919b-42ab-8462-076b400bd03f--
After spending a bit of time looking into WebClient I was able to come up with this:
try
{
var imageFile = Path.Combine("dir", "fileName");
WebClient webClient = new WebClient();
byte[] rawResponse = webClient.UploadFile(string.Format("{0}/api/values/", "http://localhost:12345/"), imageFile);
Console.WriteLine("Sever Response: {0}", System.Text.Encoding.ASCII.GetString(rawResponse)); // for debugging purposes
Console.WriteLine("File Upload was successful");
}
catch (WebException wexc)
{
Console.WriteLine("Failed with an exception of " + wexc.Message);
// anything other than 200 will trigger the WebException
}

Asmx web service basic authentication

I want to implement basic authentication using username and password validation in my asmx web service.
I don't want to use WCF and I know this is not secure way, but I need to use basic authentication without using https.
My web service is like this:
[WebService(Namespace = "http://www.mywebsite.com/")]
public class Service1
{
[WebMethod]
public string HelloWorld()
{
return "Hello world";
}
}
And I use this custom HttpModule:
public class BasicAuthHttpModule : IHttpModule
{
void IHttpModule.Init(HttpApplication context)
{
context.AuthenticateRequest += new EventHandler(OnAuthenticateRequest);
}
void OnAuthenticateRequest(object sender, EventArgs e)
{
string header = HttpContext.Current.Request.Headers["Authorization"];
if (header != null && header.StartsWith("Basic")) //if has header
{
string encodedUserPass = header.Substring(6).Trim(); //remove the "Basic"
Encoding encoding = Encoding.GetEncoding("iso-8859-1");
string userPass = encoding.GetString(Convert.FromBase64String(encodedUserPass));
string[] credentials = userPass.Split(':');
string username = credentials[0];
string password = credentials[1];
if(!MyUserValidator.Validate(username, password))
{
HttpContext.Current.Response.StatusCode = 401;
HttpContext.Current.Response.End();
}
}
else
{
//send request header for the 1st round
HttpContext context = HttpContext.Current;
context.Response.StatusCode = 401;
context.Response.AddHeader("WWW-Authenticate", String.Format("Basic realm=\"{0}\"", string.Empty));
}
}
void IHttpModule.Dispose()
{
}
}
And in the web.config I use this:
<?xml version="1.0"?>
<configuration>
<appSettings/>
<connectionStrings/>
<system.web>
<customErrors mode="Off" />
<compilation debug="true" targetFramework="4.0"/>
<authentication mode="None"/>
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<add name="BasicAuthHttpModule"
type="AuthService.BasicAuthHttpModule, AuthService" />
</modules>
</system.webServer>
</configuration>
The calling code is:
static void Main(string[] args)
{
var proxy = new Service1.Service1()
{
Credentials = new NetworkCredential("user1", "p#ssw0rd"),
PreAuthenticate = true
};
try
{
var result = proxy.HelloWorld();
Console.WriteLine(result);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.ReadKey();
}
when I use this web service, the service asks for basic authentication but header variable in the OnAuthenticateRequest method always is null and MyUserValidator.Validate() never run.
EDIT
The fiddler results:
POST http://www.mywebsite.com/Service1.asmx HTTP/1.1
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 2.0.50727.4927)
VsDebuggerCausalityData: uIDPo+drc57U77xGu/ZaOdYvw6IAAAAA8AjKQNpkV06FEWDEs2Oja2C+h3kM7dlDvnFfE1VlIIIACQAA
Content-Type: text/xml; charset=utf-8
SOAPAction: "http://www.mywebsite.com/HelloWorld"
Host: www.mywebsite.com
Content-Length: 291
Expect: 100-continue
Connection: Keep-Alive
<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><HelloWorld xmlns="http://www.mywebsite.com/" /></soap:Body></soap:Envelope>
HTTP/1.1 401 Unauthorized
Cache-Control: private
Content-Type: text/html
Server: Microsoft-IIS/7.5
WWW-Authenticate: Basic realm=""
X-AspNet-Version: 4.0.30319
WWW-Authenticate: Basic realm="www.mywebsite.com"
X-Powered-By: ASP.NET
Date: Sun, 03 Jun 2012 07:14:40 GMT
Content-Length: 1293
------------------------------------------------------------------
POST http://www.mywebsite.com/Service1.asmx HTTP/1.1
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 2.0.50727.4927)
VsDebuggerCausalityData: uIDPo+drc57U77xGu/ZaOdYvw6IAAAAA8AjKQNpkV06FEWDEs2Oja2C+h3kM7dlDvnFfE1VlIIIACQAA
Content-Type: text/xml; charset=utf-8
SOAPAction: "http://www.mywebsite.com/HelloWorld"
Authorization: Basic dXNlcjE6cEBzc3cwcmQ=
Host: www.mywebsite.com
Content-Length: 291
Expect: 100-continue
<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><HelloWorld xmlns="http://www.mywebsite.com/" /></soap:Body></soap:Envelope>
HTTP/1.1 401 Unauthorized
Content-Type: text/html
Server: Microsoft-IIS/7.5
WWW-Authenticate: Basic realm="www.mywebsite.com"
X-Powered-By: ASP.NET
Date: Sun, 03 Jun 2012 07:14:41 GMT
Content-Length: 1293
------------------------------------------------------------------
Change your custom HttpModule code to this:
public class BasicAuthHttpModule : IHttpModule
{
public void Dispose()
{
}
public void Init(HttpApplication application)
{
application.AuthenticateRequest += new
EventHandler(this.OnAuthenticateRequest);
application.EndRequest += new
EventHandler(this.OnEndRequest);
}
public void OnAuthenticateRequest(object source, EventArgs
eventArgs)
{
HttpApplication app = (HttpApplication)source;
string authHeader = app.Request.Headers["Authorization"];
if (!string.IsNullOrEmpty(authHeader))
{
string authStr = app.Request.Headers["Authorization"];
if (authStr == null || authStr.Length == 0)
{
return;
}
authStr = authStr.Trim();
if (authStr.IndexOf("Basic", 0) != 0)
{
return;
}
authStr = authStr.Trim();
string encodedCredentials = authStr.Substring(6);
byte[] decodedBytes =
Convert.FromBase64String(encodedCredentials);
string s = new ASCIIEncoding().GetString(decodedBytes);
string[] userPass = s.Split(new char[] { ':' });
string username = userPass[0];
string password = userPass[1];
if (!MyUserValidator.Validate(username, password))
{
DenyAccess(app);
return;
}
}
else
{
app.Response.StatusCode = 401;
app.Response.End();
}
}
public void OnEndRequest(object source, EventArgs eventArgs)
{
if (HttpContext.Current.Response.StatusCode == 401)
{
HttpContext context = HttpContext.Current;
context.Response.StatusCode = 401;
context.Response.AddHeader("WWW-Authenticate", "Basic Realm");
}
}
private void DenyAccess(HttpApplication app)
{
app.Response.StatusCode = 401;
app.Response.StatusDescription = "Access Denied";
app.Response.Write("401 Access Denied");
app.CompleteRequest();
}
}
Then enable Anonymous authentication and disable Basic, Digest and Windows authentication for your website in IIS.
Note: This implementation will work with WCF too.
It seems that you need send the headers manually the first time:
from Rick Strahl's Blog
string url = "http://rasnote/wconnect/admin/wc.wc?_maintain~ShowStatus";
HttpWebRequest req = HttpWebRequest.Create(url) as HttpWebRequest;
string user = "ricks";
string pwd = "secret";
string domain = "www.west-wind.com";
string auth = "Basic " + Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(user + ":" + pwd));
req.PreAuthenticate = true;
req.Headers.Add("Authorization", auth);
req.UserAgent = ": Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 (.NET CLR 4.0.20506)";
WebResponse resp = req.GetResponse();
resp.Close();