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

Add to Contacts like Add to Calendar button/ html/ Ajax option

我想为网页开发一个 "Add to contacts" 按钮,很像您在网络研讨会和活动页面上看到的 "add to calendar - Google, ICal, Outlook" 类型按钮 like this one

我开始调查 Google 联系人,因为我正在使用它。 我开始构建一个表单,向他们在 the help files here and a similar question for .

中谈论的 URL 提交 application/atom+xml

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

我的粗略代码不起作用






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



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

哦,顺便说一句,作为用户进行身份验证时 google 会抱怨它在我的小网站和您的本地版本上都不安全,只需单击高级并继续。 (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。

在左侧,我们有请求 body,它让我们可以将详细信息放入 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代码
  • url内.signIn({scope: "https://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 变量是您在完成快速入门页面上的步骤后输入密钥的地方。

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

这是我的 github:GitHub 你只需要注意 index.html php 这样我就可以建立小测试网站了给你看。

Google API 再次来袭!

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

如果您使用 Outlook 并转到您的联系人,然后右键单击一个联系人并说转发为 vCard,然后将其保存到您的桌面,您可以在类似于 Mac 上的 TextEdit 或 Windows 机器上的记事本或 Notepad++。 您会看到它具有标准格式:

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

如果您在此基础上工作,您将能够毫无问题地下载这样的文件。这是一个Wiki link