微信公衆號 登錄

<?php
namespace app\wechat\controller;
use think\Controller;
use think\Db;
class Wechatlogin extends Controller
{


    public $appId="";
    public $appSecret="";
    public function  __construct(){
        $this->appId = 'wx14e0dda14dccccce';
        $this->appSecret= 'fa19faf02f6cff794953a14fe0b219b5';

    }
    /**
     * 首先調用這個方法
     */
    public function relate()
    {
        $appid = $this->appId;
        //重定向地址
        $redirect_uri = urlencode('http://jmbj.zhangtongdongli.com/wechat/wechatlogin/getUserOpenId');

        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";

        header("Location:".$url);exit;
    }
    public function getUserOpenId(){
        
        $code=$_GET['code'];
        session("code",$code);
        $url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$this->appId."&secret=".$this->appSecret."&code=".$code."&grant_type=authorization_code";
        //3.拉取用戶的openid
        $res = $this->http_curl($url);
        $data = json_decode($res,true);
        if(!empty($data['access_token'])){
            $url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$data['access_token']."&openid=".$data['openid']."&lang=zh_CN&connect_redirect=1";
            $userInfo = $this->http_curl($url);
            $userInfo=json_decode($userInfo,true);
            $openid=$data['openid']?$data['openid']:'';
            
            if(!empty($userInfo) && !empty($openid)){
            	$nickname=isset($userInfo['nickname']) ?$userInfo['nickname'] : '普通用戶';
                //保存用戶信息
                $user_data=['nick_name'=>$this->filterNickname($nickname),
                    'sex'=>isset($userInfo['sex'])?$userInfo['sex']:2,
                    'last_login'=>time(),
                    'openid'=>$openid,
                    'avatar'=>isset($userInfo['headimgurl'])?$userInfo['headimgurl']:'',
                    'applet_thr_session'=>md5($openid)
                ];
                
                $users=Db::table("users")->where("openid = '".$openid."' and openid is not null")->find();
                
                if(!empty($users)){
                    //更新數據
                    Db::table('users')->where("openid = '".$openid."' and openid is not null")->update($user_data);
                }else{
                    //添加數據
                    $user_data['reg_time']=time();
                    $add=Db::table('users')->insert($user_data);
                    
                }
            }
            header("Location:http://jimaobj.zhangtongdongli.com/");exit;
        }else{
            header("Location:http://jmbj.zhangtongdongli.com/wechat/Wechatlogin/relate");exit;
        }
    }
    function filterNickname($nickname)
 
{
    $nickname = preg_replace('/[\x{1F600}-\x{1F64F}]/u', '', $nickname);
 
    $nickname = preg_replace('/[\x{1F300}-\x{1F5FF}]/u', '', $nickname);
 
    $nickname = preg_replace('/[\x{1F680}-\x{1F6FF}]/u', '', $nickname);
 
    $nickname = preg_replace('/[\x{2600}-\x{26FF}]/u', '', $nickname);
 
    $nickname = preg_replace('/[\x{2700}-\x{27BF}]/u', '', $nickname);
 
    $nickname = str_replace(array('"','\''), '', $nickname);
 
    return addslashes(trim($nickname));
}
    public function http_curl($url){
        $curl = curl_init();
        //設置抓取的url
        curl_setopt($curl, CURLOPT_URL, $url);
        //設置頭文件的信息作爲數據流輸出
        curl_setopt($curl, CURLOPT_HEADER, 0);
        //設置獲取的信息以文件流的形式返回,而不是直接輸出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //執行命令
        $data = curl_exec($curl);
        //關閉URL請求
        curl_close($curl);
        //顯示獲得的數據
        return $data;
    }
    public function valid(){
        $echoStr = $_GET["echostr"];
        //valid signature , option
        if($this->checkSignature()){
            echo $echoStr;
            exit;
        }
    }


    private function checkSignature(){
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }

    }

}

getUserOpenId方法就是獲取用戶信息並保存到數據庫中,有問題私信

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章