谷歌联系人导入API随机抛出404(无法添加新联系人)错误

时间:2017-03-09 10:18:56

标签: ruby google-api gmail-api gdata google-contacts

我正在尝试通过服务帐户向G Suite域下的用户帐户添加联系人。服务帐户已获得域范围访问权限。它一直插入联系人。 但有时候,尽管成功添加了联系人,但仍然会出现以下错误

<?xml version="1.0" encoding="UTF-8"?>
<errors xmlns="http://schemas.google.com/g/2005">
  <error>
    <domain>GData</domain>
    <code>notFound</code>
    <internalReason>Cannot add new contact.</internalReason>
  </error>
</errors>

以下是我们正在使用的Ruby代码

class GoogleContacts

  def self.create_contact(owner, campaign)
    body = user_contact_in_atom_format(campaign.user, campaign)
    api_access_token_obj(owner.email).post("https://www.google.com/m8/feeds/contacts/default/full?v=3",
      {
        body: body,
        headers: {'Content-Type' => 'application/atom+xml'}
      }
    )
  end

  def self.api_client_object
    @@api_client_object ||=
      OAuth2::Client.new(
        client["client_email"],
        client["private_key"],
        {
          site: 'https://www.google.com/',
          raise_errors: true
        }
      )
  end

  def self.api_access_token_obj(sub)
    OAuth2::AccessToken.new(
      api_client_object,
      get_access_token(sub)
    )
  end

  def self.get_access_token(sub)
    authorisation(sub).fetch_access_token!["access_token"]
  end

  def self.client
    @@client ||= YAML::load(open(Rails.root + 'keys/google/contacts_credentials.json'))
  end

  def self.authorisation(sub)
    Signet::OAuth2::Client.new(
      token_credential_uri: 'https://accounts.google.com/o/oauth2/token',
      audience: 'https://accounts.google.com/o/oauth2/token',
      scope: 'https://www.googleapis.com/auth/contacts',
      issuer: client["client_email"],
      signing_key: OpenSSL::PKey::RSA.new(client["private_key"], nil),
      sub: sub
    )
  end

  def self.user_contact_in_atom_format(user, campaign)
    body = <<EOF
      <atom:entry xmlns:atom="http://www.w3.org/2005/Atom"
      xmlns:gd="http://schemas.google.com/g/2005">

        <atom:category scheme="http://schemas.google.com/g/2005#kind"
          term="http://schemas.google.com/contact/2008#contact"/>

        <gd:name>
           <gd:fullName>#{user.full_name} #{campaign.name} champion</gd:fullName>
        </gd:name>

        <atom:content type="text">Notes</atom:content>

        <gd:email rel="http://schemas.google.com/g/2005#home"
          address="#{user.email}"/>

        <gd:phoneNumber rel="http://schemas.google.com/g/2005#home"
          primary="true">
          (#{user.phone_country_code})#{user.phone_num}
        </gd:phoneNumber>
      </atom:entry>
EOF
  end

end

0 个答案:

没有答案