SlideShare a Scribd company logo
NK API
              Examples




Games and
application              Websites
     s




                               (c) Jarosław Gomułka 2012
API types:

● REST
● JS
REST API
Documentation

Created for mobile application and website solutions.
REST API
Authentication is based on OAuth standard. There are many libraries supporting this
standard. Have a look here:: http://oauth.net/code/


First you need to get nk_token via /token/get request.

POST https://opensocial.nk-net.pl/v09/token/get


POST data:
login=loginUseraNaNk&password=hasłoUseraNaNk


[no cookies]


Request Headers:
<next slide>
REST API - /token/get - headers
Request Headers:
Content-Type: application/x-www-form-urlencoded
Content-Length: 28
Authorization: OAuth oauth_signature_method="HMAC-SHA1", oauth_consumer_key="customerKeyZPanelu",
oauth_timestamp="1352376881", oauth_nonce="272317321310634", oauth_version="1.0", oauth_signature="
jVaVvVZcLZ1mMHzU3dzAmw3vxPE%3D"


oauth_version="1.0",
oauth_timestamp="1352376881"
oauth_nonce="272317321310634" - must be unique, at least 15 characters
oauth_signature_method="HMAC-SHA1" - you must enter this value
oauth_signature="jVaVvVZcLZ1mMHzU3dzAmw3vxPE%3D" - it needs to be calculated:)


oauth_signature obliczamy poprzez base64_encode(HMAC-SHA1(oauth_base_string, <secret from developer panel>&));


If everything goes correctly, we will get the answer:


nk_token=jakiśDziwnyNapisWBase64
REST API - base string
Example of value POST&http%3A%2F%2Fjava1.omega.nknet%3A2080%2Fv09%2Ftoken%2Fget&login%
3Dabcef%26oauth_consumer_key%3DjakisCustomerKey%26oauth_nonce%3D273217097465315%
26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1352377781%26oauth_version%3D1.
0%26password%3DjakiśPassword


First part POST - as we were sending POST request
Second part is URL without query parameters, encoded via urldecode function
Third part are all sorted and concatenated parameters .



Remember to sign the request content (when it makes sens - check: question reported to NKsupport).


All requests need to be signed with this mechanism.
REST API - @me, @self, @all
Many endpoint specifications show strange elements like: @me, @self, @all.


@me - user currently logged in
@self, @friends, @all - indicates who can check the object on which the action is done
Download user data
GET http://opensocial.nk-net.pl/v09/social/rest/people/person.602916f34c2ee73d/@self?
nk_token=pynHhd5gLOetEOL3HtkFLwAUZ-4jHwMb6yda8Dkk-ratXkexcYcJhjWliEusR_QGTpBLvl1Rto51k8-
s24l9O9wFKaqQ9mvNDMKSU90Gp2f


[no cookies]


Request Headers:
Authorization: OAuth oauth_signature_method="HMAC-SHA1", oauth_consumer_key="psiloctest1", oauth_timestamp="
1352379660", oauth_nonce="275096425520387", oauth_version="1.0", oauth_signature="GeGBNljcPKIQPeLXgCtYX8zgVCY%3D"
Connection: keep-alive


Response:


