MySpace Developer Platform

A Place For Developers

Welcome Developers!

in

Welcome!

in

oAuth / PHP / External App 101 ?

Last post 09-01-2008 7:40 AM by Teenytank. 8 replies.
Page 1 of 1 (9 items)
Sort Posts: Previous Next
  • 05-15-2008 10:30 PM

    • Sarah
    • Top 100 Contributor
    • Joined on 05-08-2008
    • Posts 32

    oAuth / PHP / External App 101 ?

    I am so new, I shouldn't even be writing apps - but the bad news is... I am.

    I have an external PHP app.

    If I set the canvas page to be an iframe, which loads the index page of my PHP app - my application works fine.  

    Except it operates as if the user wasn't 'logged in'...

    "Aha - so I need to authenticate this somehow...."

    I am sure these threads will help those more technical than I:

    http://developer.myspace.com/Community/forums/p/1145/5032.aspx#5032
    http://developer.myspace.com/Community/forums/p/1087/4894.aspx#4894
    http://developer.myspace.com/Community/forums/t/157.aspx?PageIndex=1

    Unfortunately, I have no idea what anyone is talking about... I code by example... & there are so many examples and not one of them makes much sense.

    2 days and about 23 hours reading I am still none the clearer. 

    Is there not just a simple chunk of code I can throw at the top of my PHP index page that will say:
    "Oh, I've just received a request from MySpace - everything seems to be okay here, so I'll render myself, and carry on as if this user was logged in"?

    Would I need to code a container to send this information to the iFrame (and if so, why is there the option to have an iFrame as a canvas page?)

    This application makes no other requests for openSocial data at all - so other than the one off verification I need that the user is logged in to MySpace, it pretty much stands alone.

    Any documents in English, not Geekese, any working chunks of code with babysteps and explanations anything - much appreciated.

    I have played around with one or two things without knowing what I'm doing.

    If I try this...


    <pre>


       $security_key="XXXXXXXXXXXXX"; //my myspace secret key    
        $remote_signature = $_GET['oauth_signature'];
        $url = strtolower('http://xxxxx.com/myspace_auth.php');
        unset($_GET['oauth_signature']);
        ksort($_GET);
        $base_string = 'GET&'.
                       urlencode($url).'&'.
                       urlencode(http_build_query($_GET));
        $secret = 'security_key'.'&';
        $local_signature = base64_encode(hash_hmac("sha1", $base_string, $secret, TRUE));
        
        if ($remote_signature == $local_signature) {
            $fh = fopen("output.txt", 'w');
            fwrite($fh, "Authenticationed!\n");
            fclose($fh);
        } else {
            $fh = fopen("output.txt", 'w');
            fwrite($fh, "Authentication FAILED!\n");
            fwrite($fh, "Remote Sig: ".$remote_signature."\n");
            fwrite($fh, "Local Sig: ".$local_signature."\n");
            fclose($fh);
        }

    </pre>

    I always get 'authentication failed' and no remote sig returned.

    There are some excelent and detailed posts out there, but they always seem to lose me by becoming far too 'coder to coder' instead of 'teacher to baby'.

     Thanks for your time folks.

  • 05-16-2008 8:46 AM In reply to

    Re: oAuth / PHP / External App 101 ?

    This explains the basic principles but frankly if you are developing apps you do need to know how to program

    http://developer.myspace.com/Community/forums/t/1832.aspx

     

  • 05-16-2008 10:43 AM In reply to

    • Sarah
    • Top 100 Contributor
    • Joined on 05-08-2008
    • Posts 32

    Re: oAuth / PHP / External App 101 ?

    Thanks for the response, I know how to program - I just don't get the jargon surrounding it.. surely this is code people will be using over & over in their applications, so I don't understand why there isn't a definite answer.

    And as MySpace seem to be stressing that anyone with a bit of basic coding knowledge can build an app, I don't get why I - with 16 years 'basic coding knowledge' - can't 'get it'

    I will work through the below & let you know if I get anywhere - first glance reactions... 

    To do a request to myspace you need to use the oAUTH signature method. (ok)

    Requests are simple http GET’s or POST’s to the myspace servers to get information about a user or other data. (ok)    There are PHP libraries for this (where?)

    but since we don’t use PHP (I do)

    we had to figure this out on our own. (uh huh)

     

    This is what needs to be done in a generic way that should be translatable to any language. 

    This example gets the friends of a user.

    You have to generate a signature string first.

     The string to generate the signature on is made like this all concatenated togetherGET& plus the request URL urlencoded (ie:  http://api.myspace.com/v1/users/#####/friends) (where the ##### are the userid of the person you are getting the friends for) append an & string together the actual request which has  

    oauth_consumer_key=yourkey (yep)

    oauth_nonce=noncevalue (what the hell is a noncevalue?)

    &oauth_signature_method=HMAC-SHA1 (ok)

     &oauth_timestamp=atimestamp (ok....)

    &oauth_token=&oauth_version=1.0(note the oauth_token has no value but must be there, The order of the parameters matters, they need to be in alphabetical order. )  (ok)

     Then you URL encode the above and append it to your string you are building up. (ok)

    So your base string might look something like this (note what is and isn't url encoded ie its, GET&urlencodedhostrequest&urlencodedrequeststring) 

    GET&http%3A%2F%2Fapi.myspace.com%2Fv1%2Fusers%2F6549232%2Ffriends&oauth_consumer_key%3Dhttp%253A%252F%252Fwww.myspace.com%252F354364031%26oauth_nonce%3D1206638068.1040%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1206638068%26oauth_token%3D%26oauth_version%3D1.0 

     Then you need to hash it with HMAC-SHA1 and base64 encode it so the text value would be your string and the key (and this is important) is your consumer secret with an & appended to the end of it. (I get what you want me to do, but how do I do that?!)

    (we couldn't find a command line tool that would do an HMAC-SHA1 and base64 encode so we wrote one in C.  Contact me if you would like it)

     Then you urlencode the result of that and that is your signature.   (right, if I get that far)

    Then you have to form your query string which has all the same stuff you built up in your request plus the signature so like this 

    oauth_consumer_key=yourkey&oauth_nonce=noncevalue&oauth_signature_method=HMAC-SHA1&oauth_signature=yourgensighere&oauth_timestamp=atimestamp&oauth_token=&oauth_version=1.0 So your whole get request might look something like this

    http://api.myspace.com/v1/users/#####/friends?oauth_consumer_key=http%3A%2F%2Fwww.myspace.com%2F354364031&oauth_nonce=633421365057774247&oauth_signature=GASxMIk34F62SsLY4j6N8oMNrLA%3D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1206539705&oauth_token=&oauth_version=1.0 

    That request is then made by your server code and the result back is an XML structure that you can then parse to get the information you need

     

     

  • 05-16-2008 11:34 AM In reply to

    • Detour
    • Not Ranked
    • Joined on 05-13-2008
    • Posts 2

    Re: oAuth / PHP / External App 101 ?

    Perhaps I can help somewhat, I've been trying to dig in to this. Despite that I still seem to keep hitting dead-ends and blank walls I'd like to share what I have figured out so far in the hopes that we can help each other.

    Libraries: http://developer.myspace.com/community/libs/libraryintro.aspx
    HMAC SHA1 code in PHP (as best as I understand it from:http://developer.myspace.com/community/RestfulAPIs/intro.aspx )

     $httpMethod = 'GET';
     $url = urlencode('http://someurl/'); // not really clear what exactly is supposed to go here yet
     $secret = '12345';
    	
     $baseStr = $httpMethod.'&'.$url;
     $sig = urlencode(base64_encode(mhash(MHASH_SHA1, $baseStr, $secret)));
    
    There's also an implementation that doesn't use mhash here: http://laughingmeme.org/code/hmacsha1.php.txt

    I'm still lost on how to generate the auth token to pass for authorization requests, nothing i've tried ever works. Hopefully you're getting somewhere. Good luck...

  • 05-16-2008 1:22 PM In reply to

    Re: oAuth / PHP / External App 101 ?

    A nonce value is an ever increasing number that doesn't repeat by definition.  Use the time in milliseconds from Jan 1 1970 and as long as you don't do more than 1 request per millisecond you should be fine.

     

  • 05-16-2008 5:42 PM In reply to

    • Sarah
    • Top 100 Contributor
    • Joined on 05-08-2008
    • Posts 32

    Re: oAuth / PHP / External App 101 ?

    Thanks Russ, I am pretty sure I read that somewhere further down your thread at some point during another 14 hours of reading today...  

    I have now given in on all & any code listed here, and I'm working on modifying the GenusApis PHP5 library with - surprisingly - a bit of success... will keep everyone posted.

  • 05-20-2008 4:42 PM In reply to

    • Sarah
    • Top 100 Contributor
    • Joined on 05-08-2008
    • Posts 32

    Dummies Guide to Applications

    I had a feeling when I wrote this that I'd end up writing the answer myself...
    So this is my guide to making an application for people who aren't coders....

    I am giving an example in PHP & using SMARTY TEMPLATING & FLASH.... but I am sure you could try other things.

    THE VERY BASICS

    1.  There are three surfaces:
      • The profile surface, which appears on the user's profile.
      • The home surface, which appears on the user's main MySpace login page (the page where they check their mail, etc).
      • The canvas surface, which is where your main application will launch.

    2. There are two kinds of people you may be addressing
      • The owner: "Hello Ownername, thank you for installing this application."
      • The viewer: "Hello Viewername, Ownername has installed this application, why don't you?"

    3. It is actually very, very easy once you get the basics worked out.

    GETTING STARTED

    Most of you will have done this, if you're reading this - if not

    OPEN A MYSPACE DEVELOPER ACCOUNT

    Go to developer.myspace.com
    Click on My Apps
    Fill in the form.
    Wait for approval.

    If you don't have a developer account yet, you don't have to stop your development whilst you're waiting for approval!  
    Get designing your pages & get an idea of how your application is going to flow.

    Then once you have a developer account it's time to start cracking....


    ENTER THE BASICS OF YOUR APPLICATION

    Like.. give it a name & stuff.
    Don't worry about the Callback URLs and stuff.
    MAKE A NOTE of your Application URI & Secret Keys though, because you are going to need them!

    DOING THE CODE STUFF

    SET UP YOUR SERVER TO USE THE RIGHT PHP STUFF

    First things first.  Get the official MySpace PHP Library.
    http://x.myspace.com/libs/myspacel_php5_20080317.zip

    Edit the file config.php to point to your Application URI and use your Secret Key (from the app info page)
    Upload the contents of the myspace subdirectory to your PHP directory and also upload config.php to the same location.

    Your PHP folder is probably located outside of your website root folder.

    For example - mine is /usr/myusrname/php
    But my website files are uploaded to /usr/myusrname/public_html

    You'll also need to install the PEAR package, HTTP_Request.

    If you are lucky, your website hosting provider may have set this up in CPANEL for you - go and check. It may be under Software/Services -> PHP Pear Packages.  If so, just search for HTTP_Request and click install.  If not, you'll need to download the package from PEAR.com - http://pear.php.net/ - and again upload to your PHP directory.

    ENTER THE MYSPACE CODE THAT POINTS TO YOUR SERVER & RUNS THE APPLICATION

    I got this chunk of code from
    http://developer.myspace.com/Community/forums/p/402/1561.aspx#1561


    & modified it slightly.  

    You can use it for all three views - you just need to change the width and height of the div in the style information to match.  You enter this in the box under edit app source.

    <style type="text/css">

    //CHANGE THE WIDTH AND HEIGHT TO MATCH THE SURFACE YOU ARE USING THE CHUNK OF CODE FOR

    .profile{

        width: 800x;

        height: 1600px;

        

    //YOU CAN ADD IN ANY OTHER STYLE INFO YOU WANT HERE





    }</style>



    //THIS IS THE DIV THAT WILL BE REPLACED WITH YOUR APPLICATION - I PUT A LOADER IMAGE THERE.



    <div id="output" class="profile"><img src="YOURLOADERIMAGE.GIF"></div>

    <script type="text/javascript">





    //THIS POINTS TO YOUR PHP SCRIPT

    var server_url="http://YOURDOMAIN.com/YOURPHPSCRIPT.php";





    function init() {



    //THIS CODE GETS A BUNCH OF INFO FROM MYSPACE

        var params = {};

        params[opensocial.ContentRequestParameters.METHOD] = opensocial.ContentRequestParameters.MethodType.GET;

        params[opensocial.ContentRequestParameters.CONTENT_TYPE] = opensocial.ContentRequestParameters.ContentType.HTML;

        params[opensocial.ContentRequestParameters.AUTHENTICATION] = opensocial.ContentRequestParameters.AuthenticationType.SIGNED;

        opensocial.Container.get().makeRequest(server_url, pageloadCallback, params);

    }





    //ONCE THAT INFO IS RECEIVED IT LOADS YOUR OWN PAGE INTO THE DIV WE MADE EARLIER

    function pageloadCallback(response) {              

        document.getElementById('output').innerHTML = response;

    }





    //THIS LIL FUNCTION BELOW PROVIDES A LINK TO YOUR CANVAS PAGE FROM OTHER SURFACES



    function gocanvas() {

    var surfaces = gadgets.views.getSupportedViews();

    var canvasSurface = surfaces['canvas'];

    gadgets.views.requestNavigateTo(canvasSurface,null);

    }





    //THIS INITIALISES THE WHOLE THING OR SOMETHING



    init();

    </script>


    MAKE YOUR "PHP CONTROL FILES"

    I'm using Smarty - so my PHP control files just send a bunch of info to the templating system - I have three control files for each surface (home.php / profile.php and canvas.php) - when I get time I'll merge them into one and have it redirect according to a paramater or something.

    If you're not using Smarty, it's still really easy to get what you need. Anyway, this is how my control file for my canvas looks.



    <?php



    //THIS BIT SETS UP MY SMARTY - YOU WILL NOT NEED THIS IF YOU ARE NOT USING SMARTY

    require('/usr/myusrname/public_html/include/smarty/libs/Smarty.class.php');



    $smarty = new Smarty();

    $smarty->compile_dir = '../compile';





    //CHANGE THE BIT BELOW TO POINT TO THE ABSOLOOOOOOT LOCATION OF MYSPACEAPI

     

      require_once('/usr/myusrname/php/myspace/MySpaceAPI.php');

      $key = 'YOURKEY';

      $secret = 'YOURSECRET';

      $myspace = new MySpaceAPI($key,$secret);

     

     

    //THIS GETS THE ID OF THE VIEWER  

      $user = $_GET["opensocial_viewer_id"];



    //THIS TELL SMARTY TO ASSIGN THE STRING USERID TO WHATEVER THE ID OF THE VIEWER WAS

      $smarty->assign('userid', $user);



    //NOW WE GET SOME INFO - THIS CALLS THE FUNCTION GET USER FROM MYSPACE API & ASSIGNS THE RESULTS TO AN ARRAY CALLED RESULT

      $result = $myspace->get_user($user);



    //LOTS OF SMARTY ASSIGNS _ GET THE RIGHT PART OF THE ARRAY FROM RESULT & GIVE IT A SMARTY STRING



      $smarty->assign('imageurl', $result['imageuri']);

      $smarty->assign('profileurl', $result['weburi']);

      $smarty->assign('name', $result['displayname']);

      $smarty->assign('name', $result['displayname']);

      $smarty->assign('usertype', $result['usertype']);





    //AN EXAMPLE OF BREAKING UP AN ARRAY EVEN FURTHER

      $myArray = $myspace->get_interests($user);

      $music= $myArray['interests']['music'];

      $bands = explode(',',$music);

      $bandlist = array_rand($bands, 5);

      $smarty->assign('bandlist', $bands[$bandlist[3]]);

     

    //OK I GOT ALL THE INFO I NEED RENDER A PAGE PLZZZZZZZZZZZZ SOI SOI SOI SOI SOI  

      $smarty->display('canvas.tpl');

    ?>

    AND FINALLY - FUN WITH SMARTY

    So we just passed a ton of info into canvas.tpl :)

    If you're using Smarty you can do stuff like:

    {if $usertype == "Band"}

    Hello - I see you  are in a band called {$name} - are you any good?

    {else}

    Hello {$name} I see you are a fan of {$bandlist} well I think they suck.

    {/if}

    You can also pass this info into Flash using Flashvars...
    <PARAM NAME=FlashVars VALUE="name={$name}&band={$bandlist}&usertype={$usertype}">

    Then you can call the info into dynamic text fields using:

    myTextField_txt.htmlText = "<font face='Arial' size='14' color='#FFFFFF'>thar thar, dun worry<b>"+name+"</b>its all gun b k</font>";


    Oh yeah, remember that gocanvas() function earlier?
    Well, you can use GetURL on a button in Flash on the homepage app & direct the user to the canvas page.


    So that's it - my DUMMIES GUIDE TO APPS - for dummies like me. Hope it helps someone somewhere.

  • 07-24-2008 7:01 PM In reply to

    • Clint
    • Not Ranked
    • Joined on 07-24-2008
    • Posts 1

    Re: Dummies Guide to Applications

    Sarah, you rock.  I would ask you to marry me if I weren't already married.

    You just saved me maybe 3 or 4 days of figuring out the basics of this stuff.

    Thank you! 

     

  • 09-01-2008 7:40 AM In reply to

    Re: Dummies Guide to Applications

     Sarah,

      I gotta tell you... I've beeon working on this thing here for a few weeks in C#, but with your guide, I am going over to php.  It took me less than 2 hours to get wamp, pear and smarty all working together, and with that guide, it took mo only another 30 mins or so to get something live.  

      That was an excellent display of how things work, and I appreciate the work and the sharing you did there.  You are the best!

    DenDude

     

Page 1 of 1 (9 items)