Javascript 添加到联系人,如添加到日历按钮/html/Ajax选项

Javascript 添加到联系人,如添加到日历按钮/html/Ajax选项,javascript,outlook,addressbook,google-contacts-api,Javascript,Outlook,Addressbook,Google Contacts Api,我想为网页开发一个“添加到联系人”按钮,就像您在网络研讨会和活动页面上看到的“添加到日历-谷歌、ICal、Outlook”类型的按钮一样 我开始调查谷歌联系人,因为我使用它。 我开始构建一个表单,将application/atom+xml提交到他们在中讨论的URL以及一个类似的问题 我认为创建这项服务是一项类似于开源的社区服务,在我修补它时,一些专家的帮助将不胜感激。我在这里要求作出这一贡献 我的粗略代码,不起作用 function SendToGoogle() { var url = "ht

我想为网页开发一个“添加到联系人”按钮,就像您在网络研讨会和活动页面上看到的“添加到日历-谷歌、ICal、Outlook”类型的按钮一样

我开始调查谷歌联系人,因为我使用它。 我开始构建一个表单,将application/atom+xml提交到他们在中讨论的URL以及一个类似的问题

我认为创建这项服务是一项类似于开源的社区服务,在我修补它时,一些专家的帮助将不胜感激。我在这里要求作出这一贡献

我的粗略代码,不起作用

function SendToGoogle() { var url = "https://www.google.com/m8/feeds/contacts/default/full"; var data = contactData(); alert(data); /* $.post(url, data, function(data, status){ alert("Data: " + data + "\nStatus: " + status); }); */ $.ajax({type: "POST", url: url, dataType: "xml", contentType: "application/atom+xml", cache: false, async: true, crossDomain: true, success: function(data, status){ alert("Data: " + data + "\nStatus: " + status)} }) } //end SendToGoogle function contactData() { return ' Elizabeth Bennet Elizabeth Bennet Notes (206)555-1212 (206)555-1213 Mountain View 1600 Amphitheatre Pkwy CA 94043 United States 1600 Amphitheatre Pkwy Mountain View '; } //end contactData 函数sendtogle(){ 变量url=”https://www.google.com/m8/feeds/contacts/default/full"; var data=contactData(); 警报(数据); /* $.post(url、数据、函数(数据、状态){ 警报(“数据:+数据+”\n状态:+状态); }); */ $.ajax({type:“POST”, url:url, 数据类型:“xml”, contentType:“应用程序/atom+xml”, cache:false, async:true, 跨域:是的, 成功:功能(数据、状态){ 警报(“数据:+数据+”\n状态:+状态)} }) }//结束sendtogle 函数contactData(){ 返回“Elizabeth Bennet Elizabeth Bennet Notes(206)555-1212(206)555-1213山景1600圆形剧场Pkwy CA 94043美国1600圆形剧场Pkwy山景”; }//结束contactData
证据就在布丁里,所以在你读这篇长文章折磨自己之前:让它工作吧:)如果你打开了webtool的控制台,你可以看到我们找回了联系人资源,伊丽莎白·班纳特现在将在你的联系人中

哦,顺便说一下,当作为用户进行身份验证时,谷歌会抱怨我的小网站和你的本地版本都不安全,只需单击“高级”并继续。(谷歌将这样做,直到你提交你的OAuth供他们的团队验证,他们的团队在最终产品上做得非常好,但是…)

那么在 在最顶端,我们看到:

注意:要对用户的联系人进行读写访问,请使用People API,它使用JSON提供联系人和个人资料信息 而不是旧的GData协议

因此,这里的正确答案似乎是转到。我花了一些时间研究它,并给你一个粗略的回答

我找到了一个页面,它可以解决你想要的大部分问题。如果您完全遵循它,您将得到一个本地版本的javascript连接到他们的api,它允许我们创建联系人

我们必须在谷歌的api中设置一个api应用程序,以对这个过程进行本质上的验证

