User:Saeros Linden/Reg API Examples

From Second Life Wiki
Revision as of 13:11, 6 June 2016 by Saeros Linden (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search
NOTE: This is an official Second Life API provided and documented by Linden Lab. Its use is subject to the API Terms of Use.

The following examples illustrate using the Reg API to register a new user with a specified Second Life first name and last name. The example code first checks to determine the availability of the selected first and last name, and either registers the user or returns an error message if the name is already taken.


LLSD library downloads

To use a library:

  1. Remove the -lib suffix from the file name.
  2. Put the file in the same directory as the application code, such as the examples below.

NOTE: The PHP scripts only work with PHP4.

An externally developed Java implementation of LLSD and RegAPI is available at http://mimuve.cs.st-andrews.ac.uk/llsd-java/src/llsd-java-0.2.1.zip . Code written by Xugu Madison, copyright held by University of St Andrews, and made available under the BSD license. Tested with Java 1.5.

Question: what version of each language is required?

Example code

Ruby

This ruby example shows how to use the Registration API.

require 'llsd'

  1. 0 - get capability urls
  2. 1 - get error codes
  3. 2 - get the available last names
  4. 3 - check to see of a username + last name combo is taken
  5. 4 - register the user with this username + last name combo

get_capabilities_url = "https://cap.secondlife.com/get_reg_capabilities"

  1. grab command line args

if ARGV.length == 3

 first_name = ARGV[0]
 last_name = ARGV[1]
 password = ARGV[2]

else

 puts "Please pass in your second life first name, last name, and password as arguments."
 puts "For example: ruby registration_api.rb joe linden 1234"
 
 exit

end

  1. 0 - Get Capability URLS ##############################################

puts "========== Getting capabilities ===========\n"

post_body = "first_name=#{first_name}&last_name=#{last_name}&password=#{password}"

  1. create a url-encoded string to POST

response_xml = LLSD.post_urlencoded_data get_capabilities_url, post_body

  1. POST the capability url to get capabilities

puts "xml response:" # Print out response xml puts response_xml

puts "\n"

capability_urls = LLSD.parse(response_xml) # Parse the xml

capability_urls.each { |k,v| puts "#{k} => #{v}"} # print out capabilities

  1. 1 - Print out error codes ##############################################

puts "\n\n========== Get Error Codes Example ===========\n"

if capability_urls['get_error_codes']

 response_xml = LLSD.http_raw capability_urls['get_error_codes'] 
 # GET the capability url for getting error codes
 
 puts "xml response:" # Print out response xml
 puts response_xml
 
 error_codes = LLSD.parse(response_xml) # Parse the xml
 error_codes.each {|error| puts "#{error[0]} => #{error[1]}"} 
 # print out all error codes

else

 puts "Get_error_codes capability not granted to #{first_name} #{last_name}.  Exiting Prematurely ..."

end

  1. 2 - Get Last Names Example ##############################################

puts "\n\n========== Get Last Names Example ===========\n" if capability_urls['get_last_names']

 response_xml = LLSD.http_raw capability_urls['get_last_names'] 
 # GET the capability url for getting last names and ids
 puts "xml response:" # Print out response xml
 puts response_xml
 
 last_names = LLSD.parse(response_xml) # Parse the xml
 last_names.each {|k,v| puts "#{k} => #{v}"} # print out last names
 
 
 # 3 - Check Name Example  ##############################################
 print "\n\n========== Check Name Example ===========\n"
 if capability_urls['check_name']
   random_username = 'tester' + Kernel.rand(10000).to_s # Generate a random username
   valid_last_name_id = last_names.keys.first # Get the first valid last name id
   params_hash = {"username" => random_username, "last_name_id" => valid_last_name_id } 
   # put it in a hash
   xml_to_post = LLSD.to_xml(params_hash) # convert it to llsd xml
   response_xml = LLSD.post_xml(capability_urls['check_name'], xml_to_post)
   puts "posted xml:" # Print out response xml
   puts xml_to_post
   puts "xml response:" # Print out response xml
   puts response_xml
   is_name_available = LLSD.parse(response_xml) # Parse the xml
   puts "Result (is name available?): #{is_name_available}" # Print the result
   
   # 4 - Create User Example  ##############################################
   puts "\n\n========== Create User Example ===========\n"
   if is_name_available and capability_urls['create_user']:
     # fill in the rest of the hash we started in example 2 with valid data
     params_hash["email"] = random_username + "@ben.com"
     params_hash["password"] = "123123abc"
     params_hash["dob"] = "1980-01-01"
     
     xml_to_post = LLSD.to_xml(params_hash) # convert it to llsd xml
     response_xml = LLSD.post_xml(capability_urls['create_user'], xml_to_post)
     puts "posted xml:" # Print out response xml
     puts xml_to_post
     puts "xml response:" # Print out response xml
     puts response_xml
     result_hash = LLSD.parse(response_xml) # Parse the xml
     puts "New agent id: #{result_hash['agent_id']}" # Print the result
     
     # ALL DONE!!
   else
     puts "Create_user capability not granted to #{first_name} #{last_name}. Exiting Prematurely ..."
   end
 else
   puts "Check_name capability not granted to #{first_name} #{last_name}. Exiting Prematurely ..."
 end

else

 puts "Get_last_names capability not granted to #{first_name} #{last_name}. Exiting Prematurely..."

end

Python

<python>import llsd import urllib2, random, sys

  1. This python example shows how to use the Registration API. The example goes as follows:
  1. 0 - get capability urls
  2. 1 - get error codes
  3. 2 - get the available last names
  4. 3 - check to see of a username + last name combo is taken
  5. 4 - register the user with this username + last name combo

get_capabilities_url = "https://cap.secondlife.com/get_reg_capabilities"

  1. grab command line args

if len(sys.argv) == 4:

 first_name = sys.argv[1]
 last_name = sys.argv[2]
 password = sys.argv[3]

else:

 print "Please pass in your second life first name, last name, and password as arguments. For example:"
 print "python registration_api.py registration mackay 1234"
 
 sys.exit()


  1. 0 - Get Capability URLS #################################################################

print "========== Getting capabilities ==========="

post_body = "first_name=%s&last_name=%s&password=%s" % (first_name, last_name, password) # create a url-encoded string to POST response_xml = urllib2.urlopen(get_capabilities_url, post_body).read() # POST the capability url to get capabilities

print "xml response:" # Print out response xml print response_xml

capability_urls = llsd.parse(response_xml) # Parse the xml

for id, name in capability_urls.items(): # Print out capabilities

   print "%s => %s" % (id, name)
   
  1. 1 - Print out error codes ###############################################################

if 'get_error_codes' in capability_urls:

   print "\n\n========== Get Error Codes Example ===========\n"
 
   response_xml = urllib2.urlopen(capability_urls['get_error_codes']).read() # GET the capability url for getting error codes
 
   print "xml response:" # Print out response xml
   print response_xml
 
   error_codes = llsd.parse(response_xml) # Parse the xml
   for error in error_codes: # Print out capabilities
       print "%s => %s" % (error[0], error[1])

else:

   print "Get_error_codes capability not granted to %s %s. Now Exiting Prematurely ..." % (first_name, last_name)
   
  1. 2 - Get Last Names Example ##############################################################

if 'get_last_names' in capability_urls:

   print "\n\n========== Get Last Names Example ==========="
   response_xml = urllib2.urlopen(capability_urls['get_last_names']).read() # GET the capability url for getting last names and ids
   print "xml response:" # Print out response xml
   print response_xml
   
   last_names = llsd.parse(response_xml) # Parse the xml
   for id, name in last_names.items(): # Print out last names
       print "%s => %s" % (id, name)


   # 3 - Check Name Example ##################################################################
   if 'check_name' in capability_urls:
       print "\n\n========== Check Name Example ==========="
       random_username = 'benny' + str(random.randrange(100,10000)) # Generate a random username
       valid_last_name_id = last_names.keys()[0] # Get the first valid last name id
       params_hash = {"username": random_username, "last_name_id": valid_last_name_id } # put it in a hash
       xml_to_post = llsd.toXML(params_hash) # convert it to llsd xml
       response_xml = urllib2.urlopen(capability_urls['check_name'], xml_to_post).read() 
       print "posted xml " # Print out response xml
       print xml_to_post
       print "xml response:" # Print out response xml
       print response_xml
       is_name_available = llsd.parse(response_xml) # Parse the xml
       print "Result (is name available?): %s" % (is_name_available) # Print the result
       
       # 4 - Create User Example #################################################################
       if is_name_available and 'create_user' in capability_urls:
           print "\n\n========== Create User Example ==========="
           # fill in the rest of the hash we started in example 2 with valid data
           params_hash["email"] = random_username + "@ben.com"
           params_hash["password"] = "123123abc"
           params_hash["dob"] = "1980-01-01"
           
           xml_to_post = llsd.toXML(params_hash) # convert it to llsd xml
           response_xml = urllib2.urlopen(capability_urls['create_user'], xml_to_post).read() 
           print "posted xml " # Print out response xml
           print xml_to_post
           print "xml response:" # Print out response xml
           print response_xml
           result_hash = llsd.parse(response_xml) # Parse the xml
           print "New agent id: %s" % (result_hash["agent_id"]) # Print the result
   
           
           # ALL DONE!!
       else:
           print "create_user capability not granted to %s %s. Now Exiting Prematurely ..." % (first_name, last_name)
           
   else:
       print "check_name capability not granted to %s %s. Now Exiting Prematurely ..." % (first_name, last_name)
       

else:

   print "get_last_names capability not granted to %s %s. Now Exiting Prematurely ..." % (first_name, last_name)</python>

PHP

NOTE: This uses PHP4. See also Guidelines and tips.

<php><?php require_once('llsd.php');

// FILL THESE IN WITH YOUR OWN CAPABILITY URLS define('URI_CREATE_USER', '?????????'); define('URI_GET_LAST_NAMES', '?????????'); define('URI_CHECK_NAME', '?????????');

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

   if (is_name_available($_POST['username'], $_POST['last_name_id']))
   {
       $user = array
       (
           'username'     => $_POST['username'],
           'last_name_id' => (int)$_POST['last_name_id'],
           'email'        => $_POST['email'],
           'password'     => $_POST['password'],
           'dob'          => $_POST['dob_year'].'-'.$_POST['dob_month'].'-'.$_POST['dob_day']
       );
       $result = llsd_post(URI_CREATE_USER, $user);
       print $result['agent_id'];
   }
   else
   {
       print 'SL name not available.';
   }

} ?>