{"entry":{"isOwner":true,"isViewer":true,"id":"person.602916f34c2ee73d","thumbnailUrl":"http://s.m.nk.
pl/img/avatar/avatar_default_female","name":{"formatted":"du1 mnk (u003cscriptu003ealert(1);u003c/scriptu003e)","
additionalName":"mnk (u003cscriptu003ealert(1);u003c/scriptu003e)","familyName":"mnk","givenName":"du1"},"photos":
[{"value":"http://s.m.nk.pl/img/avatar/avatar_default_female","type":"thumbnail"}],"displayName":"du1 mnk
(u003cscriptu003ealert(1);u003c/scriptu003e)"}}
Adding shout
POST https://opensocial.nk-net.pl/v09/social/rest/activities/@me/@self/app.sledzik?nk_token=pynHhd5gLOetEOL3HtkFLwAUZ-
4jHwMb6yda8Dkk-ratXkexcYcJhjWliEusR_QGTpBLvl1Rto51k8-s24l9O9wFKaqQ9mvNDMKSU90Gp2f


POST data:
{"title":"Some short text 123"}


[no cookies]


Request Headers:
Content-Type: application/json
Content-Length: 31
Authorization: OAuth oauth_body_hash="%2FIyGusEZ4w8%2BuI9gOr5emjQha9E%3D", oauth_signature_method="HMAC-SHA1",
oauth_consumer_key="psiloctest1", oauth_timestamp="1352379705", oauth_nonce="275140932345687", oauth_version="1.0",
oauth_signature="Rhv3r9eVAx66MDlcTepvQ7bPkuw%3D"
Connection: close


Response 200:
{"entry":{}}
When something is not working...
We suggest the following steps:
●   Check the error code. You can find many useful information there.
●   Check logs - http://developers.nk.pl/applications-logs/
●   Catch the request with tcpdump or extract it with netcat. Then check if data is
    sent according to the specification
●   Describe the problem in details in NK support
API JS
In this part we will show you how to create Opensocial applications.
Shindig is used as application container which implements OpenSocial standard
Shindig is responsible for:
 ●    application rendering
 ●    proxy request creation
 ●    data cache
 ●    RPC/REST requests



We are supporting OpenSociala ver 0.9.


List of all functionalities we are supporting
is accessible in our documentation.
API JS
Aplikacje definiujemy przez pojedynczy plik gadget.xml
Adres do tego pliku podajemy w panelu zarządzania aplikacjami i stronami.
Preparation of development environment
1.   You create application in https://developers.nk.pl/developers
2.   Set debug mode (data cache is disabled)
3.   You add tester ID on application tester list
4.   Enter your application: http://nk.pl/#applications_test/xyz (the exact link is in
     application settings)

For the beginning we can put the following, classic example code as gadget.xml:
 <?xml version="1.0" encoding="UTF-8" ?>
 <Module>
  <ModulePrefs/>
  <Content type="html" view="canvas">
   <![CDATA[
     Hello World
   ]]>
  </Content>
 </Module>
Examples:
Following examples are available under this URL:
https://github.com/jaaro/various/tree/master/nk


1.   ROT13
2.   Information about the user
3.   Informacje about friends
4.   Embedding flash
5.   Swfobject
6.   Hamster fall
7.   Adding shout on NK

We suggest to test other JS API functionalities in this application: nkda.
Payments- JS code
function handlePaymentResponse(dataItem) {
if (dataItem.hadError()) {
    alert('got an error');
} else {
    var orderId = dataItem.getData().getField(opensocial.Payment.Field.ORDER_ID);
    alert('payment request accepted, orderId: ' + orderId);
}
}


function makePayment() {
var params = {};


params[opensocial.Payment.Field.AMOUNT] = 5;
params[opensocial.Payment.Field.MESSAGE] = "large sword";
params[opensocial.Payment.Field.PARAMETERS] = "some_app_specific_params";


var payment = opensocial.newPayment(params);
opensocial.requestPayment(payment, handlePaymentResponse);
}
Payments
Enter the right value in "Payment Callback URL" field (Administration panel):




When transaction is completed, nk is sending under this URL the following request:

POST /some/url HTTP/1.1
Host: gamehost.com
Content-Type: application/x-www-form-urlencoded


amount=5&appId=app.1&containerDomain=nk.pl&message=large%20sword&oauth_consumer_key=key&
oauth_nonce=252b9d59381dd803dcf156663d1375d9&oauth_signature=%2F7%2BGAbB0DDYNZwC%2BsSACe1O5Kpw%3D&
oauth_signature_method=HMAC-SHA1&oauth_timestamp=1273755263&oauth_version=1.0&
orderId=32787067d4de27d7fb97d816723d5c75bb9fd337&parameters=some_app_specific_params&
paymentType=payment&viewerId=person.abc
Payments
Application must confirm the payment has been received by generating the following
response:

HTTP/1.1 200 OK
Content-Type: application/json


{"orderId":"32787067d4de27d7fb97d816723d5c75bb9fd337","responseCode":"ok","responseMessage":"all
ok","signature":"7e7455aac4a1be3186185e5bd056791adf01818c"}


If the confirmation (response) is not ok, NK server will send request every minute for next 24hours or till we get
the correct response.


If you want to test payments, send e-mail to egbtest@nasza-klasa.pl with request for specified amount of NK
currency (EGB) , you NK profile ID and name of the application you are testing.
Inviting friends to the application:
function handleInviteFriendResponse(responseItem) {
    if (responseItem.hadError()) {
        // handle error
    } else {
        alert(responseItem.getData() + ' invited friend(s)');
    }
}
function invite() {


    var msg = 'Join me !';


    var paramsObject = new Object();
    nk.requestInviteFriends(msg, paramsObject, handleInviteFriendResponse);
}


invite();
Check if user is already member of the
application group.
function response(data) {
if (data.hadError()) {
 // handle error
} else {
 var result = data.get("isInGroup").getData();
 if (result) {
     output("User is in application's group");
 } else {
     output("User is NOT in application's group");
 }
}
};
function request() {
var req = opensocial.newDataRequest();
req.add(nk.groups.newIsUserInAppGroupRequest(), "isInGroup");
req.send(response);
};


request();
Adding user to application group:
function callback(responseItem) {
if (responseItem.hadError()) {
    // handle error
} else {
    console.log(responseItem);
}
}


function invite() {
nk.groups.requestAddUserToAppGroup(callback);
}


invite();
Adding picture:
function uploadPhotoHandler(resp) {
    if (resp.hadError()) {
    // handle error
    }
}


function uploadPhoto() {
    nk.photos.requestUploadAppPhoto("Photo added from Dev App", null, uploadPhotoHandler);
}


uploadPhoto();
How many user have installed the
application?
function response(data) {
if (data.get("amount").hadError()) {
     // handle error
} else {
     alert(data.get("amount").getData());
}
};


function request() {
var req = opensocial.newDataRequest();
req.add(nk.newGetAmountOfUsersRequest(), "amount");
req.send(response);
};


request();
Adding shout:
function onActivityPosted(data) {
 if (data.hadError()) {
     alert("There was a problem: " + data.getErrorMessage());
 } else {
     output("The activity was posted successfully.");
 }
};


function postActivity(title) {
 var data = {};
 data[opensocial.Activity.Field.TITLE] = title;
 var activity = opensocial.newActivity(data);
 opensocial.requestCreateActivity(
      activity,
      opensocial.CreateActivityPriority.HIGH,
      onActivityPosted
 );
};
postActivity("This is a sample activity");
Communication between users - message
function response(data) {
 if (data.hadError()) {
     alert("There was a problem: " + data.getErrorMessage());
 } else {
     output("The message was sent.");
 }
};


function request() {
 var iconUrl = new opensocial.Url({"type" : "icon", "address" : "http://www.example.org/icons/notifyIcon.jpg"});
 var msgParams = {
     "title" : "Title of notification",
     "urls" : new Array(iconUrl), // image used in notification
     "type" : "notification",       // only notification is currently supported
 };
 var msg = opensocial.newMessage("Body of notification", msgParams); opensocial.requestSendMessage(["person.XXX"], msg,
response);
};


request();
JS API

You can find many other examples in our dokumentation
together with detailed features specification.

http://developers.nk.pl/documentation/nk-api/opensocial-js-api/
Some interesting features:
Please note, that even if we support some features, they may not be operated in the same way as in original
OpenSocial specification, for example: Activity.


List of supported paramenters is here: http://developers.nk.pl/documentation/nk-api/opensocial-js-api/


Interesting features:


gadgets.log / gadgets.warn / gadgets.error


gadgets.json.parse / gadgets.json.stringify


gadgets.window.adjustHeight


gadgets.io.makeRequest / osapi.http.get

More Related Content

What's hot

Knot.x: when Vert.x and RxJava meet
Knot.x: when Vert.x and RxJava meetKnot.x: when Vert.x and RxJava meet
Knot.x: when Vert.x and RxJava meet
Tomasz Michalak
 
Javascript 2
Javascript 2Javascript 2
Javascript 2
pavishkumarsingh
 
Api docs v4.0
Api docs v4.0Api docs v4.0
Api docs v4.0Anh Tuan
 
Authentication
AuthenticationAuthentication
Authenticationsoon
 
Ajax chap 4
Ajax chap 4Ajax chap 4
Ajax chap 4
Mukesh Tekwani
 
Ajax chap 5
Ajax chap 5Ajax chap 5
Ajax chap 5
Mukesh Tekwani
 
CIS 2015b FIDO U2F in 10 minutes - Dirk Balfanz
CIS 2015b FIDO U2F in 10 minutes - Dirk BalfanzCIS 2015b FIDO U2F in 10 minutes - Dirk Balfanz
CIS 2015b FIDO U2F in 10 minutes - Dirk Balfanz
CloudIDSummit
 
20111204 web security_livshits_lecture01
20111204 web security_livshits_lecture0120111204 web security_livshits_lecture01
20111204 web security_livshits_lecture01Computer Science Club
 
Synapse india dotnet development web approch part 2
Synapse india dotnet development web approch part 2Synapse india dotnet development web approch part 2
Synapse india dotnet development web approch part 2
Synapseindiappsdevelopment
 
NoSQL oder: Freiheit ist nicht schmerzfrei - IT Tage
NoSQL oder: Freiheit ist nicht schmerzfrei - IT TageNoSQL oder: Freiheit ist nicht schmerzfrei - IT Tage
NoSQL oder: Freiheit ist nicht schmerzfrei - IT Tage
Alexander Hendorf
 
Web client security
Web client securityWeb client security
Web client security
Ziv Birer
 
Drupal 8 Authentication
Drupal 8 AuthenticationDrupal 8 Authentication
Drupal 8 Authentication
Juampy NR
 
JSON Web Tokens Will Improve Your Life
JSON Web Tokens Will Improve Your LifeJSON Web Tokens Will Improve Your Life
JSON Web Tokens Will Improve Your Life
John Anderson
 
InheritedWidget is your friend - GDG London (2018-08-08)
InheritedWidget is your friend - GDG London (2018-08-08)InheritedWidget is your friend - GDG London (2018-08-08)
InheritedWidget is your friend - GDG London (2018-08-08)
Andrea Bizzotto
 
Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1
Zianed Hou
 
Android query
Android queryAndroid query
Android query
Michal Pavlasek
 
HtmlElements – естественное расширение PageObject
HtmlElements – естественное расширение PageObjectHtmlElements – естественное расширение PageObject
HtmlElements – естественное расширение PageObject
SQALab
 
Building Your First Data Science Applicatino in MongoDB
Building Your First Data Science Applicatino in MongoDBBuilding Your First Data Science Applicatino in MongoDB
Building Your First Data Science Applicatino in MongoDB
MongoDB
 
1 24 - user data management
1 24 - user data management1 24 - user data management
1 24 - user data managementMongoDB
 

What's hot (20)

Knot.x: when Vert.x and RxJava meet
Knot.x: when Vert.x and RxJava meetKnot.x: when Vert.x and RxJava meet
Knot.x: when Vert.x and RxJava meet
 
Javascript 2
Javascript 2Javascript 2
Javascript 2
 
Api docs v4.0
Api docs v4.0Api docs v4.0
Api docs v4.0
 
Authentication
AuthenticationAuthentication
Authentication
 
Ajax chap 4
Ajax chap 4Ajax chap 4
Ajax chap 4
 
Blockly
BlocklyBlockly
Blockly
 
Ajax chap 5
Ajax chap 5Ajax chap 5
Ajax chap 5
 
CIS 2015b FIDO U2F in 10 minutes - Dirk Balfanz
CIS 2015b FIDO U2F in 10 minutes - Dirk BalfanzCIS 2015b FIDO U2F in 10 minutes - Dirk Balfanz
CIS 2015b FIDO U2F in 10 minutes - Dirk Balfanz
 
20111204 web security_livshits_lecture01
20111204 web security_livshits_lecture0120111204 web security_livshits_lecture01
20111204 web security_livshits_lecture01
 
Synapse india dotnet development web approch part 2
Synapse india dotnet development web approch part 2Synapse india dotnet development web approch part 2
Synapse india dotnet development web approch part 2
 
NoSQL oder: Freiheit ist nicht schmerzfrei - IT Tage
NoSQL oder: Freiheit ist nicht schmerzfrei - IT TageNoSQL oder: Freiheit ist nicht schmerzfrei - IT Tage
NoSQL oder: Freiheit ist nicht schmerzfrei - IT Tage
 
Web client security
Web client securityWeb client security
Web client security
 
Drupal 8 Authentication
Drupal 8 AuthenticationDrupal 8 Authentication
Drupal 8 Authentication
 
JSON Web Tokens Will Improve Your Life
JSON Web Tokens Will Improve Your LifeJSON Web Tokens Will Improve Your Life
JSON Web Tokens Will Improve Your Life
 
InheritedWidget is your friend - GDG London (2018-08-08)
InheritedWidget is your friend - GDG London (2018-08-08)InheritedWidget is your friend - GDG London (2018-08-08)
InheritedWidget is your friend - GDG London (2018-08-08)
 
Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1
 
Android query
Android queryAndroid query
Android query
 
HtmlElements – естественное расширение PageObject
HtmlElements – естественное расширение PageObjectHtmlElements – естественное расширение PageObject
HtmlElements – естественное расширение PageObject
 
Building Your First Data Science Applicatino in MongoDB
Building Your First Data Science Applicatino in MongoDBBuilding Your First Data Science Applicatino in MongoDB
Building Your First Data Science Applicatino in MongoDB
 
1 24 - user data management
1 24 - user data management1 24 - user data management
1 24 - user data management
 

Similar to Nk API - examples

InterCon 2016 - Segurança de identidade digital levando em consideração uma a...
InterCon 2016 - Segurança de identidade digital levando em consideração uma a...InterCon 2016 - Segurança de identidade digital levando em consideração uma a...
InterCon 2016 - Segurança de identidade digital levando em consideração uma a...
iMasters
 
iMasters Intercon 2016 - Identity within Microservices
iMasters Intercon 2016 - Identity within MicroservicesiMasters Intercon 2016 - Identity within Microservices
iMasters Intercon 2016 - Identity within Microservices
Erick Belluci Tedeschi
 
2016 pycontw web api authentication
2016 pycontw web api authentication 2016 pycontw web api authentication
2016 pycontw web api authentication
Micron Technology
 
The Big Picture and How to Get Started
The Big Picture and How to Get StartedThe Big Picture and How to Get Started
The Big Picture and How to Get Started
guest1af57e
 
Authentication and authorization in res tful infrastructures
Authentication and authorization in res tful infrastructuresAuthentication and authorization in res tful infrastructures
Authentication and authorization in res tful infrastructures
Corley S.r.l.
 
Box Authentication Types
Box Authentication TypesBox Authentication Types
Box Authentication Types
Jonathan LeBlanc
 
DevFest Kuala Lumpur - Implementing Google Analytics - 2011-09-29.ppt
DevFest Kuala Lumpur - Implementing Google Analytics - 2011-09-29.pptDevFest Kuala Lumpur - Implementing Google Analytics - 2011-09-29.ppt
DevFest Kuala Lumpur - Implementing Google Analytics - 2011-09-29.ppt
Vinoaj Vijeyakumaar
 
GTUG Philippines - Implementing Google Analytics - 2011-10-11
GTUG Philippines - Implementing Google Analytics - 2011-10-11GTUG Philippines - Implementing Google Analytics - 2011-10-11
GTUG Philippines - Implementing Google Analytics - 2011-10-11
Vinoaj Vijeyakumaar
 
How to implement golang jwt authentication and authorization
How to implement golang jwt authentication and authorizationHow to implement golang jwt authentication and authorization
How to implement golang jwt authentication and authorization
Katy Slemon
 
Esquema de pasos de ejecución IdM
Esquema de pasos de ejecución IdMEsquema de pasos de ejecución IdM
Esquema de pasos de ejecución IdM
Fernando Lopez Aguilar
 
The Open & Social Web - Kings of Code 2009
The Open & Social Web - Kings of Code 2009The Open & Social Web - Kings of Code 2009
The Open & Social Web - Kings of Code 2009
Chris Chabot
 
Node.js 與 google cloud storage
Node.js 與 google cloud storageNode.js 與 google cloud storage
Node.js 與 google cloud storage
onlinemad
 
[CB16] Esoteric Web Application Vulnerabilities by Andrés Riancho
[CB16] Esoteric Web Application Vulnerabilities by Andrés Riancho[CB16] Esoteric Web Application Vulnerabilities by Andrés Riancho
[CB16] Esoteric Web Application Vulnerabilities by Andrés Riancho
CODE BLUE
 
Drive chrome(headless) with puppeteer
Drive chrome(headless) with puppeteerDrive chrome(headless) with puppeteer
Drive chrome(headless) with puppeteer
VodqaBLR
 
IdM and AC
IdM and ACIdM and AC
Introduction to OAuth
Introduction to OAuthIntroduction to OAuth
Introduction to OAuthPaul Osman
 
SEA Open Hack - YAP
SEA Open Hack - YAPSEA Open Hack - YAP
SEA Open Hack - YAP
Jonathan LeBlanc
 
YAP / Open Mail Overview
YAP / Open Mail OverviewYAP / Open Mail Overview
YAP / Open Mail Overview
Jonathan LeBlanc
 
Adding Identity Management and Access Control to your Application, Authorization
Adding Identity Management and Access Control to your Application, AuthorizationAdding Identity Management and Access Control to your Application, Authorization
Adding Identity Management and Access Control to your Application, Authorization
Fernando Lopez Aguilar
 
OAuth 2.0
OAuth 2.0OAuth 2.0
OAuth 2.0
Uwe Friedrichsen
 

Similar to Nk API - examples (20)

InterCon 2016 - Segurança de identidade digital levando em consideração uma a...
InterCon 2016 - Segurança de identidade digital levando em consideração uma a...InterCon 2016 - Segurança de identidade digital levando em consideração uma a...
InterCon 2016 - Segurança de identidade digital levando em consideração uma a...
 
iMasters Intercon 2016 - Identity within Microservices
iMasters Intercon 2016 - Identity within MicroservicesiMasters Intercon 2016 - Identity within Microservices
iMasters Intercon 2016 - Identity within Microservices
 
2016 pycontw web api authentication
2016 pycontw web api authentication 2016 pycontw web api authentication
2016 pycontw web api authentication
 
The Big Picture and How to Get Started
The Big Picture and How to Get StartedThe Big Picture and How to Get Started
The Big Picture and How to Get Started
 
Authentication and authorization in res tful infrastructures
Authentication and authorization in res tful infrastructuresAuthentication and authorization in res tful infrastructures
Authentication and authorization in res tful infrastructures
 
Box Authentication Types
Box Authentication TypesBox Authentication Types
Box Authentication Types
 
DevFest Kuala Lumpur - Implementing Google Analytics - 2011-09-29.ppt
DevFest Kuala Lumpur - Implementing Google Analytics - 2011-09-29.pptDevFest Kuala Lumpur - Implementing Google Analytics - 2011-09-29.ppt
DevFest Kuala Lumpur - Implementing Google Analytics - 2011-09-29.ppt
 
GTUG Philippines - Implementing Google Analytics - 2011-10-11
GTUG Philippines - Implementing Google Analytics - 2011-10-11GTUG Philippines - Implementing Google Analytics - 2011-10-11
GTUG Philippines - Implementing Google Analytics - 2011-10-11
 
How to implement golang jwt authentication and authorization
How to implement golang jwt authentication and authorizationHow to implement golang jwt authentication and authorization
How to implement golang jwt authentication and authorization
 
Esquema de pasos de ejecución IdM
Esquema de pasos de ejecución IdMEsquema de pasos de ejecución IdM
Esquema de pasos de ejecución IdM
 
The Open & Social Web - Kings of Code 2009
The Open & Social Web - Kings of Code 2009The Open & Social Web - Kings of Code 2009
The Open & Social Web - Kings of Code 2009
 
Node.js 與 google cloud storage
Node.js 與 google cloud storageNode.js 與 google cloud storage
Node.js 與 google cloud storage
 
[CB16] Esoteric Web Application Vulnerabilities by Andrés Riancho
[CB16] Esoteric Web Application Vulnerabilities by Andrés Riancho[CB16] Esoteric Web Application Vulnerabilities by Andrés Riancho
[CB16] Esoteric Web Application Vulnerabilities by Andrés Riancho
 
Drive chrome(headless) with puppeteer
Drive chrome(headless) with puppeteerDrive chrome(headless) with puppeteer
Drive chrome(headless) with puppeteer
 
IdM and AC
IdM and ACIdM and AC
IdM and AC
 
Introduction to OAuth
Introduction to OAuthIntroduction to OAuth
Introduction to OAuth
 
SEA Open Hack - YAP
SEA Open Hack - YAPSEA Open Hack - YAP
SEA Open Hack - YAP
 
YAP / Open Mail Overview
YAP / Open Mail OverviewYAP / Open Mail Overview
YAP / Open Mail Overview
 
Adding Identity Management and Access Control to your Application, Authorization
Adding Identity Management and Access Control to your Application, AuthorizationAdding Identity Management and Access Control to your Application, Authorization
Adding Identity Management and Access Control to your Application, Authorization
 
OAuth 2.0
OAuth 2.0OAuth 2.0
OAuth 2.0
 

Recently uploaded

GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
ThomasParaiso2
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems S.M.S.A.
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
James Anderson
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
Neo4j
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
Peter Spielvogel
 

Recently uploaded (20)

GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
 

Nk API - examples

  • 1. NK API Examples Games and application Websites s (c) Jarosław Gomułka 2012
  • 3. REST API Documentation Created for mobile application and website solutions.
  • 4. REST API Authentication is based on OAuth standard. There are many libraries supporting this standard. Have a look here:: http://oauth.net/code/ First you need to get nk_token via /token/get request. POST https://opensocial.nk-net.pl/v09/token/get POST data: login=loginUseraNaNk&password=hasłoUseraNaNk [no cookies] Request Headers: <next slide>
  • 5. REST API - /token/get - headers Request Headers: Content-Type: application/x-www-form-urlencoded Content-Length: 28 Authorization: OAuth oauth_signature_method="HMAC-SHA1", oauth_consumer_key="customerKeyZPanelu", oauth_timestamp="1352376881", oauth_nonce="272317321310634", oauth_version="1.0", oauth_signature=" jVaVvVZcLZ1mMHzU3dzAmw3vxPE%3D" oauth_version="1.0", oauth_timestamp="1352376881" oauth_nonce="272317321310634" - must be unique, at least 15 characters oauth_signature_method="HMAC-SHA1" - you must enter this value oauth_signature="jVaVvVZcLZ1mMHzU3dzAmw3vxPE%3D" - it needs to be calculated:) oauth_signature obliczamy poprzez base64_encode(HMAC-SHA1(oauth_base_string, <secret from developer panel>&)); If everything goes correctly, we will get the answer: nk_token=jakiśDziwnyNapisWBase64
  • 6. REST API - base string Example of value POST&http%3A%2F%2Fjava1.omega.nknet%3A2080%2Fv09%2Ftoken%2Fget&login% 3Dabcef%26oauth_consumer_key%3DjakisCustomerKey%26oauth_nonce%3D273217097465315% 26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1352377781%26oauth_version%3D1. 0%26password%3DjakiśPassword First part POST - as we were sending POST request Second part is URL without query parameters, encoded via urldecode function Third part are all sorted and concatenated parameters . Remember to sign the request content (when it makes sens - check: question reported to NKsupport). All requests need to be signed with this mechanism.
  • 7. REST API - @me, @self, @all Many endpoint specifications show strange elements like: @me, @self, @all. @me - user currently logged in @self, @friends, @all - indicates who can check the object on which the action is done
  • 8. Download user data GET http://opensocial.nk-net.pl/v09/social/rest/people/person.602916f34c2ee73d/@self? nk_token=pynHhd5gLOetEOL3HtkFLwAUZ-4jHwMb6yda8Dkk-ratXkexcYcJhjWliEusR_QGTpBLvl1Rto51k8- s24l9O9wFKaqQ9mvNDMKSU90Gp2f [no cookies] Request Headers: Authorization: OAuth oauth_signature_method="HMAC-SHA1", oauth_consumer_key="psiloctest1", oauth_timestamp=" 1352379660", oauth_nonce="275096425520387", oauth_version="1.0", oauth_signature="GeGBNljcPKIQPeLXgCtYX8zgVCY%3D" Connection: keep-alive Response: {"entry":{"isOwner":true,"isViewer":true,"id":"person.602916f34c2ee73d","thumbnailUrl":"http://s.m.nk. pl/img/avatar/avatar_default_female","name":{"formatted":"du1 mnk (u003cscriptu003ealert(1);u003c/scriptu003e)"," additionalName":"mnk (u003cscriptu003ealert(1);u003c/scriptu003e)","familyName":"mnk","givenName":"du1"},"photos": [{"value":"http://s.m.nk.pl/img/avatar/avatar_default_female","type":"thumbnail"}],"displayName":"du1 mnk (u003cscriptu003ealert(1);u003c/scriptu003e)"}}
  • 9. Adding shout POST https://opensocial.nk-net.pl/v09/social/rest/activities/@me/@self/app.sledzik?nk_token=pynHhd5gLOetEOL3HtkFLwAUZ- 4jHwMb6yda8Dkk-ratXkexcYcJhjWliEusR_QGTpBLvl1Rto51k8-s24l9O9wFKaqQ9mvNDMKSU90Gp2f POST data: {"title":"Some short text 123"} [no cookies] Request Headers: Content-Type: application/json Content-Length: 31 Authorization: OAuth oauth_body_hash="%2FIyGusEZ4w8%2BuI9gOr5emjQha9E%3D", oauth_signature_method="HMAC-SHA1", oauth_consumer_key="psiloctest1", oauth_timestamp="1352379705", oauth_nonce="275140932345687", oauth_version="1.0", oauth_signature="Rhv3r9eVAx66MDlcTepvQ7bPkuw%3D" Connection: close Response 200: {"entry":{}}
  • 10. When something is not working... We suggest the following steps: ● Check the error code. You can find many useful information there. ● Check logs - http://developers.nk.pl/applications-logs/ ● Catch the request with tcpdump or extract it with netcat. Then check if data is sent according to the specification ● Describe the problem in details in NK support
  • 11. API JS In this part we will show you how to create Opensocial applications. Shindig is used as application container which implements OpenSocial standard Shindig is responsible for: ● application rendering ● proxy request creation ● data cache ● RPC/REST requests We are supporting OpenSociala ver 0.9. List of all functionalities we are supporting is accessible in our documentation.
  • 12. API JS Aplikacje definiujemy przez pojedynczy plik gadget.xml Adres do tego pliku podajemy w panelu zarządzania aplikacjami i stronami.
  • 13. Preparation of development environment 1. You create application in https://developers.nk.pl/developers 2. Set debug mode (data cache is disabled) 3. You add tester ID on application tester list 4. Enter your application: http://nk.pl/#applications_test/xyz (the exact link is in application settings) For the beginning we can put the following, classic example code as gadget.xml: <?xml version="1.0" encoding="UTF-8" ?> <Module> <ModulePrefs/> <Content type="html" view="canvas"> <![CDATA[ Hello World ]]> </Content> </Module>
  • 14. Examples: Following examples are available under this URL: https://github.com/jaaro/various/tree/master/nk 1. ROT13 2. Information about the user 3. Informacje about friends 4. Embedding flash 5. Swfobject 6. Hamster fall 7. Adding shout on NK We suggest to test other JS API functionalities in this application: nkda.
  • 15. Payments- JS code function handlePaymentResponse(dataItem) { if (dataItem.hadError()) { alert('got an error'); } else { var orderId = dataItem.getData().getField(opensocial.Payment.Field.ORDER_ID); alert('payment request accepted, orderId: ' + orderId); } } function makePayment() { var params = {}; params[opensocial.Payment.Field.AMOUNT] = 5; params[opensocial.Payment.Field.MESSAGE] = "large sword"; params[opensocial.Payment.Field.PARAMETERS] = "some_app_specific_params"; var payment = opensocial.newPayment(params); opensocial.requestPayment(payment, handlePaymentResponse); }
  • 16. Payments Enter the right value in "Payment Callback URL" field (Administration panel): When transaction is completed, nk is sending under this URL the following request: POST /some/url HTTP/1.1 Host: gamehost.com Content-Type: application/x-www-form-urlencoded amount=5&appId=app.1&containerDomain=nk.pl&message=large%20sword&oauth_consumer_key=key& oauth_nonce=252b9d59381dd803dcf156663d1375d9&oauth_signature=%2F7%2BGAbB0DDYNZwC%2BsSACe1O5Kpw%3D& oauth_signature_method=HMAC-SHA1&oauth_timestamp=1273755263&oauth_version=1.0& orderId=32787067d4de27d7fb97d816723d5c75bb9fd337&parameters=some_app_specific_params& paymentType=payment&viewerId=person.abc
  • 17. Payments Application must confirm the payment has been received by generating the following response: HTTP/1.1 200 OK Content-Type: application/json {"orderId":"32787067d4de27d7fb97d816723d5c75bb9fd337","responseCode":"ok","responseMessage":"all ok","signature":"7e7455aac4a1be3186185e5bd056791adf01818c"} If the confirmation (response) is not ok, NK server will send request every minute for next 24hours or till we get the correct response. If you want to test payments, send e-mail to egbtest@nasza-klasa.pl with request for specified amount of NK currency (EGB) , you NK profile ID and name of the application you are testing.
  • 18. Inviting friends to the application: function handleInviteFriendResponse(responseItem) { if (responseItem.hadError()) { // handle error } else { alert(responseItem.getData() + ' invited friend(s)'); } } function invite() { var msg = 'Join me !'; var paramsObject = new Object(); nk.requestInviteFriends(msg, paramsObject, handleInviteFriendResponse); } invite();
  • 19. Check if user is already member of the application group. function response(data) { if (data.hadError()) { // handle error } else { var result = data.get("isInGroup").getData(); if (result) { output("User is in application's group"); } else { output("User is NOT in application's group"); } } }; function request() { var req = opensocial.newDataRequest(); req.add(nk.groups.newIsUserInAppGroupRequest(), "isInGroup"); req.send(response); }; request();
  • 20. Adding user to application group: function callback(responseItem) { if (responseItem.hadError()) { // handle error } else { console.log(responseItem); } } function invite() { nk.groups.requestAddUserToAppGroup(callback); } invite();
  • 21. Adding picture: function uploadPhotoHandler(resp) { if (resp.hadError()) { // handle error } } function uploadPhoto() { nk.photos.requestUploadAppPhoto("Photo added from Dev App", null, uploadPhotoHandler); } uploadPhoto();
  • 22. How many user have installed the application? function response(data) { if (data.get("amount").hadError()) { // handle error } else { alert(data.get("amount").getData()); } }; function request() { var req = opensocial.newDataRequest(); req.add(nk.newGetAmountOfUsersRequest(), "amount"); req.send(response); }; request();
  • 23. Adding shout: function onActivityPosted(data) { if (data.hadError()) { alert("There was a problem: " + data.getErrorMessage()); } else { output("The activity was posted successfully."); } }; function postActivity(title) { var data = {}; data[opensocial.Activity.Field.TITLE] = title; var activity = opensocial.newActivity(data); opensocial.requestCreateActivity( activity, opensocial.CreateActivityPriority.HIGH, onActivityPosted ); }; postActivity("This is a sample activity");
  • 24. Communication between users - message function response(data) { if (data.hadError()) { alert("There was a problem: " + data.getErrorMessage()); } else { output("The message was sent."); } }; function request() { var iconUrl = new opensocial.Url({"type" : "icon", "address" : "http://www.example.org/icons/notifyIcon.jpg"}); var msgParams = { "title" : "Title of notification", "urls" : new Array(iconUrl), // image used in notification "type" : "notification", // only notification is currently supported }; var msg = opensocial.newMessage("Body of notification", msgParams); opensocial.requestSendMessage(["person.XXX"], msg, response); }; request();
  • 25. JS API You can find many other examples in our dokumentation together with detailed features specification. http://developers.nk.pl/documentation/nk-api/opensocial-js-api/
  • 26. Some interesting features: Please note, that even if we support some features, they may not be operated in the same way as in original OpenSocial specification, for example: Activity. List of supported paramenters is here: http://developers.nk.pl/documentation/nk-api/opensocial-js-api/ Interesting features: gadgets.log / gadgets.warn / gadgets.error gadgets.json.parse / gadgets.json.stringify gadgets.window.adjustHeight gadgets.io.makeRequest / osapi.http.get