I am beginner for webservice. I am writing a webservice in Moodle.
I would like to write one service for user sign up. In this case that user will not have any token or username+password.
How we can allow this user to call core_user_createUsers web service for sign up?
For other services I am using this code:
$domainname = 'http://mydomain/moodle';
require_once('./curl.php');
$curl = new curl;
$authurl = $domainname .'/login/token.php?username=admin&password=Admin123$&service=shcs_services';
$resp = $curl->get($authurl);
if($resp)
{
$resp = json_decode($resp);
$authToken = $resp->token;
}
/// PARAMETERS
$serverurl = $domainname . '/webservice/rest/server.php';
$params['wstoken'] = $authToken;
$params['wsfunction'] = 'core_user_createUsers';
$params['moodlewsrestformat'] = 'json';
$user1 = new stdClass();
$user1->username = 'testusername';
$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'));
$users = array($user1);
$params['users'] = $users;
$resp = $curl->post($serverurl, $params);
echo $resp;
in above code I would like to skip the below part
$authurl = $domainname .'/login/token.php?username=admin&password=Admin123$&service=shcs_services';
$resp = $curl->get($authurl);
if($resp)
{
$resp = json_decode($resp);
$authToken = $resp->token;
}
so that I don't want to pass the value $params['wstoken'] = $authToken; to web service .
But it is not allowing me without the token. Here's the error I get:
{"exception":"moodle_exception","errorcode":"invalidtoken","message":"Invalid token - token not found"}
Token is the only way to connect the web service to with your app. It is must. As I am working nowadays on web services and mobile app. So I experienced that token is the only way to validate the web services. The first step to connect with web service by validating it. And you are not passing the token at all. So your validation is going to be failed. and you are getting this error.
Related
I have 2 cookieAuthenticationoptions in my OWINStartup code, but only the first one is getting honored.
I cannot find any info. online on this, so will appreciate if someone can help me, if this is even possible. Here is my code:
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
// Enable clients to authenticate using cookies
var cookieOptions = new CookieAuthenticationOptions
{
AuthenticationType = "type1",
LoginPath = new PathString("/"),
SlidingExpiration = true,
Provider =
new CookieAuthenticationProvider
{
OnValidateIdentity = OnValidateIdentityAsync,
OnException = OnCookieException,
OnResponseSignIn = OnResponseSignIn,
},
};
// For auth tokens to properly work for both delve.office.com and <region>.delve.office.com
// we use a separate auth cookie per region/deployment.
if (!IsDevBox.Value)
{
cookieOptions.CookieName = AuthCookieNameWithoutSuffix + CookieHelper.GetCookieSuffix();
cookieOptions.CookieDomain = AuthCookieDomain;
}
// Enable clients to authenticate using cookies
var cookieOptions_BearerToken = new CookieAuthenticationOptions
{
AuthenticationType = "type2",
CookieName = "BearerToken",
LoginPath = new PathString("/"),
SlidingExpiration = true,
Provider =
new CookieAuthenticationProvider
{
OnValidateIdentity = OnValidateIdentityAsync_BearerToken,
OnException = OnCookieException,
OnResponseSignIn = OnResponseSignIn,
},
};
app.UseCookieAuthentication(cookieOptions);
app.UseCookieAuthentication(cookieOptions_BearerToken);
If I just use the BearerToken option, it works - but in the above case it is not getting honored. Any ideas?
Thanks so much!
Okey so after searching for 3 hours and trying various options, I no longer have any clue how to solve this...
The situation:
Our nationwide packet deliverer (Die Post) offers a webservice for checking if an address exists.
I contacted them, received username and password for the application as well as the .wsdl-file.
I made a service reference to the downloaded file and can use the classes without problems.
Now the problem:
We have 2 other webservices which the previous programer set up with authentication and everything, I just copy pasted the code from one of the services and set everything to current one, but when I try to get a response, I always get an error (Internal Error), with no more information.
I found a way to get the last request and the only difference from the request to the one in the SoapUI (which works perfectly fine) is that, instead of "<soapenv:Header/>" it is
<s:Header>
<Action s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">http://post.ch/AdressCheckerExtern/V4-01-00</Action>
</s:Header>
The current code is:
// Create Request
PostAdressChecker.AdressCheckerRequestType adrRequest = new PostAdressChecker.AdressCheckerRequestType()
{
Street = strStrasse,
HouseNbr = strHausnummer,
Zip = strPlz,
Town = strOrt,
Params = new PostAdressChecker.AdressCheckerRequestTypeParams()
{
CallUser = "TU_99660_0001",
SearchLanguage = "1",
MaxRows = "10",
SearchType = "10"
}
};
BasicHttpBinding basicBinding = new BasicHttpBinding(BasicHttpSecurityMode.Transport)
{
ReaderQuotas = { MaxStringContentLength = int.MaxValue },
MaxReceivedMessageSize = int.MaxValue,
SendTimeout = new TimeSpan(0, 2, 0)
};
PostAdressChecker.ACHePortTypeClient client;
client = new PostAdressChecker.ACHePortTypeClient(basicBinding, new EndpointAddress(strUrl));
client.Endpoint.Behaviors.Add(new PostSigningEndpointBehavior(strUsername, strPassword));
SoapTracer RequestInterceptor = new SoapTracer();
client.Endpoint.Behaviors.Add(RequestInterceptor);
try
{
PostAdressChecker.AdressCheckerResponseType adrResponse = client.AdrCheckerExterne(adrRequest);
}
catch (Exception ex)
{
strError = ex.ToString();
}
Does anybody have an idea how to debug/solve this?
Thank you very much and best regards
in perl I do it like this. maybe this can give you some inspiration ...
sub clientFactory {
my $wsdl = XML::Compile::WSDL11->new('etc/adrCheckerExterne-V4-01-00.wsdl');
$wsdl->importDefinitions('etc/adrCheckerExterne-V4-01-00.xsd');
$wsdl->importDefinitions('etc/adrCheckerTypes-V4-01-00.xsd');
my $basic_auth = sub {
my ($request, $trace) = #_;
my $authorization = 'Basic '.
b64_encode "$adrCheckerUser:$adrCheckerPassword";
$request->header(Authorization => $authorization );
my $ua = $trace->{user_agent};
$ua->request($request);
};
return $wsdl->compileClient(
'AdrCheckerExterne',
transport_hook => $basic_auth,
aync => 1,
);
};
my $client = clientFactory;
my $check = $client->(
Params => {
MaxRows => 100,
CallUser => $adrCheckerUser,
SearchLanguage => 1,
SearchType => 1
},
FirstName => $first_name,
Name => ${last_name},
Street => ${street},
HouseNbr => ${nr},
Zip => ${zip},
Town => ${town},
HouseKey => 0,
PboxAddress => 0,
);
You need to add HouseKey = 0 to your adrRequest. This is a required input - you can just set it to 0 if you do not know it. Otherwise the service will return an error.
I have created a new information page named as request. In this I have added the following code
{
$mail = new Mail();
$namess = $this->request->post['name'];
$emailss = $this->request->post['email'];
$phoness = $this->request->post['phone'];
$phoness2 = $this->request->post['phone2'];
$enquiryss = $this->request->post['enquiry'];
$conve = $this->request->post['contactviae'];
if($conve == '1')
{
$emailsss = "Yes";
}
else
{
$phonesss = "Yes";
}
if(!isset($emailsss)){
$emailsss = "No";
}
if(!isset($phonesss)){
$phonesss = "No";
}
echo $body = "Hello Admin <br/><br/> You have recieved a request for product. The details for your product is as follow :
<br/><br/><table border='1'><tr><td>Name</td><td>$namess</td></tr><tr><td>Email</td><td>$emailss</td></tr>
<tr><td>Phone No</td><td>$phoness</td></tr><tr><td>Secondary Phone</td><td>$phoness2</td></tr><tr><td>Enquiry</td><td>$enquiryss</td></tr><tr><td>Contact Via Email</td><td>$emailsss</td></tr>
<tr><td>Contact Via Phone</td><td>$phonesss</td></tr></table><br/><br/>Thanks & Regards";
$mail->protocol = $this->config->get('config_mail_protocol');
$mail->parameter = $this->config->get('config_mail_parameter');
$mail->smtp_hostname = $this->config->get('config_mail_smtp_hostname');
$mail->smtp_username = $this->config->get('config_mail_smtp_username');
$mail->smtp_password = html_entity_decode($this->config->get('config_mail_smtp_password'), ENT_QUOTES, 'UTF-8');
$mail->smtp_port = $this->config->get('config_mail_smtp_port');
$mail->smtp_timeout = $this->config->get('config_mail_smtp_timeout');
$mail->setTo($this->config->get('config_email'));
$mail->setFrom($this->request->post['email']);
$mail->setSender(html_entity_decode($this->request->post['name'], ENT_QUOTES, 'UTF-8'));
$mail->setSubject("Request a product");
$mail->setHtml($body);
$this->response->redirect($this->url->link('information/request/success'));}
But after submitting the button it is redirecting to success page but not getting any mail. Plz help me what I am missing
able to send mail through contact page
Do you set the email configuration in the admin? It's in System > Settings > (Edit the store) > Mail
I'm using NetSuite webservice in my WP7 project.
This is the link that I use (the newer version):
https://webservices.na1.netsuite.com/wsdl/v2012_1_0/netsuite.wsdl
This worked perfectly in my C# console application, but not in WP7.
In WP7, it logs in successfully, but when adding anything (employee, customer, timebill, ...) I get the following error:
"Your connection has timed out. Please log in again"
UPDATE:
this is my console code:
NetSuiteService service = new NetSuiteService();
service.CookieContainer = new CookieContainer();
Passport passport = new Passport();
passport.account = "TSTDRVxxxxxx";
passport.email = "hamzeh.soboh#para-solutions.com";
RecordRef role = new RecordRef();
role.internalId = "3";
passport.role = role;
passport.password = "passxxxx";
Status status = service.login(passport).status;
and the following is my WP7 code:
NetSuitePortTypeClient service = new NetSuitePortTypeClient();
// service.CookieContainer = new CookieContainer();
Passport passport = new Passport();
passport.account = "TSTDRVxxxxxx";
passport.email = "hamzeh.soboh#para-solutions.com";
RecordRef role = new RecordRef();
role.internalId = "3";
passport.role = role;
passport.password = "passxxxx";
service.loginAsync(passport);
uncommenting the second statement causes a runtime error.
Try without cookies, something like this:
// Instantiate the NetSuite web services
netSuiteService = new DataCenterAwareNetSuiteService(*yourAccountNumber*);
netSuiteService.Timeout = 1000 * 60 * 60;
var appInfo = new ApplicationInfo();
//App info from application netsuite
appInfo.applicationId = *yourApplicationId*;
// Prepare login credentials for request level login
netSuiteService.passport = new Passport()
{
email = yourEmail*,
password = *yourPassword*,
account = *yourAccountNumber*
};
netSuiteService.applicationInfo = appInfo;
Prefs = new Preferences();
netSuiteService.preferences = Prefs;
SearchPreferences = new SearchPreferences();
netSuiteService.searchPreferences = SearchPreferences;
Prefs.warningAsErrorSpecified = true;
Prefs.warningAsError = false;
SearchPreferences.bodyFieldsOnly = false;
I read, i try, i looking informations about how add / update combinations by webservice, in presta 1.5.3 but still i don't know how to do that.
Can someone help me?
Assigning combinations to products via Webservice is a multi-step operation (unlike CSV import).
given a product with id_product
add product_options (BO Attribute Names)
add product_option_values (BO Attribute Values) to product_options
add combinations while specifying id_product
Start by initialising PrestaShopWebservice with DEBUG=true:
$api = new PrestaShopWebservice($psShopUrl, $psAuthKey, $psDebug);
Instead of building the XML from scratch get a template for the resource you need like this:
$sxml = $api->get(array('url' => $psShopUrl.'api/'.$resource.'?schema=blank'));
The response is a SimpleXMLElement which is a easier to manipulate than DOM.
NB: The response contains all wrapper nodes and you must send the same back in your request i.e. PSWebServiceLibrary will not recreate them for you.
<?xml version="1.0" encoding="UTF-8"?>
<prestashop xmlns:xlink="http://www.w3.org/1999/xlink">
<combination>
...
</combination>
</prestashop>
SXML manipulation example:
$schema = $api->get(array('url' => $psShopUrl.'api/product_options?schema=blank'));
$data = $schema->children()->children();
$data->is_color_group = false;
$data->group_type = $group_type; // radio, select
$data->name->language[0] = 'attribute private name';
$data->public_name->language[0] = 'attribute public name';
$xml = $schema->asXML(); // all of it!
$ret = $api->add(array('resource' => 'product_options', 'postXml' => $xml));
$id_attribute_group = (int)$ret->children()->children()->id; // save for next step
Then get product_option_values schema, set data and the id_attribute_group from previous step. And so on.
Updating is the same except you will get the resource by id and then edit:
$sxml = $api->get(array('resource' => $resource, 'id' => $id));
...
$ret = $api->edit(array('resource' => $resource, 'id' => $id, 'putXml' => $xml));
As for adding multiple id values to the product_option_values node in the combinations resource you can use the array_push shortcut []:
$data->associations->product_option_values->product_option_values[]->id = 123;
$data->associations->product_option_values->product_option_values[]->id = 456;
This is work fine for me :
$webService = new PrestaShopWebservice($url, $api_key, FALSE);
$xml = $webService->get(array('url' => $url .'/api/combinations?schema=blank'));
$resources = $xml->children()->children();
$resources->id_product = $ps_product_id;
$resources->wholesale_price = $wholesale_price;
$resources->price = $price;
$resources->unit_price_impact = $unit_price_impact;
$resources->minimal_quantity = $minimal_quantity;
$resources->quantity = $quantity;
$resources->weight = $weight;
$resources->associations->product_option_values->product_option_value[0]->id = $color_id;
$resources->associations->product_option_values->product_option_value[1]->id = $size_id;
$request = $xml->asXML();
//This is a function that curl request to specific URL using method (POST)
$response = ps_curl($url . '/api/combinations', $request, 'POST', $api_key);
$xml_load = simplexml_load_string($response);
$id = $xml_load->combination->id;
I hope that's helpful :)