WeChat public platform develops web pages to obtain user geographical location

高洛峰
Release: 2017-02-28 10:11:11
Original
3859 people have browsed it

In this WeChat public platform development tutorial, we will introduce how to obtain the user's geographical location information on the web page.

This article is divided into the following two parts:

  1. Generate JS-SDK permission verification signature

  2. Use the geographical location interface to obtain Coordinates

1. WeChat JS-SDK

1. Obtain Access Token

The method of obtaining access token is as follows Introduction, for details, see WeChat Public Platform Development (26) ACCESS TOKEN

2. Obtain jsapi_ticket

Before generating a signature, you must first understand jsapi_ticket. jsapi_ticket is a temporary tool used by public accounts to call the WeChat JS interface. bill. Under normal circumstances, the validity period of jsapi_ticket is 7200 seconds and is obtained through access_token. Since the number of api calls to obtain jsapi_ticket is very limited, frequent refreshes of jsapi_ticket will result in restricted api calls and affect their own business. Developers must cache jsapi_ticket globally in their own services.

Refer to the following documents to obtain access_token (validity period is 7200 seconds, developers must cache access_token globally in their own services):
Use the access_token obtained in the first step to request jsapi_ticket using http GET method (validity period is 7200 seconds) , developers must cache jsapi_ticket globally in their own services), the interface address is as follows

https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi
Copy after login

Successfully returns the following JSON:

{
    "errcode":0,
    "errmsg":"ok",
    "ticket":"bxLdikRXVbTPdHSM05e5u5sUoXNKd8-41ZO3MhKoyN5OfkWITDGgnr2fwJ0m9E8NYzWKVZvdVtaUgWvsdshFKA",
    "expires_in":7200
}
Copy after login

After obtaining jsapi_ticket, you can generate a signature for JS-SDK permission verification.

3. Signature algorithm implementation

The signature generation rules are as follows: fields participating in the signature include noncestr (random string), valid jsapi_ticket, timestamp (timestamp), url (URL of the current web page) , excluding # and its following parts). After sorting all the parameters to be signed according to the ASCII code of the field name from small to large (lexicographic order), use the URL key-value pair format (i.e. key1=value1&key2=value2...) to splice them into a string string1. It should be noted here that all parameter names are lowercase characters. Perform sha1 encryption on string1, use original values ​​for field names and field values, and do not perform URL escaping.

That is signature=sha1(string1). Example:

noncestr=Wm3WZYTPz0wzccnW
jsapi_ticket=sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg
timestamp=1414587457url=http://mp.weixin.qq.com?params=value
Copy after login

Step 1. Sort all the parameters to be signed according to the ASCII code of the field name from small to large (lexicographic order), and use the URL The format of the key-value pair (i.e. key1=value1&key2=value2...) is spliced ​​into a string string1:

jsapi_ticket=sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg&noncestr=Wm3WZYTPz0wzccnW&timestamp=1414587457&url=http://mp.weixin.qq.com?params=value
Copy after login

Step 2. Pair string1 Perform sha1 signature and get signature:

0f9de62fce790f9a083d5c99e95740ceb90c27ed
Copy after login

The complete code is as follows

<?php
class JSSDK {
  private $appId;
  private $appSecret;

  public function __construct($appId, $appSecret) {
    $this->appId = $appId;
    $this->appSecret = $appSecret;
  }