一旦我们这样做了,我们就可以设置按钮,请求用户接受身份验证(允许我们为他们创建联系人)

有趣的是改变他们的代码,只需将页面上排名前十的用户放在创建联系人的位置

在您获得用户许可后,似乎有一些方法可以直接使用常规http请求,但我发现使用他们的http请求会更快

我们需要知道如何设置
gapi.client.people.people.createContact
api调用,它需要一个。该资源非常方便,可以点击查看如何设置人员资源类别

在我们尝试将api放在网页上之前,我们可以在这里使用它。在右侧面板中有一个标题:

试试这个API

在它旁边有一个小盒子,它可以扩展这个区域,这样我们就可以更容易地使用api。右上角有一个JavaScript选项,用于尝试查看与我们正在执行的请求等效的JavaScript

在左边,我们有一个请求主体,它允许我们输入createContacts api请求的详细信息。因此,对于您的示例,如果您输入:

    {
      "names": [
          {
            "givenName": "Elizabeth",
            "familyName": "Bennet"
          }
        ],
        "phoneNumbers": [
          {
            "type": "home",
            "value": "(206)555-1212"
          },
          {
            "type": "cell",
            "value": "(206)555-1213"
          }
        ],
        "addresses": [
          {
            "type": "home",
            "streetAddress": "1600 Amphitheatre Pkwy",
            "postalCode": "94043",
            "country": "United States",
            "city": "Mountain View",
            "region": "California"
          }
        ]
    }
在左边的框中,您可以看到它将其输入到右边的javascript createContacts请求中

现在,代码对于我们希望如何保持自己和用户的身份验证并不完美,因此我们将挑选两件主要的事情:

  • createContacts代码
  • .signIn({scope:)中的urlhttps://www.googleapis.com/auth/contacts“})
该范围基本上告诉api我们希望用户访问什么

因此,现在把所有这些放在一起:

<!DOCTYPE html>
<html>
  <head>
    <title>People API Quickstart</title>
    <meta charset="utf-8" />
  </head>
  <body>
    <p>People API Quickstart</p>

    <!--Add buttons to initiate auth sequence and sign out-->
    <button id="authorize_button" style="display: none;">Authorize</button>
    <button id="signout_button" style="display: none;">Sign Out</button>
    <button id="contact_button" style="display: none;">Create Contact</button>

    <pre id="content" style="white-space: pre-wrap;"></pre>

    <script type="text/javascript">
      // Client ID and API key from the Developer Console
      var CLIENT_ID = '< YOUR CLIENT ID HERE! >';
      var API_KEY = '< YOUR API KEY HERE! >';

      // Array of API discovery doc URLs for APIs used by the quickstart
      var DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/people/v1/rest"];

      // Authorization scopes required by the API; multiple scopes can be
      // included, separated by spaces.
      var SCOPES = "https://www.googleapis.com/auth/contacts";

      var authorizeButton = document.getElementById('authorize_button');
      var signoutButton = document.getElementById('signout_button');
      var contactButton = document.getElementById('contact_button');

      /**
       *  On load, called to load the auth2 library and API client library.
       */
      function handleClientLoad() {
        gapi.load('client:auth2', initClient);
      }

      /**
       *  Initializes the API client library and sets up sign-in state
       *  listeners.
       */
      function initClient() {
        gapi.client.init({
          apiKey: API_KEY,
          clientId: CLIENT_ID,
          discoveryDocs: DISCOVERY_DOCS,
          scope: SCOPES
        }).then(function () {
          // Listen for sign-in state changes.
          gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);

          // Handle the initial sign-in state.
          updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
          authorizeButton.onclick = handleAuthClick;
          signoutButton.onclick = handleSignoutClick;
          contactButton.onclick = handleContactClick;
        }, function(error) {
          appendPre(JSON.stringify(error, null, 2));
        });
      }

      /**
       *  Called when the signed in status changes, to update the UI
       *  appropriately. After a sign-in, the API is called.
       */
      function updateSigninStatus(isSignedIn) {
        if (isSignedIn) {
          authorizeButton.style.display = 'none';
          signoutButton.style.display = 'block';
          contactButton.style.display = 'block';
        } else {
          authorizeButton.style.display = 'block';
          signoutButton.style.display = 'none';
        }
      }

      /**
       *  Sign in the user upon button click.
       */
      function handleAuthClick(event) {
        gapi.auth2.getAuthInstance().signIn();
      }

      /**
       *  Sign out the user upon button click.
       */
      function handleSignoutClick(event) {
        gapi.auth2.getAuthInstance().signOut();
      }

      /**
       *  Create a contact upon button click.
       */
      function handleContactClick() {
        gapi.client.people.people.createContact({
          "resource": {
            "names": [
              {
                "givenName": "Elizabeth",
                "familyName": "Bennet"
              }
            ],
            "phoneNumbers": [
              {
                "type": "home",
                "value": "(206)555-1212"
             .signIn({scope: "https://www.googleapis.com/auth/contacts"}) },
              {
                "type": "cell",
                "value": "(206)555-1213"
              }
            ],
            "addresses": [
              {
                "type": "home",
                "streetAddress": "1600 Amphitheatre Pkwy",
                "postalCode": "94043",
                "country": "United States",
                "city": "Mountain View",
                "region": "California"
              }
            ]
          }
        }).then(function(response) {
                // Handle the results here (response.result has the parsed body).
                console.log("Response", response);
              },
              function(err) { console.error("Execute error", err); });
      }

      /**
       * Append a pre element to the body containing the given message
       * as its text node. Used to display the results of the API call.
       *
       * @param {string} message Text to be placed in pre element.
       */
      function appendPre(message) {
        var pre = document.getElementById('content');
        var textContent = document.createTextNode(message + '\n');
        pre.appendChild(textContent);
      }
    </script>

    <script async defer src="https://apis.google.com/js/api.js"
      onload="this.onload=function(){};handleClientLoad()"
      onreadystatechange="if (this.readyState === 'complete') this.onload()">
    </script>
  </body>
