Home  >  Article  >  WeChat Applet  >  WeChat public platform develops web pages to obtain user geographical location

WeChat public platform develops web pages to obtain user geographical location

高洛峰
高洛峰Original
2017-02-28 10:11:113844browse

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

Successfully returns the following JSON:

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

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

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

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

0f9de62fce790f9a083d5c99e95740ceb90c27ed

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['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 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 expire_time 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 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;
  }
}

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();
?>

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>

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: '<?php  echo $signPackage["appId"];?>',
    timestamp: <?php  echo $signPackage["timestamp"];?>,
    nonceStr: '<?php  echo $signPackage["nonceStr"];?>',
    signature: '<?php  echo $signPackage["signature"];?>',
    jsApiList: [        // 所有要调用的 API 都要加到这个列表中
        'checkJsApi',        'openLocation',        'getLocation'
      ]
});

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 () {
});

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

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

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('用户拒绝授权获取地理位置');
    }
});

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!

Statement:
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