微信公众号地理位置——2018年6月5日

2018年06月05日 19:46:01阅读数:1038博客 / 沈斌的博客 / php

微信公众号 地理位置,使用jssdk

  1. 配置jssdk 的域名,view 中html引入js文件

  2. 配置wx.config

  3. 通过wx.ready处理成功的情况

application\index\controller\Weixin.php

实例

<?php
namespace app\index\controller;
use think\Controller;
use think\facade\Cache;
class Weixin extends Controller
{
    public function __construct(){
        parent::__construct();
        $this->model=model('Weixin');
    }
    public function index()
    {

        $valid=$this->model->valid();

        if(!$valid){
            exit('signature error');
        }
        $xmldata=file_get_contents("php://input");
        file_put_contents('D://subs.txt',$xmldata);




        /*
        $xmldata='<xml><ToUserName><![CDATA[gh_f10a1709655b]]></ToUserName>
            <FromUserName><![CDATA[o9i9i0TUiPy3hlFgcVk2lswL9T_U]]></FromUserName>
            <CreateTime>1527982562</CreateTime>
            <MsgType><![CDATA[event]]></MsgType>
            <Event><![CDATA[subscribe]]></Event>
            <EventKey><![CDATA[]]></EventKey>
            </xml>';

        */
        // xml transfer object
        $postObj=simplexml_load_string($xmldata,'SimpleXMLElement',LIBXML_NOCDATA);
        $data=(array)$postObj;

        // dump($data['FromUserName']);
        if(isset($data['MsgType']) && $data['MsgType'] == 'event'){
            //subscribe
            if($data['Event'] == 'subscribe'){
                $this->model->subscribe($data);
                return 'subscribe ok';
            }

            //unsubscribe
            if($data['Event'] == 'unsubscribe'){
                $this->model->unsubscribe($data);
                return 'unsubscribe ok';
            }
        }
        // exit('');
    }

    public function get_access_token($iscache=true){
        $cache_key='access_token';
        if(!$iscache){
            Cache::rm($cache_key);
        }
        $data=Cache::get($cache_key);
        if($data && $iscache){
            return $data;
        }


        $appid=config('app.appid');
        $appsecret=config('app.APPSECRET');
        $url='https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$appsecret;
        $res=http_Get($url);
        // dump($res);
        $res=json_decode($res,true);
        // dump($res);
        if(!isset($res[$cache_key])){
            return false;
        }
        Cache::set($cache_key,$res['access_token'],($res['expires_in']-600));

        return $res[$cache_key];
    }

    public function custom_menu(){
        $access_token=$this->get_access_token();
        if(!$access_token){
            exit('access_token get failed');
        }
        $url='https://api.weixin.qq.com/cgi-bin/menu/create?access_token='.$access_token;
        $data = '{
                    "button":[
                        {
                            "type":"view",
                            "name":"Home",
                            "url":"http://scottshen.top/"
                        },
                        {
                            "type":"view",
                            "name":"视频教程",
                            "url":"http://www.baidu.com"
                        },
                        {
                            "name":"用户info",
                            "sub_button":[
                                {
                                    "type":"view",
                                    "name":"用户信息",
                                    "url":"http://881c65b6.ngrok.io/index.php/index/weixin/auth"
                                },
                                {
                                   "type":"view",
                                   "name":"用户地理位置",
                                   "url":"http://881c65b6.ngrok.io/index.php/index/weixin/location"
                                }]
                        }]
                }';

        $res=http_Post($url,$data);
        dump($res);

    }

    public function auth(){
        // halt(config('app.APPID'));
        $appid=config('app.appid');
        $redirect='http://881c65b6.ngrok.io/index.php/index/weixin/userinfo';
        $url_code = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri='.urlEncode($redirect)
        .'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';


        header('Location:'.$url_code);

    }

    public function userinfo(){
        // dump(config('app.APPID'));
        $code=input('get.code');
        // dump($code);
        $res=$this->model->auth_access_token($code);
        // dump($res);

        $auth_access_token=$res['access_token'];
        $openid=$res['openid'];
        // dump($auth_access_token);
        $userinfo=$this->model->get_userinfo($auth_access_token,$openid);
        dump($userinfo);

    }

    public function location(){
        $data['appid']=config('app.appid');
        $data['timestamp']=time();
        $data['nonceStr']=md5(time().rand(1,999));

        //生成签名
        $access_token=$this->get_access_token();
        $jsapi_ticket=$this->model->jsapi_ticket($access_token);


        //签名字符串
        //noncestr s小写,查了好久这个问题,报invalid signature,
        //拼接字符串是noncestr
        $parmas['noncestr']=$data['nonceStr'];
        $parmas['jsapi_ticket']=$jsapi_ticket;
        $parmas['timestamp']=$data['timestamp'];

        $parmas['url']="http://881c65b6.ngrok.io/index.php/index/weixin/location";
        ksort($parmas,SORT_STRING);
        // dump($parmas);
        $str=urldecode(http_build_query($parmas));
        //生成签名
        $data['signature']=sha1($str);
        // dump(sha1($str));
        // dump($data['signature']);


        return $this->fetch('',$data);

    }

}

运行实例 »

点击 "运行实例" 按钮查看在线实例

application\index\model\Weixin.php

实例

<?php
namespace app\index\model;
use think\Model;
use think\Db;
use think\facade\Cache;

