linkedin.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import simplejson as json
  2. import requests
  3. import urlparse, urllib
  4. AUTHORIZATION_URL = 'https://www.linkedin.com/uas/oauth2/authorization'
  5. ACCESS_TOKEN_URL = 'https://www.linkedin.com/uas/oauth2/accessToken'
  6. class LinkedinOauthClient(object):
  7. is_authorized = False
  8. def __init__(self, client_id, client_secret):
  9. self.client_id = client_id
  10. self.client_secret = client_secret
  11. def get_authorize_url(self):
  12. auth_setting = {'response_type' : 'code',
  13. 'client_id' : self.client_id,
  14. 'client_secret' : self.client_secret,
  15. 'redirect_uri' : 'http://127.0.0.1:8000/hackathon/',
  16. 'state' : 'DCEeFWf45A53sdfKef424',
  17. 'scope': 'r_basicprofile'}
  18. params = urllib.urlencode(auth_setting)
  19. authURL = AUTHORIZATION_URL + '?' + params
  20. return authURL
  21. def get_access_token(self, code):
  22. settings = {'grant_type' : 'authorization_code',
  23. 'code' : code,
  24. 'redirect_uri' : 'http://127.0.0.1:8000/hackathon/',
  25. 'client_id' : self.client_id,
  26. 'client_secret': self.client_secret}
  27. header = {'content-type' : 'application/x-www-form-urlencoded'}
  28. params = urllib.urlencode(settings)
  29. link = ACCESS_TOKEN_URL + '?' + params
  30. req = requests.post(link)#, headers=header)
  31. if req.status_code != 200:
  32. raise Exception('Invalid response %s' %req.status_code)
  33. content = json.loads(req.content)
  34. self.access_token = content['access_token']
  35. self.is_authorized = True
  36. def getUserInfo(self):
  37. #link = 'https://api.linkedin.com/v1/people/~?format=json&oauth2_access_token=' + self.access_token
  38. link = 'https://api.linkedin.com/v1/people/~:(id,first-name,skills,educations,languages,twitter-accounts)?oauth2_access_token='+self.access_token
  39. headers = {'x-li-format' : 'json',
  40. 'content-type' : 'application/json'}
  41. req = requests.get(link, headers=headers)
  42. content = json.loads(req.content)
  43. if req.status_code != 200:
  44. raise Exception('Invalid response %s' %req.status_code)
  45. self.user_id = content['id']
  46. print content
  47. return content