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

标签 javascript outlook addressbook google-contacts-api

我想为网页开发一个“添加到联系人”按钮,很像您在网络研讨会和事件页面上看到的“添加到日历 - Google、ICal、Outlook”类型的按钮 like this one .

当我使用它时,我开始研究 Google 通讯录。 我开始构建一个表单,将 application/atom+xml 提交到他们在 the help files here 中讨论的 URL。和 Google on Stack 的类似问题.

我认为创建它是一种类似开源的社区服务,在我修改它时,一些专家的帮助将不胜感激。我在这里请求捐款。

我的粗略代码,行不通






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



最佳答案

证据就在布丁里,所以在你折磨自己之前阅读这篇长篇文章:Create Contacts Test Site开始工作 :) 如果您打开了 webtool 的控制台,您可以看到我们取回了联系人资源,Elizabeth Bennet 现在将出现在您的联系人中!

哦,顺便说一下,当以用户身份进行身份验证时,google 会提示它在我的小网站和您的本地版本上都不安全,只需单击高级并继续。 (谷歌会这样做,直到你提交你的 OAuth 以供他们的团队在最终产品上很好地验证但是......)

所以在 google help docs 在最上面我们看到了这个:

Note: For read and write access to users' contacts, use the People API, which provides both contact and profile information using JSON instead of the older GData protocol.

所以看起来这里的正确答案确实是移动到 People API .我花了一些时间研究它并粗略地回答了你。

我找到了 this example页面可以解决您想要的大部分内容。如果你完全按照它去做,你会得到一个本地版本,使用 javascript 连接到他们的 api,这允许我们创建联系人。

我们必须在 google 的 api 中设置一个 api 应用程序来从本质上验证这个过程。

完成后,我们可以设置请求用户接受身份验证的按钮(允许我们为他们创建联系人)。

有趣的是更改他们的代码,这只是将页面上用户的前 10 个用户放入创建联系人中。

确实有一些方法可以在获得用户许可后直接使用常规 http 请求来完成,但我发现使用他们的 crazy api setup 会更快.

我们需要知道如何设置 gapi.client.people.people.createContact api 调用,它需要 Person resource .该资源可以方便地单击以查看我们如何设置人员资源类别。

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

Try this 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: "https://www.googleapis.com/auth/contacts"}) 中的 url>

该范围基本上告诉 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 变量是您在完成快速入门页面上的步骤后放入 key 的地方。

很明显按钮和工作方式可以改变,但这只是为了证明它有效:P

这是我的 github:GitHub您只需要注意 php 的 index.html,这样我就可以建立一个小测试网站来向您展示。

Google API 再次出击!

希望对你有帮助,有什么问题可以私信我!

关于javascript - 添加到联系人,例如添加到日历按钮/html/Ajax 选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53069117/

相关文章:

android - 从 HTML 网页向移动设备地址簿添加联系人

javascript - 我的 cron 作业始终包含相同的标记值

java - 更改模糊事件输入文本字段的最大长度

outlook - 我应该如何使用 Outlook 发送代码片段?

iphone - 代码在添加电话联系人查询时崩溃

ios - 从地址簿中获取两个文本字段的电话号码

javascript - 只发送一次 Ajax 请求

javascript - 语法错误: Missing catch or finally after try with ytdl-core

oauth-2.0 - 如何使用 OAuth2 通过 IMAP 连接到 outlook.office365.com

java - 如何使用java从outlook打开附加文档?