  public function getSignPackage() {
    $jsapiTicket = $this->getJsApiTicket();

    // 注意 URL 一定要动态获取,不能 hardcode.
    $protocol = (!empty($_SERVER[&#39;HTTPS&#39;]) && $_SERVER[&#39;HTTPS&#39;] !== &#39;off&#39; || $_SERVER[&#39;SERVER_PORT&#39;] == 443) ? "https://" : "http://";
    $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

    $timestamp = time();
    $nonceStr = $this->createNonceStr();

    // 这里参数的顺序要按照 key 值 ASCII 码升序排序
    $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";

    $signature = sha1($string);

    $signPackage = array(
      "appId"     => $this->appId,
      "nonceStr"  => $nonceStr,
      "timestamp" => $timestamp,
      "url"       => $url,
      "signature" => $signature,
      "rawString" => $string
    );
    return $signPackage; 
  }

  private function createNonceStr($length = 16) {
    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    $str = "";
    for ($i = 0; $i < $length; $i++) {
      $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
    }
    return $str;
  }

  private function getJsApiTicket() {
    // jsapi_ticket 应该全局存储与更新,以下代码以写入到文件中做示例
    $data = json_decode(file_get_contents("jsapi_ticket.json"));
    if ($data->expire_time < time()) {
      $accessToken = $this->getAccessToken();
      // 如果是企业号用以下 URL 获取 ticket
      // $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
      $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
      $res = json_decode($this->httpGet($url));
      $ticket = $res->ticket;
      if ($ticket) {
        $data->expire_time = time() + 7000;
        $data->jsapi_ticket = $ticket;
        $fp = fopen("jsapi_ticket.json", "w");
        fwrite($fp, json_encode($data));
        fclose($fp);
      }
    } else {
      $ticket = $data->jsapi_ticket;
    }

    return $ticket;
  }

  private function getAccessToken() {
    // access_token 应该全局存储与更新,以下代码以写入到文件中做示例
    $data = json_decode(file_get_contents("access_token.json"));
    if ($data->expire_time < time()) {
      // 如果是企业号用以下URL获取access_token
      // $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret";
      $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret";
      $res = json_decode($this->httpGet($url));
      $access_token = $res->access_token;
      if ($access_token) {
        $data->expire_time = time() + 7000;
        $data->access_token = $access_token;
        $fp = fopen("access_token.json", "w");
        fwrite($fp, json_encode($data));
        fclose($fp);
      }
    } else {
      $access_token = $data->access_token;
    }
    return $access_token;
  }

  private function httpGet($url) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, 500);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_URL, $url);

    $res = curl_exec($curl);
    curl_close($curl);

    return $res;
  }
}
Copy after login

2. The web page obtains the geographical location coordinates

1. Bind the domain name

First log in to the WeChat public platform and enter the "Function Settings" of "Public Account Settings" to fill in " JS interface security domain name".

WeChat public platform develops web pages to obtain user geographical location

2. Get the signature package

<?php
require_once "jssdk.php";
$jssdk = new JSSDK("yourAppID", "yourAppSecret");
$signPackage = $jssdk->GetSignPackage();
?>
Copy after login

3. Import the JS file

Introduce the following JS file on the page that needs to call the JS interface (https is supported):

<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
Copy after login

4. Inject the permission verification configuration through the config interface

All pages that need to use JS-SDK must first inject configuration information, otherwise they will not be called.

 wx.config({
    debug: false,
    appId: &#39;<?php echo $signPackage["appId"];?>&#39;,
    timestamp: <?php echo $signPackage["timestamp"];?>,
    nonceStr: &#39;<?php echo $signPackage["nonceStr"];?>&#39;,
    signature: &#39;<?php echo $signPackage["signature"];?>&#39;,
    jsApiList: [        // 所有要调用的 API 都要加到这个列表中
        &#39;checkJsApi&#39;,        &#39;openLocation&#39;,        &#39;getLocation&#39;
      ]
});
Copy after login

5. Process successful verification through the ready interface

The geographical location needs to be called when the page is loaded, and the relevant interface needs to be placed in ready Called in the function to ensure correct execution

wx.ready(function () {
});
Copy after login

5.1 Use checkJsApi to determine whether the current client version supports the specified acquisition of geographical location

wx.checkJsApi({
    jsApiList: [
        &#39;getLocation&#39;
    ],
    success: function (res) {
        // alert(JSON.stringify(res));
        // alert(JSON.stringify(res.checkResult.getLocation));
        if (res.checkResult.getLocation == false) {
            alert(&#39;你的微信版本太低,不支持微信JS接口,请升级到最新的微信版本!&#39;);
            return;
        }
    }
});
Copy after login

5.2. Use the getLocation interface to obtain the geographical location coordinates

wx.getLocation({
    success: function (res) {
        var latitude = res.latitude; // 纬度,浮点数,范围为90 ~ -90
        var longitude = res.longitude; // 经度,浮点数,范围为180 ~ -180。
        var speed = res.speed; // 速度,以米/每秒计
        var accuracy = res.accuracy; // 位置精度
    },
    cancel: function (res) {
        alert(&#39;用户拒绝授权获取地理位置&#39;);
    }
});
Copy after login

3. Implementation effect

Pop-up request acquisition page

WeChat public platform develops web pages to obtain user geographical location

JS successfully obtains the geographical location parameter

WeChat public platform develops web pages to obtain user geographical location


For more articles related to WeChat public platform development webpage to obtain user geographical location, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template