Nk API - examples
Upcoming SlideShare
Loading in...5
×
 

Nk API - examples

on

  • 4,345 views

 

Statistics

Views

Total Views
4,345
Views on SlideShare
1,249
Embed Views
3,096

Actions

Likes
0
Downloads
1
Comments
0

5 Embeds 3,096

http://developers.nk.pl 3089
http://staging.developers.nk.pl 3
http://translate.googleusercontent.com 2
https://www.google.ca 1
https://www.google.com 1

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Nk API - examples Nk API - examples Presentation Transcript

  • NK API ExamplesGames andapplication Websites s (c) Jarosław Gomułka 2012
  • API types:● REST● JS
  • REST APIDocumentationCreated for mobile application and website solutions.
  • REST APIAuthentication is based on OAuth standard. There are many libraries supporting thisstandard. 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/getPOST data:login=loginUseraNaNk&password=hasłoUseraNaNk[no cookies]Request Headers:<next slide>
  • REST API - /token/get - headersRequest Headers:Content-Type: application/x-www-form-urlencodedContent-Length: 28Authorization: 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 charactersoauth_signature_method="HMAC-SHA1" - you must enter this valueoauth_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 stringExample 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śPasswordFirst part POST - as we were sending POST requestSecond part is URL without query parameters, encoded via urldecode functionThird 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, @allMany 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 dataGET 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-aliveResponse:{"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 shoutPOST https://opensocial.nk-net.pl/v09/social/rest/activities/@me/@self/app.sledzik?nk_token=pynHhd5gLOetEOL3HtkFLwAUZ-4jHwMb6yda8Dkk-ratXkexcYcJhjWliEusR_QGTpBLvl1Rto51k8-s24l9O9wFKaqQ9mvNDMKSU90Gp2fPOST data:{"title":"Some short text 123"}[no cookies]Request Headers:Content-Type: application/jsonContent-Length: 31Authorization: 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: closeResponse 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 JSIn this part we will show you how to create Opensocial applications.Shindig is used as application container which implements OpenSocial standardShindig is responsible for: ● application rendering ● proxy request creation ● data cache ● RPC/REST requestsWe are supporting OpenSociala ver 0.9.List of all functionalities we are supportingis accessible in our documentation.
  • API JSAplikacje definiujemy przez pojedynczy plik gadget.xmlAdres do tego pliku podajemy w panelu zarządzania aplikacjami i stronami.
  • Preparation of development environment1. You create application in https://developers.nk.pl/developers2. Set debug mode (data cache is disabled)3. You add tester ID on application tester list4. 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/nk1. ROT132. Information about the user3. Informacje about friends4. Embedding flash5. Swfobject6. Hamster fall7. Adding shout on NKWe suggest to test other JS API functionalities in this application: nkda.
  • Payments- JS codefunction 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);}
  • PaymentsEnter 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.1Host: gamehost.comContent-Type: application/x-www-form-urlencodedamount=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
  • PaymentsApplication must confirm the payment has been received by generating the followingresponse:HTTP/1.1 200 OKContent-Type: application/json{"orderId":"32787067d4de27d7fb97d816723d5c75bb9fd337","responseCode":"ok","responseMessage":"allok","signature":"7e7455aac4a1be3186185e5bd056791adf01818c"}If the confirmation (response) is not ok, NK server will send request every minute for next 24hours or till we getthe correct response.If you want to test payments, send e-mail to egbtest@nasza-klasa.pl with request for specified amount of NKcurrency (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 theapplication group.function response(data) {if (data.hadError()) { // handle error} else { var result = data.get("isInGroup").getData(); if (result) { output("User is in applications group"); } else { output("User is NOT in applications 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 theapplication?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 - messagefunction 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 APIYou can find many other examples in our dokumentationtogether 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 originalOpenSocial 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.errorgadgets.json.parse / gadgets.json.stringifygadgets.window.adjustHeightgadgets.io.makeRequest / osapi.http.get