Quantcast
Channel: Scoreoid Support Wiki » Achievements
Viewing all articles
Browse latest Browse all 5

getPlayerField()

0
0

Scoreoid’s Open API methods are RESTful (HTTP/HTTPS) requests which return XML or JSON responses. The Scoreoid Open API works with every coding language making it truly cross platform. We recommend using the built in Scoreoid console via the Scoreoid dashboard to learn and test our Open API methods.

getPlayerField() method lets you pull a specific field from your player info.
API URL: https://api.scoreoid.com/v1/getPlayerField
POST Parameters
api_key=> Your API Key [Required]
game_id => Your Game ID [Required]
response => String Value, "XML" or "JSON" [Required]
username => String Value, the players username [Required]
field => String Value, the selected field (username, password, unique_id, first_name, last_name, email, platform, created,updated, bonus, achievements, best_score, gold, money, kills, lives, time_played, unlocked_levels, unlocked_items, inventory,last_level, current_level, current_time, current_bonus, current_kills, current_achievements, current_gold, current_unlocked_levels,current_unlocked_items, current_lifes, xp, energy, boost, latitude, longitude, game_state, platform, rank) [Required]
API Response Returns
The players fields value upon failure you well receive an error message, example - "Please enter player username" 
Code Snippets

The following are simple code snippets designed for basic examples, they do not follow best practice nor recommend guidelines. We have listed a number of the popular languages however Scoreoid supports every language that is able to use RESTful HTTP/HTTPS.

Example Response

Example response in JSON or XML format


JSON


{"best_score":150}


XML


<?xml version="1.0" encoding="UTF-8"?>
<best_score>150</best_score>



AS3


function getGame():void
{
    var url:String = "API URL";
    var request:URLRequest = new URLRequest(url);
    var requestVars:URLVariables = new URLVariables();
    request.data = requestVars;
    requestVars.api_key = "YOUR API KEY";
    requestVars.game_id = "YOUR GAME ID";
    requestVars.response ="XML";
        requestVars.username ="Players Username";
        requestVars.field ="the required field"
   
        request.method = URLRequestMethod.POST;
   
    var urlLoader:URLLoader = new URLLoader();
        urlLoader = new URLLoader();
        urlLoader.dataFormat = URLLoaderDataFormat.TEXT;
        urlLoader.addEventListener(Event.COMPLETE, loaderCompleteHandler);

        urlLoader.load(request);
}

function loaderCompleteHandler(event:Event):void
{
    trace("responseVars: " + event.target.data);
}

JavaScript/HTML5



For JavaScript and HTML5 web based games please use Scoroeid’s auto generated proxy check out the full wiki article for instructions.

For mobile or desktop based HTML5/JavaScript games use the standard XMLHttpRequest object (or any library that implements it). We recommend using jQuery Post or a normal Ajax call using pure Javascript does the job very quickly and avoids the overhead for loading the jQuery file. Do note we recommend that you test this thru the targeted platform debugger, if you run into any issues please fill out a support ticket.

jQuery post code snippet

$.post("API URL", {api_key:"api key",game_id:"game id",response:"xml"},
   function(data) {
     alert("Data Loaded: " + data);
     console.log("Data Loaded: " + data);
   });

Make sure to inculde the Javascript library in your files.

C#


// What we are sending
string post_data = "api_key=Your API Key&game_id=Your game ID&response=XML&username=Players username&field=the required field";

// URL
string uri = "API URL";

// Create a request
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create(uri); request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.Method = "POST";

// Turn our request string into a byte stream
byte[] postBytes = Encoding.ASCII.GetBytes(str);

// This is important - make sure you specify type this way
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postBytes.Length;
Stream requestStream = request.GetRequestStream();

// Now send it
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();

// Grab te response and print it out to the console along with the status code
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Console.WriteLine(new StreamReader(response.GetResponseStream()).ReadToEnd());
Console.WriteLine(response.StatusCode);

Lua



The following example uses LuaSocket libraries, taking from Corona’s network API’s
local function networkListener( event )
        if ( event.isError ) then
                print( "Network error!")
        else
                print ( "RESPONSE: " .. event.response )
        end
end
 
postData = "api_key=Your API Key&game_id=Your Game ID&response=xml&username=The Player Username&field=The Required Fied"
 
local params = {}
params.body = postData
 
network.request( "API URL", "POST", networkListener, params)

Objective C



The following example is using Cocoa
NSString *post = [NSString stringWithFormat:@"api_key=%@&game_id=%@&response=%@&username=%@&field=%@",
[self urlEncodeValue:Your API Key]
[self urlEncodeValue:Your Game ID]
[self urlEncodeValue:XML]
[self urlEncodeValue:The Player Username]
[self urlEncodeValue:The Required Field]];

NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:@"API URL"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

