• 微信入口、生成菜单,公众号授权获取用户信息(unionid)


    本篇主要存储一次原来自己使用的微信公众号开发的一些小功能

    比较常用的为配置微信入口、生成菜单、已经授权登录获取用户信息一些小功能。

    不过,最好还是多看微信开发文档。文档地址:跳转微信开发文档

    不多说什么了,直接上代码:

    <?php
    namespace appindexcontroller;
    /**
     *微信接入类
     */
    use thinkController;
    
    define("TOKEN", "TOKEN");          #微信公众号 TOKEN
    
    class Wx  extends Controller
    {
        var $appid     = 'APPID';      #微信公众号appid
        var $appsecret = 'APPSECRET';  #微信公众号appsecret
    
        #微信入口验证
        public function valid()
        {
            $echoStr = isset($_GET["echostr"])?$_GET["echostr"]:null;
    
            if($this->checkSignature()){
                echo $echoStr;
                //exit;
            }
            // else{
            //     $this->responseMsg();
            // }
        }
    
        private function checkSignature()
        {
            $signature = $_GET["signature"];
            $timestamp = $_GET["timestamp"];
            $nonce = $_GET["nonce"];    
                    
            $token = TOKEN;
            $tmpArr = array($token, $timestamp, $nonce);
            sort($tmpArr, SORT_STRING);
            $tmpStr = implode( $tmpArr );
            $tmpStr = sha1( $tmpStr );
            
            if( $tmpStr == $signature ){
                return true;
            }else{
                return false;
            }
        }
    
        #获取 基础 Access_token  
        public function get_access_token()
        {
    #accestoken有7200秒时效,获取后请尽量找地方存储,不要每次调用每次获取
    #下面是我存储的accesstoken与失效时间,各位看官大大可以自由存储
    $accesstoken = getConfigValue('accesstoken'); $tokentime = getConfigValue('tokentime'); #如果token 的时间已经小于当前时间, 从新获取 if($tokentime < time()) { #获取配置参数 $appId = $this->appid; $appSecret = $this->appsecret; //获取access_token字符串 $tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appId."&secret=".$appSecret; // 如果是企业号用以下URL获取access_token // $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret"; $res = $this->https_request($tokenUrl); //提取access_token字符串 解析json字符串 $data = json_decode($res, true); #修改对应存储 model('config')->where('code','accesstoken')->update(['value'=>$data['access_token']]); model('config')->where('code','tokentime')->update(['value'=>time()+7000]); $tokens = $data['access_token']; }else{ $tokens = $accesstoken; } // return $data['access_token']; return $tokens; } #生成菜单 public function makeMenu() { $accessToken = $this->get_access_token(); // $url = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token='.$accessToken; $data = ' { "button":[ { "type": "view", "name": "单级菜单", "url": "对应路径" }, { "name":"多级菜单", "sub_button":[ { "type":"view", "name":"一级菜单", "url":"最多三个" }, { "type":"view", "name":"二级菜单", "url":"最多五个" } ] } ] }'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$accessToken); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)'); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_AUTOREFERER, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $tmpInfo = curl_exec($ch); if (curl_errno($ch)) { echo curl_error($ch); } curl_close($ch); echo $tmpInfo; } #授权第一步 获取code public function getReturn() { $appid = $this->appid; #回调地址 $redirect_uri = '回调路径'; #如果拼接字符串 $data = []; $data[0] = $_GET['state']; if(!empty($_GET['recode'])) { $data[1] = $_GET['recode']; } $state = implode(",",$data); #请求授权 $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=".$redirect_uri."response_type=code&scope=snsapi_userinfo&state=$state#wechat_redirect"; header("Location:$url"); die; } #授权登录 并获取授权用户信息 public function getUserCode() { $appid = $this->appid; $secret = $this->appsecret; $code = $_GET["code"]; #获取授权用户对应的openid $get_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$secret.'&code='.$code.'&grant_type=authorization_code'; $json_obj = json_decode(file_get_contents($get_token_url,true),true); #获取授权用户信息 $openid = $json_obj['openid']; // $access_token = $json_obj['access_token']; // $get_user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN'; $get_user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$json_obj['access_token'].'&openid='.$openid.'&lang=zh_CN'; #带有unionid 的授权用户信息 -- 带有unionid 必须用基础access_token 来获取 $accessToken = $this->get_access_token(); $get_user_info_url = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token='.$accessToken.'&openid='.$openid.'&lang=zh_CN'; #获得用户的信息 $user_obj = json_decode(file_get_contents($get_user_info_url,true),true); $res = explode(',', $_GET['state']); #对应用户的state[0] 来指定跳转的路径 $loginUrl = "重定向路径"; #根据openid 来查找对应的用户信息 #进行其他操作 #进行重定向 $this->redirect($loginUrl); } # request 请求 private function https_request($url, $data = null) { $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); if (!empty($data)){ curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $data); } curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec($curl); curl_close($curl); return $output; } }

    在刚开始微信开发的时候这个类库帮我不少。

    有需要的小伙伴可以借鉴。

    如有疑问可以留言

    大家共同进步哈。

    2020年04月21日

  • 相关阅读:
    GPU 版 TensorFlow failed to create cublas handle: CUBLAS_STATUS_ALLOC_FAILED
    Python -- 值转换为字符串的两种机制
    Python
    vim中注释多行python代码
    HTTP协议状态码详解(HTTP Status Code)
    关于Python报错:SyntaxError: Non-ASCII character 'xe5' in file的解决方法
    Linux如何查看进程、杀死进程、启动进程等常用命令
    vim 如何设置显示行号和缩进
    一、报错
    二、极光推送
  • 原文地址:https://www.cnblogs.com/YFYQ/p/12745367.html
Copyright © 2020-2023  润新知