Linden Lab Official:Reg API Examples: Difference between revisions

From Second Life Wiki
Jump to navigation Jump to search
Rand Linden (talk | contribs)
Re-inserted LLSD-Java reference
(6 intermediate revisions by one other user not shown)
Line 2: Line 2:


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.
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.
<br/><br/>
__TOC__
<br clear="all"/>


== LLSD library downloads ==
== LLSD library downloads ==
Line 14: Line 15:
* [https://secure-web10.secondlife.com/developers/third_party_reg/llsd_libs/llsd.py-lib Python LLSD library] (version 1.2)
* [https://secure-web10.secondlife.com/developers/third_party_reg/llsd_libs/llsd.py-lib Python LLSD library] (version 1.2)
* [https://secure-web10.secondlife.com/developers/third_party_reg/llsd_libs/llsd.pm-lib Perl LLSD library] (version 1.0)
* [https://secure-web10.secondlife.com/developers/third_party_reg/llsd_libs/llsd.pm-lib Perl LLSD library] (version 1.0)
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?
Question: what version of each language is required?
Line 21: Line 26:
=== Ruby ===
=== Ruby ===


<pre>
This ruby example shows how to use the Registration API.
require 'llsd'


# This ruby example shows how to use the Registration API. The example goes as follows:
<ruby>require 'llsd'


# 0 - get capability urls
# 0 - get capability urls
Line 40: Line 44:
   password = ARGV[2]
   password = ARGV[2]
else
else
   puts "Please pass in your second life first name, last name, and password as arguments. For example:"
   puts "Please pass in your second life first name, last name, and password as arguments."
   puts "ruby registration_api.rb joe linden 1234"
   puts "For example: ruby registration_api.rb joe linden 1234"
    
    
   exit
   exit
end
end


# 0 - Get Capability URLS #################################################################
# 0 - Get Capability URLS ##############################################
puts "========== Getting capabilities ===========\n"
puts "========== Getting capabilities ===========\n"


post_body = "first_name=#{first_name}&last_name=#{last_name}&password=#{password}" # create a url-encoded string to POST
post_body = "first_name=#{first_name}&last_name=#{last_name}&password=#{password}"  
response_xml = LLSD.post_urlencoded_data get_capabilities_url, post_body # POST the capability url to get capabilities
# create a url-encoded string to POST
response_xml = LLSD.post_urlencoded_data get_capabilities_url, post_body  
# POST the capability url to get capabilities


puts "xml response:" # Print out response xml
puts "xml response:" # Print out response xml
Line 61: Line 67:
capability_urls.each { |k,v| puts "#{k} => #{v}"} # print out capabilities
capability_urls.each { |k,v| puts "#{k} => #{v}"} # print out capabilities


# 1 - Print out error codes ###############################################################
# 1 - Print out error codes ##############################################
puts "\n\n========== Get Error Codes Example ===========\n"
puts "\n\n========== Get Error Codes Example ===========\n"


if capability_urls['get_error_codes']   
if capability_urls['get_error_codes']   
   response_xml = LLSD.http_raw capability_urls['get_error_codes'] # GET the capability url for getting 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 "xml response:" # Print out response xml
Line 72: Line 79:
   error_codes = LLSD.parse(response_xml) # Parse the xml
   error_codes = LLSD.parse(response_xml) # Parse the xml


   error_codes.each {|error| puts "#{error[0]} => #{error[1]}"} # print out all error codes
   error_codes.each {|error| puts "#{error[0]} => #{error[1]}"}  
  # print out all error codes
else
else
   puts "Get_error_codes capability not granted to #{first_name} #{last_name}. Now Exiting Prematurely ..."
   puts "Get_error_codes capability not granted to #{first_name} #{last_name}. Exiting Prematurely ..."
end
end
 


 
# 2 - Get Last Names Example ##############################################
# 2 - Get Last Names Example ##############################################################
puts "\n\n========== Get Last Names Example ===========\n"
puts "\n\n========== Get Last Names Example ===========\n"
if capability_urls['get_last_names']
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
   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 "xml response:" # Print out response xml
Line 92: Line 99:
    
    
    
    
   # 3 - Check Name Example ##################################################################
   # 3 - Check Name Example ##############################################
   print "\n\n========== Check Name Example ===========\n"
   print "\n\n========== Check Name Example ===========\n"
   if capability_urls['check_name']
   if capability_urls['check_name']
     random_username = 'tester' + Kernel.rand(10000).to_s # Generate a random username
     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
     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
     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
     xml_to_post = LLSD.to_xml(params_hash) # convert it to llsd xml
Line 113: Line 121:
     puts "Result (is name available?): #{is_name_available}" # Print the result
     puts "Result (is name available?): #{is_name_available}" # Print the result
      
      
   
     # 4 - Create User Example ##############################################
 
     # 4 - Create User Example #################################################################
     puts "\n\n========== Create User Example ===========\n"
     puts "\n\n========== Create User Example ===========\n"
     if is_name_available and capability_urls['create_user']:
     if is_name_available and capability_urls['create_user']:
Line 139: Line 145:
       # ALL DONE!!
       # ALL DONE!!
     else
     else
       puts "Create_user capability not granted to #{first_name} #{last_name}. Now Exiting Prematurely ..."
       puts "Create_user capability not granted to #{first_name} #{last_name}. Exiting Prematurely ..."
     end
     end
   else
   else
     puts "Check_name capability not granted to #{first_name} #{last_name}. Now Exiting Prematurely ..."
     puts "Check_name capability not granted to #{first_name} #{last_name}. Exiting Prematurely ..."
   end
   end
else
else
   puts "Get_last_names capability not granted to #{first_name} #{last_name}. Now Exiting Prematurely..."
   puts "Get_last_names capability not granted to #{first_name} #{last_name}. Exiting Prematurely..."
end
end</ruby>
</pre>


=== Python ===
=== Python ===


<pre>
<python>import llsd
import llsd
import urllib2, random, sys
import urllib2, random, sys


Line 191: Line 195:
     print "%s => %s" % (id, name)
     print "%s => %s" % (id, name)
      
      
   
# 1 - Print out error codes ###############################################################
# 1 - Print out error codes ###############################################################
if capability_urls.has_key('get_error_codes'):
if capability_urls.has_key('get_error_codes'):
Line 223: Line 225:
     for id, name in last_names.items(): # Print out last names
     for id, name in last_names.items(): # Print out last names
         print "%s => %s" % (id, name)
         print "%s => %s" % (id, name)




Line 249: Line 249:
         print "Result (is name available?): %s" % (is_name_available) # Print the result
         print "Result (is name available?): %s" % (is_name_available) # Print the result
          
          
       


         # 4 - Create User Example #################################################################
         # 4 - Create User Example #################################################################
Line 284: Line 282:
          
          
else:
else:
     print "get_last_names capability not granted to %s %s. Now Exiting Prematurely ..." % (first_name, last_name)
     print "get_last_names capability not granted to %s %s. Now Exiting Prematurely ..." % (first_name, last_name)</python>
</pre>


=== PHP ===
=== PHP ===
Warning, not up to date, will update soon.
NOTE: This uses PHP4.  See also [[Registration_API#Guidelines_and_tips|Guidelines and tips]].


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


Line 431: Line 427:
     return false;
     return false;
}
}
?>
?></php>
</pre>


[[Category:RegAPI|Sample Code]]
[[Category:RegAPI|Sample Code]]
[[Category:Web Service APIs]]
[[Category:Web Service APIs]]

Revision as of 03:28, 4 September 2009

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 "ruby registration_api.rb 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 capability_urls.has_key('get_error_codes'):

   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 capability_urls.has_key('get_last_names'):

   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 capability_urls.has_key('check_name'):
       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 capability_urls.has_key('create_user'):
           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>