Create a web service with CodeIgniter - web-services

im using CodeIgniter 1.7 framework to make my Website.
Another team do the mobile version for iPhone.
So the other team ask me to do a web service for authentification.
They tell that they will send me :
POST REQUEST
Input : login , password, push_token
if failure authentification -> Output HTTP : error code 0
if success -> Output XML :
<DATA>
<User id='id_user' title='..' first_name='' last_name='' email='' postal='' country_id=''/>
</DATA>
Basically i have this function for authentification:
function check_login($username="", $password="")
{
$username = $_POST['username'];
$password = $_POST['password'];
...
...
}
im looking into this post Codeigniter web services but i don't understand how its really work because im new in webservice.

I would consider using json as a sole output with one value being TRUE or FALSE depending on success. It's easier to handle, and all it requires is for your site to be in utf8.
If your check_login() returns TRUE, use that as the condition for success.
Example of reply:
/* Class etc. */
function do_login() {
$arr_json = array('success' => FALSE);
if ($this->login_library->check_login()) {
$arr_json['success'] = TRUE;
$arr_json['user_id'] = $this->login_library->user_id;
}
echo json_encode($arr_json);
}
login_library is just an example for your library which does the login. The reply they receive only needs to be decoded through json_decode(). And then simply check if the key success is TRUE or not.
If needed, have an extra key called error_message or similiar, and you can run all post-values through form_validation. Then you can also have $arr_json['error_message'] = trim(validation_errors('', "\n")); before the echo aswell.

You should definately look into Phil Sturgeons CodeIgniter Rest Server:
https://github.com/philsturgeon/codeigniter-restserver
There's a pretty good documentation. He also made a screencast about it: http://philsturgeon.co.uk/blog/2011/03/video-set-up-a-rest-api-with-codeigniter
Furthermore you could have a look at this article, where Adam Whitney explains his approach:
Building a RESTful Service using CodeIgniter
http://adamwhitney.net/blog/?p=707

Related

Posting data to Silex app ( jwt authentication using cnam/security-jwt-service-provider )