class Weixin extends Model
{
    public function valid()
    {
        $signature=input('get.signature');
        // $signature='c5052967c11f8d7e59c3b4011407b94c697b1ceb';
        // var_dump($signature);
        $timestamp=input('get.timestamp');
        // $timestamp='1527896867';

        $nonce=input('get.nonce');
        // $nonce='3010175004';

        $echostr=input('get.echostr');
        // $echostr='9044276551450221539';
        $token=config('app.token');

        file_put_contents('d://data.txt','signature='.$signature.' timestmp='.$timestamp.' nonce='.$nonce.' echostr='.$echostr);
        $tmpArr=array($timestamp,$nonce,$token);
        sort($tmpArr,SORT_STRING);

        // dump($tmpArr);
        $tmpStr=implode($tmpArr);
        // echo $tmpStr;
        // $tmpStr=sha1($tmpStr);
        //
        if(sha1($tmpStr) != $signature){
            // exit('error');
            return false;
        }
        // 首次接入成功需要输出$echostr
        // exit($echostr);

        return true;
    }
    //网页授权access_tonken
    public function auth_access_token($code){
        $appid=config('app.appid');
        $appsecret=config('app.APPSECRET');
        $url='https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.
        $appsecret.'&code='.$code.'&grant_type=authorization_code';

        $res=http_Get($url);
        $res=json_decode($res,true);

        if(!isset($res['access_token'])){
            return false;
        }

        return $res;
    }

    public function get_userinfo($auth_access_token,$openid){
        $url='https://api.weixin.qq.com/sns/userinfo?access_token='.
            $auth_access_token.'&openid='.
            $openid.'&lang=zh_CN';
        $res=http_Get($url);
        $res=json_decode($res,true);
        return $res;
    }

    public function subscribe($data){
        dump($data['FromUserName']);
        $user=Db::table('wechat')
            ->where('openid',$data['FromUserName'])
            ->find();
        // halt($user);
        // 新关注用户
        if(!$user){
            $data=['openid'=>$data['FromUserName'],
                    'sub_status'=>1,
                    'add_time'=>time(),
            ];
            Db::table('wechat')
                ->insertGetId($data);

        } else {
            Db::table('wechat')
                ->where('openid',$data['FromUserName'])
                ->update(['sub_status'=>1]);
        }
    }

    public function unsubscribe(){
        Db:table('wechat')
            ->where('openid',$data['FromUserName'])
            ->update(['sub_status'=>0]);
    }
    // 获取jsai_ticket
    public function jsapi_ticket($access_token,$iscache=true){
        $key='jsapi_ticket';
        if(!$iscache){
            Cache::rm($key);
        }

        $data=Cache::get($key);
        if($data && $iscache){
            return $data;
        }

        $appid=config('app.appid');
        $appsecret=config('app.APPSECRET');
        $url='https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='.
            $access_token.'&type=jsapi';

        $res=http_Get($url);
        $res=json_decode($res,true);
        if(!isset($res['ticket'])){
            return false;
        }

        Cache::set($key,$res['ticket'],$res['expires_in']-100);
        return $res['ticket'];
    }


}

运行实例 »

点击 "运行实例" 按钮查看在线实例

application\index\view\weixin\location.html

实例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>location</title>
    <script type="text/javascript" src="//res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
</head>
<body>

</body>
</html>
<script type="text/javascript">
    wx.config({
        debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
        appId: '{$appid}', // 必填,公众号的唯一标识
        timestamp: {$timestamp}, // 必填,生成签名的时间戳
        nonceStr: '{$nonceStr}', // 必填,生成签名的随机串
        signature: '{$signature}',// 必填,签名
        jsApiList: ['getLocation','openLocation'] // 必填,需要使用的JS接口列表
    });

    wx.ready(function(){
        getLocation(openLocation);
    })

    function getLocation(callback){
        wx.getLocation({
            type: 'gcj02', // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02'
            success: function (res) {
                var latitude = res.latitude; // 纬度,浮点数,范围为90 ~ -90
                var longitude = res.longitude; // 经度,浮点数,范围为180 ~ -180。
                var speed = res.speed; // 速度,以米/每秒计
                var accuracy = res.accuracy; // 位置精度
                if(callback != undefined){
                    callback(res);
                }
            }
        });
    }

    function openLocation(res){
        wx.openLocation({
            latitude: res.latitude, // 纬度,浮点数,范围为90 ~ -90
            longitude: res.longitude, // 经度,浮点数,范围为180 ~ -180。
            name: '', // 位置名
            address: '', // 地址详情说明
            scale: 20, // 地图缩放级别,整形值,范围从1~28。默认为最大
            infoUrl: '' // 在查看位置界面底部显示的超链接,可点击跳转
        });
    }


</script>

运行实例 »

点击 "运行实例" 按钮查看在线实例

通过alert提示配置成功,显示wx.getLocation $res 信息,openLocation调用ok,最后显示地图中的定位

批改状态:合格

老师批语:

版权申明:本博文版权归博主所有,转载请注明地址!如有侵权、违法,请联系admin@php.cn举报处理!

全部评论

文明上网理性发言,请遵守新闻评论服务协议

条评论
  • 博主信息
    沈斌的博客
    博文
    56
    粉丝
    3
    评论
    1
    访问量
    42423
    积分:0
    P豆:417