- (NSString *)urlEncodeValue:(NSString *)str
{
NSString *result = (NSString *) CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)str, NULL, CFSTR("?=&+"), kCFStringEncodingUTF8);
return [result autorelease];
}

Java



The following example is for Android, tested on Android 2.1
HttpPost httppost;
HttpClient httpclient;

// List with parameters and their values
List<NameValuePair> nameValuePairs;

String serverResponsePhrase;
int serverStatusCode;
String bytesSent;

httppost = new HttpPost(API URL);  
httpclient = new DefaultHttpClient();
nameValuePairs = new ArrayList<NameValuePair>(5);  

// Adding parameters to send to the HTTP server.
nameValuePairs.add(new BasicNameValuePair(api_key, Your API Key));
nameValuePairs.add(new BasicNameValuePair(game_id, Your game));
nameValuePairs.add(new BasicNameValuePair(response, XML)
nameValuePairs.add(new BasicNameValuePair(username, Players username));
nameValuePairs.add(new BasicNameValuePair(field, the required field));

// Send POST message  with given parameters to the HTTP server.
try {                    
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));  

HttpResponse response = httpclient.execute(httppost);

InputStream is = response.getEntity().getContent();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(20);

int current = 0;  
while((current = bis.read()) != -1)
{  
baf.append((byte)current);  
}  

bytesSent = new String(baf.toByteArray());

// Response from the server          
serverResponsePhrase = response.getStatusLine().getReasonPhrase();
serverStatusCode = response.getStatusLine().getStatusCode();
}
catch (Exception e) {
// Exception handling
}

C++



The following example uses libcurl C++ library
#include <stdio.h>
#include <curl/curl.h>
 
int main(void)
{
  CURL *curl;
  CURLcode res;
 
  curl = curl_easy_init();
  if(curl) {
    curl_easy_setopt(curl, CURLOPT_URL, "API URL");
    res = curl_easy_perform(curl);
 
    /* always cleanup */
    curl_easy_cleanup(curl);
  }
  return 0;
}

Unity



JavaScript example using Unity WWW class.
function Start () {

/* API  method */
var url = "API URL";

/* Unity WWW Class used for HTTP Request */
var form = new WWWForm();

form.AddField( "api_key", "YOUR API KEY" );
form.AddField( "game_id", "YOUR GAME ID");
form.AddField( "response", "xml");
form.AddField( "username", "Player Username");
form.AddField( "field", "The Required Field");

var www = new WWW( url, form );

/* Wait for request to complete */
yield www;

/* Check for errors */
if (www.error == null)
{
    /* Request completed! */
     Debug.Log("request completed!: " + www.data);
} else {
    /* Something wrong! */
    Debug.Log("WWW Error: "+ www.error);
 }
}

C# example using Unity WWW class.

    /* Use this for initialization */
    void Start () {
       
        /* API  method */
        string url = "API URL";

        /* Unity WWW Class used for HTTP Request */
        WWWForm form = new WWWForm();
       
        form.AddField( "api_key", "YOUR API KEY" );
        form.AddField( "game_id", "YOUR GAME ID");
        form.AddField( "response", "xml");
        form.AddField( "username", "Player Username");
        form.AddField( "field", "The Required Field");
       
        WWW www = new WWW(url, form);
        StartCoroutine(WaitForRequest(www));
    }
   
    IEnumerator WaitForRequest(WWW www)
    {
        yield return www;

        /* Check for errors */
        if (www.error == null)
        {
            Debug.Log("WWW Ok!: " + www.text);
        } else {
            Debug.Log("WWW Error: "+ www.error);
        }    
    }

MORE



The following example uses Python 3.0 http.client library (low-level library that implements RFC 2616).
>>> import http.client, urllib.parse
>>> params = urllib.parse.urlencode({'api_key': Your API Key, 'game_id': Your game, 'response': XML, 'username': Players username, 'field': the required field})

>>> conn = http.client.HTTPConnection("API URL:80")
>>> conn.request("POST", "/cgi-bin/query", params)
>>> response = conn.getresponse()
>>> print(response.status, response.reason)
200 OK
>>> data = response.read()
>>> conn.close()

The following example uses PHP.

// Submit those variables to the server
$post_data = array(
    'api_key' => 'Your API Key',
    'game_id' => 'Your Game ID',
    'response' => 'XML',
    'username' => 'Player username',
'field' => 'the required field'
);
 
// Send request
$result = post_request('API URL', $post_data);
 
if ($result['status'] == 'ok'){
 
    // Print headers
    echo $result['header'];
 
    echo '<hr />';
 
    // print the result of the whole request:
    echo $result['content'];
 
}
else {
    echo 'A error occured: ' . $result['error'];
}


The post getPlayerField() appeared first on Scoreoid Support Wiki.


Viewing all articles
Browse latest Browse all 5

Latest Images

Trending Articles





Latest Images