I am creating web service using silex micro framework. This is first time i am using it and I dont have prior knowledge on symfony. I could be able to understand how silex works and how to write controller providers , service providers etc ..
I couldnt work out authentication for my webservice.
I want to use JWT authentication and I found this cnam/security-jwt-service-provider extending firebase/php-jwt.
I set it up right and I get this output when I access protected resource
{"message":"A Token was not found in the TokenStorage."}
which is correct.
Question: I want to post the username , password to application and get token back. ( username=admin , password=foo )
I am using postman chrome extension ( also used Advanced rest client ) to post values to url ( http://silex.dev/api/login)
Post data I am sending
Key=> username Value=> admin
Key=> password Value=> foo
I also tried
Key=> _username Value=> admin
Key=> _password Value=> foo
Aldo tried key vaule pairs in basic auth headers.
response I get id
{
"success": false,
"error": "Invalid credentials"
}
When I debug the Application I see no post data at all.
$vars = json_decode($request->getContent(), true);
I get null $var.
PS: I know I will get a valid token back if I get these values posted correctly because I edited values from empty to correct values in breakpoint.
Apparently I should send data in json format and should set content-type appication/json
eg:
{
"_username":"admin",
"_password":"foo"
}
and response will something be like
{
success: true
token: "eyJ0eXAiOisKV1diLCJfbGgiOhJIjzI1NiJ9.eyJuYW1lIjoiYWRtaW4iLCJleHAiOjE0Mzk5MDUxMjh9.DMdXAv2Ay16iI1UQbHZABLCU_gsD_j9-gEU2M2L2MFQ"
}

Facebook realtime updates, no post update from facebook

I followed the guide realtime updates on facebook.
My application is a tab page.
I'm using the sandbox environment.
Initially set up by the signing of the dashboard.
The callback URL endpoint verify works fine.
I did an post on the page for only test.
But so far (after 24hrs), i received no update post from facebook.
On log apache server, there is no post from facebook too.
My callback script:
<?php
define('UPD_FILE', 'updates.log');
$method = $_SERVER['REQUEST_METHOD'];
global $log_file;
if ($method == 'GET' && $_GET['hub_mode'] == 'subscribe' && $_GET['hub_verify_token'] == 'jogabonito') {
echo $_GET['hub_challenge'];
exit;
}
else if ($method == 'POST')
{
$log_file=UPD_FILE;
$updates = json_decode(file_get_contents("php://input"), true);
logToFile("updates =".print_r($updates));
}
function logToFile($message){
global $log_file;
$hdl = fopen($log_file, 'a') or die ("couldn't open log file");
fwrite($hdl,$message."\n");
fclose($hdl);
}
?>
Grateful for the attention
Your code works (somewhat) fine after some requirements have been met.
You have subscribed successfully for at least one field change.
The user you are testing with has granted your app some or all of the required permissions for the fields you are subscribed for.
If one of the above isn't properly handled you won't be notified about related changes.
On another note I wrote "somewhat" because you are dumping the array content using print_r without specifying that the function should return the data rather than print it. The way you have it right now will result in a "1" result.
What you need should look more like this:
logToFile("updates =".print_r($updates, true));
I was facing the same problem, below solution fixed my problem,
just make an POST request to the following URL
https://graph.facebook.com/PAGE_ID/tabs?app_id=APP_ID&access_token=PAGE_ACCESS_TOKEN
Please replace the values before making a request

Trouble with SOAP request from Flex

SUM: I ended up having to form the XML manually. I also had to create an Operation and use its send(); method rather than just doing something like WebService.MyServiceFunction(); - not sure why that was the case.
I send off the request as follows:
var xm:XML =
<SetPropertiesForCurrentUser xmlns="http://asp.net/ApplicationServices/v200">
<values xmlns:d4p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<d4p1:KeyValueOfstringanyType>
<d4p1:Key>{obj.Key}</d4p1:Key>
<d4p1:Value xmlns:d6p1="http://www.w3.org/2001/XMLSchema" i:type="d6p1:string">{obj.Value}</d4p1:Value>
</d4p1:KeyValueOfstringanyType>
</values>
</SetPropertiesForCurrentUser>;
var profileService:WebService = new WebService();
profileService.useProxy = false;
profileService.loadWSDL(url);
var o:Operation = profileService.SetPropertiesForCurrentUser;
o.send(xm);
Here’s my scenario:
I have ASP.NET web services to handle authentication, user roles, and user profiles (default ASP.NET AuthenticationService, RoleService, and ProfileService, to be exact).
So from my Flex web app, I am able to successfully call the ASP.NET service. For example, something like this works fine:
var profileService:WebService = new WebService();
profileService.useProxy = false;
profileService.GetAllPropertiesForCurrentUser.addEventListener("result",getAllPropertiesForCurrentUser_EventHandler);
profileService.addEventListener("fault",getAllPropertiesForCurrentUserFault_EventHandler);
profileService.loadWSDL(url);
profileService.GetAllPropertiesForCurrentUser();
I run into trouble when I need to pass a Dictionary object to another function on the service (SetPropertiesForCurrentUser). The .NET service asks for this type of value:
System.Collections.Generic.IDictionary(Of String, Object)
Here are the two pertinent entries from the web.config entry from my ASP.NET service:
<properties>
<clear/>
<add name="coordinateFormat" />
</properties>
...
<profileService enabled="true"
readAccessProperties="coordinateFormat"
writeAccessProperties="coordinateFormat"/>
So after putting together a SOAP request from a Silverlight app (which works as expected) I’ve narrowed it down to a difference in the XML request sent to the SOAP handler:
From Flex:
<tns:Value>DMS</tns:Value>
From Silverlight:
<d4p1:Value xmlns:d6p1="http://www.w3.org/2001/XMLSchema" i:type="d6p1:string">DMS</d4p1:Value>
If I take the request generated by Flex, catch it with Fiddler, modify that one line to include the “type” namespace – it works.
Anyone have an idea how I can get that namespace onto my variable that is passed to the SOAP handler from Actionscript? Here is my code for sending off that SetPropertiesForCurrentUser function:
var obj:Object = {};
obj["Key"] = "coordinateFormat";
obj["Value"] = DMS;
var profileService:WebService = new WebService();
profileService.useProxy = false;
profileService.SetPropertiesForCurrentUser.addEventListener("result",setPropertiesForCurrentUser_EventHandler);
profileService.addEventListener("fault",setPropertiesForCurrentUserFault_EventHandler);
profileService.loadWSDL(url);
profileService.SetPropertiesForCurrentUser(new ArrayCollection([obj]),false);
Thanks,
Josh
The default SOAPEncoder that is used is some what limited in its capabilities (like not including the type attribute you mentioned above). Luckily, there is a way to control that by writing your own encoder.
see this link at adobe (read part about using custom web service serialization) Link on Adobe's Site

Unable to set headers in apex web service callouts in salesforce

I'm currently trying to call Amazon Product Retail Web Service in Salesforce.
As I mentioned in
Getting WSDL parse error while generating Apex code from WSDL in Salesforce
I was initially unable to generate apex stub class, but I followed the method suggested by #Ballinger and created apex class. I wrote an apex class to use that stub and to set request parameters. The class i wrote is as follows
public class AmazonProductStubNew
{
public static void getResults()
{
System.Debug(' getResults start ');
AmazonWS.AWSECommerceServicePortUS stub = new AmazonWS.AWSECommerceServicePortUS();
stub.inputHttpHeaders_x = new Map<String,String>();
stub.inputHttpHeaders_x.put('AWSAccessKeyId','MyAmazonAWSAccessKeyId');
stub.inputHttpHeaders_x.put('Timestamp','2012-11-28T12:11:30Z');
stub.inputHttpHeaders_x.put('Signature','Encrypted Secret Code');
String MarketplaceDomain = '';
String AWSAccessKeyId = 'MyAmazonAWSAccessKeyId';
String AssociateTag = '';
String XMLEscaping = '';
String Validate = '';
AmazonWS.ItemSearchRequest Shared = new AmazonWS.ItemSearchRequest();
Shared.SearchIndex = 'DVD';
AmazonWS.ItemSearchRequest[] Request = new AmazonWS.ItemSearchRequest[1];
Request[0] = new AmazonWS.ItemSearchRequest();
Request[0].Title = 'Inception';
AmazonWS.ItemSearchResponse_element response = stub.ItemSearch(MarketplaceDomain,AWSAccessKeyId,AssociateTag,XMLEscaping,Validate,Shared,Request);
AmazonWS.Items_element[] localItems = response.Items;
System.Debug(localItems[0].TotalResults);
}
}
Even though I've added HTTP headers to stub, I'm not getting it in XML Request message
XML Request is as follows
<?xml version="1.0" encoding="UTF-8"?>
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<env:Header />
<env:Body>
<ItemSearch xmlns="http://webservices.amazon.com/AWSECommerceService/2011-08-01">
<MarketplaceDomain>
</MarketplaceDomain>
<AWSAccessKeyId>MyAWSAccessKeyId</AWSAccessKeyId>
<AssociateTag></AssociateTag>
<XMLEscaping></XMLEscaping>
<Validate></Validate>
<Shared><SearchIndex>DVD</SearchIndex></Shared>
<Request><Title>Inception</Title>
</Request></ItemSearch>
</env:Body></env:Envelope>
Since headers are not there in SOAP Request, There is a SOAP fault asking for Signature from Amazon Server.
As you can see, I'm new to Salesforce Apex. I followed the steps in
http://www.salesforce.com/us/developer/docs/apexcode/index_Left.htm#StartTopic=Content/apex_web_services_wsdl2apex.htm#http_header_support
to set the headers.
Any idea on why the header isn't getting added?
P.S I added headers manually and tried in SOAP UI, I'm getting proper response.
Thanks :)
I think you're using wrong functions :) (question is indeed confusing).
SOAP (or generally HTTP) communication consists of sending headers and actual message (payload if you like). Headers are short text thingies, message is often a giant XML.
Your code is setting HTTP headers (which are used in web communication to authenticate, provide info about your browser, preferred languages, set cookies, return status codes like 404 page not found...) Please don't be offended with the "for dummies" but I realize the wikipedia article is a bit too much, this might be simpler: http://net.tutsplus.com/tutorials/other/http-headers-for-dummies/
And what I suspect Amazon's webservice wants is just some fields inside the <env:Header>...</env:Header> tag? Just check the generated apex code for existence of subclass called "Header" (you can also search for the variable names like "Signature". This is going to be a total wild guess but I think you'll have to write something like that:
AmazonWS.AWSECommerceServicePortUS stub = new AmazonWS.AWSECommerceServicePortUS();
AmazonWS.Header h = new AmazonWS.Header();
h.AWSAccessKeyId = 'MyAmazonAWSAccessKeyId';
h.Timestamp = '2012-11-28T12:11:30Z';
h.Signature = 'Encrypted Secret Code';
stub.Header = h; // plug it into the request
// create and plug other required tags
AmazonWS.ItemSearchRequest Shared = new AmazonWS.ItemSearchRequest();
Shared.SearchIndex = 'DVD';
AmazonWS.ItemSearchRequest[] Request = new AmazonWS.ItemSearchRequest[1];
Request[0] = new AmazonWS.ItemSearchRequest();
Request[0].Title = 'Inception';
// ...
Now, to make it more confusing you might still have to use a HTTP header, there's a special one called SOAPAction. But generally speaking I believe you're after placing your data in the XML, not in http headers.
Funny enough, I've downloaded the Java example from http://aws.amazon.com/code/Product-Advertising-API/2478 and if I read it correctly they're passing the signature in the URL (endpoint), not in the XML. Probably because it's a REST GET method (if you can access that API it could save you a lot of hair pulled, SOAP is clunky).

