Ruby/Rails服务端无需OAuth重定向连接Google My Business API及调用方法
使用服务账号调用Google My Business API(Ruby/Rails)
服务账号是完全适配你需求的无交互服务端授权方案,无需浏览器重定向,凭证可安全存储在Rails secrets或环境变量中,完美替代OAuth授权码流程。
一、优化Access Token获取代码(符合Rails最佳实践)
你已成功获取token,建议将密钥从文件读取改为从Rails凭证/环境变量读取,避免敏感文件提交到版本控制:
scope = 'https://www.googleapis.com/auth/business.manage' # 方式1:从Rails credentials读取 json_key = Rails.application.credentials.google_service_account_json # 方式2:从环境变量读取(适合部署环境) # json_key = ENV['GOOGLE_SERVICE_ACCOUNT_JSON'] authorizer = Google::Auth::ServiceAccountCredentials.make_creds( json_key_io: StringIO.new(json_key), scope: scope ) token_hash = authorizer.fetch_access_token! access_token = token_hash[:access_token] # token_hash[:expires_at] 可用于判断token是否过期(通常有效期1小时)
二、使用Access Token调用API
以下是两种常用的Ruby HTTP客户端调用示例,以获取商家位置列表为例(替换为你需要的API端点和参数):
方式1:用Faraday(Rails常用HTTP客户端)
- 先在Gemfile中添加依赖:
gem 'faraday'
运行bundle install安装。
- 调用代码:
require 'faraday' # 初始化客户端,设置默认请求头 conn = Faraday.new(url: 'https://mybusinessbusinessinformation.googleapis.com/v1') do |faraday| faraday.headers['Authorization'] = "Bearer #{access_token}" faraday.headers['Content-Type'] = 'application/json' faraday.adapter Faraday.default_adapter end # 替换为你的商家账号ID(account_id) account_id = 'your-google-my-business-account-id' response = conn.get "/accounts/#{account_id}/locations" # 处理响应 if response.success? locations = JSON.parse(response.body) puts "获取到的位置信息:#{locations}" else puts "API调用失败:#{response.status} - #{response.body}" end
方式2:用Net::HTTP(原生Ruby,无需额外Gem)
require 'net/http' require 'json' account_id = 'your-google-my-business-account-id' uri = URI("https://mybusinessbusinessinformation.googleapis.com/v1/accounts/#{account_id}/locations") http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true request = Net::HTTP::Get.new(uri) request['Authorization'] = "Bearer #{access_token}" request['Content-Type'] = 'application/json' response = http.request(request) if response.is_a?(Net::HTTPSuccess) locations = JSON.parse(response.body) puts "获取到的位置信息:#{locations}" else puts "API调用失败:#{response.code} - #{response.body}" end
关键注意事项
- 服务账号授权:必须在Google My Business后台,将服务账号的邮箱(在密钥JSON文件的
client_email字段)添加为账号的管理员/所有者,否则会提示权限不足。 - Token过期处理:Access Token有效期为1小时,可通过
token_hash[:expires_at]判断是否过期,过期后调用authorizer.refresh_access_token!刷新。 - API端点匹配:不同的GMB操作对应不同的API端点,需参考官方文档调整请求路径和方法(GET/POST/PUT等)。
内容的提问来源于stack exchange,提问作者ninja
相关产品推荐
相关产品推荐