Create Second Life Account

<form action="<?php print $_SERVER['PHP_SELF']; ?>" method="post">

First name: <input type="text" name="username" size="25" maxlength="31" value="" />
Last name:
 <select name="last_name_id">
 <?php
 $last_names = llsd_get(URI_GET_LAST_NAMES);
 foreach ($last_names as $last_name_id => $name)
 {
     print '<option value="'.$last_name_id.'">'.$name.'</option>';
 }
 ?>
 </select>
Password: <input type="password" name="password" size="20" value="" />
Email: <input type="text" name="email" size="35" value="" />
Date of brith:
   <select name="dob_day">
   <?php
   $days = get_days();
   foreach ($days as $key => $value) { print '<option value="'.$key.'" '.$selected.'>'.$value.'</option>'; }
   ?>
   </select>
   <select name="dob_month">
   <?php
   $months = get_months();
   foreach ($months as $key => $value) { print '<option value="'.$key.'" '.$selected.'>'.$value.'</option>'; }
   ?>
   </select>
   
   <select name="dob_year">
   <?php
   $years = get_years();
   foreach ($years as $key => $value) { print '<option value="'.$key.'" '.$selected.'>'.$value.'</option>'; } 
   ?>
   </select>
<input type="submit" value="Create SL Account" />

</form>

<?php function get_months() {

   $months = array();
   for ($i = 1; $i <= 12; $i++)
   {
       $key = date('n', mktime(0, 0, 0, $i, 1, 2000));
       $value = date('M.', mktime(0, 0, 0, $i, 1, 2000));
       $months[sprintf("%02d", $key)] = $value;
   }
   return $months;

}

function get_years() {

   $today = getdate();
   $max_year = $today['year'] - 90;
   $min_year = $today['year'] - 13;
   $years = array();
   for ($i = $min_year; $i >= $max_year; $i--)
   {
       $years[$i] = $i;
   }
   return $years;

}

function get_days() {

   $days = array();
   for ($i = 1; $i <= 31; $i++)
   {
       $days[sprintf("%02d", $i)] = sprintf("%02d", $i);
   }
   return $days;

}

function is_name_available($username, $last_name_id) {

   $params = array('username' => $username, 'last_name_id' => (int)$last_name_id);
   if (llsd_post(URI_CHECK_NAME, $params) == 'true')
   {
       return true;
   }
   return false;

} ?></php>