</html>

人员API快速入门
人员API快速入门

授权 退出 建立联系 //来自开发人员控制台的客户端ID和API密钥 var CLIENT_ID=“<您的客户ID在这里!>”; var API_KEY='<您的API KEY在这里!>'; //quickstart使用的API的API发现文档URL数组 var DISCOVERY_DOCS=[”https://www.googleapis.com/discovery/v1/apis/people/v1/rest"]; //API要求的授权范围;可以使用多个作用域 //包含,用空格分隔。 变量作用域=”https://www.googleapis.com/auth/contacts"; var authorizeButton=document.getElementById('authorizen_按钮'); var signburatton=document.getElementById('signout_按钮'); var contactButton=document.getElementById('contact_button'); /** *加载时,调用以加载auth2库和API客户端库。 */ 函数handleClientLoad(){ load('client:auth2',initClient); } /** *初始化API客户端库并设置登录状态 *听众。 */ 函数initClient(){ gapi.client.init({ API密钥:API_密钥, clientId:客户端ID, 发现文档:发现文档, 范围:范围 }).然后(函数(){ //侦听登录状态的更改。 gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus); //处理初始登录状态。 更新信号状态(gapi.au)
begin:vcard
version:3.0
prodid:Microsoft-MacOutlook/10.15.0.190117
UID:<uid string>
fn;charset=utf-8:<first> <last>
n;charset=utf-8:<last>;<first>;;;
title;charset=utf-8:<title>
office;charset=utf-8:<location>
note;charset=utf-8: 
adr;charset=utf-8;type=work;type=pref:;;;;;;<country>
label;charset=utf-8;type=work;type=pref:<country>
tel;charset=utf-8;type=cell:<mobile>
email;charset=utf-8;type=internet;type=pref;type=work:<email address>
end:vcard