1. 程式人生 > >php微信網頁開發實現自動登入註冊功能例項

php微信網頁開發實現自動登入註冊功能例項

功能:自動登入註冊功能
描述:php實現微信網頁自動登入註冊功能
範圍:適用於所有php版本

thinkphp5.0例項

$token = cookie('token');
if($token){
	//這裡寫登入後的邏輯
 }else{
            $code = isset($_REQUEST['code'])?$_REQUEST['code']:'';
            if($code){
            //自動登入
            $appId = sysconf('wechat_appid');
            $appSecret = sysconf('wechat_appsecret');
            $code =input('get.code');
            $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appId&secret=$appSecret&code={$code}&grant_type=authorization_code";
            $a = file_get_contents($url);
            $json= json_decode($a,true);

                if(isset($json['openid'])){
                    $openid = $json['openid'];
                    $url ="https://api.weixin.qq.com/sns/userinfo?access_token=".$json['access_token']."&openid=".$json['openid'];
                    $a = file_get_contents($url);
                    $json = (array)json_decode($a);
                    $nickname = $json['nickname'];
                    $headimgurl = $json['headimgurl'];
                    // 追加使用者資訊(如:openid、暱稱、頭像等)地址引數跳回前端頁面
                    if($openid){
                        $data = [
                            'name'=>removeEmoji($nickname),
                            'openid'=>$openid,
                            'head'=>$headimgurl,
                            'token'=>echo_token(removeEmoji($nickname),'',time()),
                            'login_at'=>date('Y-m-d H:i:s'),
                            'status'=>'1',
                            'password'=>'',
                            'money'=>0.00,
                            'cid'=>4
                        ];
                        $token = db('web_user')->where(['openid'=>$data['openid']])->value('token');
                        if(!$token){
                            db('web_user')->insert($data);
                        }else{
                            db('web_user')->where(['openid'=>$data['openid']])->update(['token'=>$data['token'],'login_at'=>date('Y-m-d H:i:s'),'login_num'=>['exp','login_num+1']]);
                        }

                        cookie('token',$data['token']);
                        cookie('openid',$openid);
                        cookie('appid',$appId);
                    }
                }
            }else{

                $redirect_uri="http://" . $_SERVER['HTTP_HOST'] . "?u=".$u."&stu=1";  //http://www.youqiong.net/ " . $_SERVER['SERVER_NAME'] . "  " . $_SERVER['HTTP_HOST'] . "
                $redirect_uri=urlencode($redirect_uri);
                $url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appId."&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_userinfo&state=''#wechat_redirect";
                header("location:".$url."");
                die;
            }


        }

注:原生開發替換掉sql和thinkphp 相關的自帶助手函式,用上原生的方式即可。