You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google People API是否支持更新Person/UserDefined字段?

Google People API 是否支持更新 Person/UserDefined 字段?

答案是肯定的——Google People API 确实支持更新 Person.userDefined 字段,尽管官方updateContact接口文档里的updatePersonFields参数列表没明确列出这个字段,但这属于文档疏漏,实际使用中这个字段是可以正常更新的。

接下来结合你的代码和场景,说说可能导致你更新失败的原因和修复建议:

可能的问题与修复方向

1. 数组字段需要完整替换,不能增量更新

Google People API 的updateContact是部分更新机制,但对于userDefined这种数组类型的字段,API会用你传入的完整数组替换原有的数据,而不是只修改你指定的项。如果你只传入了部分自定义项,原有未被包含的项会被直接删除。

正确的做法应该是:

  • 先调用getContact接口获取当前联系人的完整数据
  • 在现有userDefined列表的基础上修改(添加、编辑或删除项)
  • 把修改后的完整Person对象传给updateContact

2. 确认ETag获取和设置无误

你的代码里已经处理了ETag,这一点做得很对——ETag是用来避免并发更新冲突的,确保你修改的是最新版本的联系人数据。不过可以检查下get-g-contact-id-and-etag函数是否正确从资源名称中获取到了有效的ETag值,比如有没有可能返回了空值?

3. 打印更详细的错误信息定位问题

你当前的错误处理只记录了异常消息,建议把完整的错误栈或者API返回的响应体也打出来,比如:

(lg/log! :error (str "更新失败: " (.getMessage e) "\n错误栈: " (clojure.string/join "\n" (.getStackTrace e))))

这样能帮你快速定位到底是权限问题、字段格式错误,还是其他原因。

修正后的核心代码示例

这里给你调整了更新逻辑,先获取当前联系人数据再修改:

;; 新增获取联系人的函数
(defn get-google-contact [people-service resource-name]
  (-> people-service
      .people
      (.getContact resource-name)
      (.setPersonFields update-person-fields)
      .execute))

(defn update-google-contact [user-id wingman-contact-id google-contact]
  (try
    (lg/log! :info (str "为用户 " user-id " 更新Google联系人"))
    (let [people-service (initialize-people-service user-id)
          resource-name (.getResourceName google-contact)
          [google-contact-id etag] (get-g-contact-id-and-etag resource-name people-service)
          ;; 获取当前联系人的完整数据
          current-contact (get-google-contact people-service resource-name)
          ;; 示例:在现有userDefined列表中添加新项
          updated-user-defined (conj (.getUserDefined current-contact)
                                     (doto (com.google.api.services.people.v1.model.UserDefined.)
                                       (.setKey "CUSTOM_KEY")
                                       (.setValue "CUSTOM_VALUE")))
          ;; 更新联系人对象的userDefined和ETag
          updated-contact (doto current-contact
                            (.setUserDefined updated-user-defined)
                            (.setEtag etag))]
      (-> people-service
          .people
          (.updateContact resource-name updated-contact)
          (.setUpdatePersonFields update-person-fields)
          .execute
          (update-contact-callback)))
    (catch Exception e
      (lg/log! :error (str "更新失败: " (.getMessage e) "\n错误栈: " (clojure.string/join "\n" (.getStackTrace e))))
      false)))

额外需要检查的点

  • 确认你的OAuth权限包含https://www.googleapis.com/auth/contacts——更新联系人必须要有这个权限
  • 检查构造UserDefined对象时,key和value有没有空值或者格式不符合要求的情况

内容的提问来源于stack exchange,提问作者Lam Nguyen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:47:39