通过微信网页获取用户经纬度实现定位
简单记录下
流程
前端
- 通过API获取appId,nonceStr,timestamp,signature。
- 配置wx.config,在ready执行即可
后端
- 获取AccessToken 获取到之后要存起来,防止频繁调用,过期之后再重新获取
- 获取getJsApiTicket 获取到之后要存起来,防止频繁调用,过期之后再重新获取
- 计算生成SignPackage
过程坑
- 微信平台要设置白名单ip 获取token等必须设置白名单IP。
- 生成SignPackage的url必须是js调用页面的url,也就是wx.config那个前端页面的url
- 微信平台要设置那个什么安全调用JS,不然无法调用
代码
后端生成SignPackage
根据官方的demo。自己修改过,tp6缓存替换文件存储,命名空间自己注意
<?php
namespace app\admin\lib;
use think\facade\Cache;
class Wechat
{
private $appId;
private $appSecret;
private $url;
public function __construct($appId, $appSecret, $url = '')
{
$this->url = $url;
$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 = $this->url ?: $_SERVER['REQUEST_URI'];
$url = "$protocol$_SERVER[HTTP_HOST]$url";
$timestamp = time();
$nonceStr = $this->createNonceStr();
// 这里参数的顺序要按照 key 值 ASCII 码升序排序
$string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr×tamp=$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()
{
$data = json_decode($this->get_php_file("jsapi_ticket.php"));
if ($data->expire_time > time()) {
return $data->jsapi_ticket;
}
$accessToken = $this->getAccessToken();
$url = "https://api2.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;
$this->set_php_file("jsapi_ticket.php", json_encode($data));
}
return $ticket;
}
private function getAccessToken()
{
$data = json_decode($this->get_php_file("access_token.php"));
if ($data->expire_time > time()) {
return $data->access_token;
}
$url = "https://api2.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;
$this->set_php_file("access_token.php", json_encode($data));
}
return $access_token;
}
private function httpGet($url)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 500);
// 为保证第三方服务器与微信服务器之间数据传输的安全性,所有微信接口采用https方式调用,必须使用下面2行代码打开ssl安全校验。
// 如果在部署过程中代码在此处验证失败,请到 http://curl.haxx.se/ca/cacert.pem 下载新的证书判别文件。
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;
}
private function get_php_file($filename)
{
return Cache::get($filename, '{"jsapi_ticket":"","access_token":"","expire_time":0}');
}
private function set_php_file($filename, $content)
{
Cache::set($filename, $content);
}
}
调用
$we_chat = new Wechat("id", "秘钥",'/admin/users/maph5.html(这里是前端调用页面的url)');
$signPackage = $we_chat->getSignPackage();
return json(['code'=>1,'msg'=>'获取数据成功','data'=>$signPackage]);
前端简单实现
获取定位并打开地图标点定位
<html>
<head>
<meta charset="utf-8">
<title>定位</title>
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<script src="/js/axios/axios.min.js" charset="utf-8"></script>
<script src="http://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
</head>
<body>
<script>
let appId, timestamp, nonceStr, signature;
let latitude,longitude;
axios.get('/admin/ajax/get_wechat_api').then(({data}) => run(data))
let run = ({data}) => {
wx.config({
debug: false,
appId: data.appId,
timestamp: data.timestamp,
nonceStr: data.nonceStr,
signature: data.signature,
jsApiList: ['getLocation','openLocation']
});
wx.error(function (res) {
console.log(res);
});
wx.ready(function () {
wx.getLocation({
type: 'gcj02', // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02'
success: function (res) {
latitude = res.latitude; // 纬度,浮点数,范围为90 ~ -90
longitude = res.longitude; // 经度,浮点数,范围为180 ~ -180。
wx.openLocation({
latitude: latitude, // 纬度,浮点数,范围为90 ~ -90
longitude: longitude, // 经度,浮点数,范围为180 ~ -180。
name: '我的位置', // 位置名
address: '这是我的详细地址', // 地址详情说明
scale: 28, // 地图缩放级别,整型值,范围从1~28。默认为最大
infoUrl: 'https://www.baidu.com' // 在查看位置界面底部显示的超链接,可点击跳转(这个我这里好像没有用)
});
// var speed = res.speed; // 速度,以米/每秒计
// var accuracy = res.accuracy; // 位置精度
}
});
});
}
</script>
</body>
</html>