在 G Suite 中更新用户照片

Update user photo in G Suite

我正在尝试使用以下代码更新 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 编码字符串更新 "Try it!" section here 中的照片,并且我已经能够使用 PHP 客户端库来完成此操作。我认为这是一个错误是否正确?

我知道这是一个很老的问题,但我遇到了同样的问题,结果是 google-api-client 库自动 base64 encodes/decodes 你的 photo_data,所以你只需要将文件数据传递给它而不是对其进行编码,否则它会被编码两次,您将遇到 400 错误。

# Read file
photo_data = File.read(image_path)

# Create a UserPhoto object
user_photo_object = Google::Apis::AdminDirectoryV1::UserPhoto.new(photo_data: photo_data)

# Update Photo
directory.update_user(user_key, user_photo_object)