CF8 and Salesforce REST API - updating records

I'm trying to do integration with Salesforce using their REST API and CF8.
I got the OAuth bit working, getting data etc but now I'm trying to update some records in Contact table.
First I tought about doing it the "proper" way as their docs say -
Update a record using HTTP PATCH.
But CFHTTP doesn't support PATCH method.
So then I tried running a SOQL query:
UPDATE Contact SET MailingStreet = 'Blah Blah' WHERE Id = '003A000000Zp4ObIAJ'
but here I'm getting
{"message":"unexpected token: UPDATE","errorCode":"MALFORMED_QUERY"}
Does anyone have an idea how to do it?
You can create your own PATCH method if your client supports it, but there is an easier way. From the Force.com REST API Developer's Guide:
If you use an HTTP library that doesn't allow overriding or setting an
arbitrary HTTP method name, you can send a POST request and provide an
override to the HTTP method via the query string parameter
_HttpMethod. In the PATCH example, you can replace the PostMethod line
with one that doesn't use override:
PostMethod m = new PostMethod(url + "?_HttpMethod=PATCH");
In CF9 CFScript, using the method that Paddyslacker already suggested for adding _HttpMethod=PATCH to the URL:
private boolean function patchObject(required string sfid, required string type, required struct obj) {
local.url = variables.salesforceInstance & '/services/data/v' & variables.apiVersion &'/sobjects/' & arguments.type & '/' & arguments.sfid &'?_HttpMethod=PATCH';
local.http = new Http(url=local.url,method='post');
//... convert obj to a json string, add to local.http ...
local.httpSendResult = local.http.send().getPrefix();
}
We have a CF9 CFC that we wrote that wraps most of the REST API that we will be open sourcing soon. I'll come back and link to it when we do.