更新用户照片

时间:2016-11-12 00:23:49

标签: ruby google-api google-api-ruby-client

我正在尝试使用以下代码更新G Suite用户的用户照片:

require 'google/apis/admin_directory_v1'
require 'googleauth'
require 'googleauth/stores/file_token_store'

require 'fileutils'

OOB_URI = 'urn:ietf:wg:oauth:2.0:oob'
CLIENT_SECRETS_PATH = 'client_secrets.json'
CREDENTIALS_PATH = File.join(Dir.home, '.credentials',
                             "admin-directory_v1-ruby-quickstart.yaml")
SCOPE = "https://www.googleapis.com/auth/admin.directory.user"    

def authorize
  FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))

  client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)
  token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)
  authorizer = Google::Auth::UserAuthorizer.new(
    client_id, SCOPE, token_store)
  user_id = 'default'
  credentials = authorizer.get_credentials(user_id)
  if credentials.nil?
    url = authorizer.get_authorization_url(
      base_url: OOB_URI)
    puts "Open the following URL in the browser and enter the " +
         "resulting code after authorization"
    puts url
    code = gets
    credentials = authorizer.get_and_store_credentials_from_code(
      user_id: user_id, code: code, base_url: OOB_URI)
  end
  credentials
end

# Initialize the API
service = Google::Apis::AdminDirectoryV1::DirectoryService.new
service.authorization = authorize

require "base64"    
pic = Base64.encode64(File.read('profilepic.png')).tr("+/", "-_")

photo = Google::Apis::AdminDirectoryV1::UserPhoto.new
photo.photo_data = pic

service.update_user_photo("user@domain.com", photo)

然后我收到错误"invalid: Invalid Input: photoData (Google::Apis::ClientError)"。我开始怀疑这可能是客户端库中的错误,但我想首先检查其他人是否成功执行了此操作。我已经能够更新"试试吧!"使用pic = Base64.encode64(File.read('profilepic.png')).tr("+/", "-_")返回的base64编码字符串https://developers.google.com/admin-sdk/directory/v1/reference/users/photos/update这里的部分,我已经能够使用PHP客户端库执行此操作,因此我猜这是一个错误。任何人都可以提供见解吗?

0 个答案:

没有答案