Skip to content
This repository has been archived by the owner on Oct 10, 2020. It is now read-only.

Oauth 2

mptre edited this page May 9, 2012 · 1 revision

Getting started

This is a basic example of how to implement the SoundCloud API wrapper in your PHP application. Remember this is just a quick one to get you started. All kind of error handling and validation of user generated data has been stripped out for sake of simplicity.

Make sure to check out the demo application. The application includes code for the authentication flow, refresh token flow and storing user credentials.

1. Register your application

Head over to SoundCloud and register your new OAuth application in order to maintain your client id and secret. These two strings will identify your application. Make sure to define a valid redirect URI aswell.

2. Download the PHP wrapper

Simply clone the wrapper using Git. If you're not familiar with git you could download the whole library directly from GitHub and place the files in your desired location.

$ git clone git://github.com/mptre/php-soundcloud.git

3. Create a new Soundcloud object

Make sure the Services_Soundcloud class is included in your application. The constructor takes four parameters. At this step you'll only need the first three. See the source code for further reference.

$soundcloud = new Services_Soundcloud('yourClientId', 'yourClientSecret', 'yourRedirectUri');

4. Get authorize URL

Generate a URL used for authorization and prompt your user to visit your newly generated URL.

$authorizeUrl = $soundcloud->getAuthorizeUrl();

And somewhere in your view.

<a href="<?php echo $authorizeUrl; ?>">Connect with SoundCloud</a>

5. Get access token

The user will be redirected back to your already defined redirect URI. A code will be included in the URL as a query string parameter. Obtain that code in order to request a access token.

try {
    $accessToken = $soundcloud->accessToken($_GET['code']);
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
    exit($e->getMessage());
}

The variable accessToken will contain all necessary credentials in order to perform requests to SoundCloud on behalf of the user.

6. Request protected resources

Here's an example requesting the authenticated user's account data. Note that the default response format is set to JSON.

try {
    $me = json_decode($soundcloud->get('me'), true);
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
    exit($e->getMessage());
}