1. 程式人生 > >PHP TP模板下的微信登入(PC)

PHP TP模板下的微信登入(PC)

1.微信開發者賬號的申請就不說,企業級;官網域名回跳地址。(微信開放平臺APPID)

      還有注意點:很多應用是放在微信公眾號中的,此地微信登入是:微信公眾平臺APPID

2.請求程式碼構

<?php

class ui_login_weixin_login extends ui
{

    public function __construct()
    {
        parent::__construct();
        //當前由使用者
        if (empty($this->uid)) {
            $biz_weixin_loginapi = new biz_weixin_loginapi();
            $weixin_login_url = $biz_weixin_loginapi->get_url_code();
            //請求到位址列
            header('location:' . $weixin_login_url);
        } else {
            header('location:' . WWW_DOMAIN);
        }
    }
}
public function get_url_code(){
		$url = self::WEIXIN_URL;
	    //回撥地址
		$code_redirect_uri = urlencode(self::CODE_REDIRECT_URI); // self::CODE_REDIRECT_URI 回撥地址需要urlencode ;
		
		$state = md5(uniqid(mt_rand(), true));
		$_SESSION['weixin_login_state'] = $state;
		//請求地址
		$url .= 'connect/qrconnect?appid='.self::APPID.'&redirect_uri='.$code_redirect_uri.'&response_type=code&scope=snsapi_login&state='.$state.'#wechat_redirect';
		return $url;
	}

這兩部程式碼即可完成對微信的請求

2.編寫回調程式碼:

步驟:

2.1  判斷是不是有返回值;

2.2  獲取access_token open_id;

2.3  獲取微信使用者資訊;

2.4  檢驗微信token是否有效;

2.5  根據unionid查詢查詢本地 是否有資料 有得話,執行本地登入方法,成功或者失敗 ;

2.6  沒有得話 寫入weixin_login user 表各一份資料 微信登陸表 使用者表,執行本地登入方法,成功或者失敗;

<?php

class ui_login_weixin_logincallback extends ui
{

    public function __construct($S, $param)
    {
        parent::__construct();
        
        // 如果已登陸 跳轉到首頁
        if (! empty($this->uid)) {
            header('location:' . WWW_DOMAIN);
            return null;
        }
        $header = loadMod('glob/header');
        $footer = loadMod('glob/footer');
        $S->assign('header', $header);
        $S->assign('footer', $footer);
        
        $info = $this->login_callback($param['code'], $param['state']);
        $S->assign('info', $info);
    }

    /**
     * 微信登陸掃碼後 訪問得方法
     */
    protected function login_callback($code, $state)
    {
        
        // 如果返回值無code 或者state不對 跳轉到首頁
        if (empty($code) || $state !== $_SESSION['weixin_login_state']) {
            return array(
                'title' => '登陸失敗,請重新嘗試!',
                'url' => '/',
                'sec' => 5,
                'msg' => 'alert'
            );
        }
        
        // 獲取access_token open_id
        $biz_weixin_loginapi = new biz_weixin_loginapi();
        $result_access_token = $biz_weixin_loginapi->get_access_token($code);
        if ($result_access_token['msg'] !== 'success') {
            return array(
                'title' => '登陸失敗,請重新嘗試!',
                'url' => '/',
                'sec' => 5,
                'msg' => 'alert'
            );
        }
        
        $access_token = $result_access_token['data']['access_token'];
        $open_id = $result_access_token['data']['openid'];
        // 獲取使用者資訊
        $result_user_info = $biz_weixin_loginapi->get_user_info($access_token, $open_id);
        if ($result_user_info['msg'] !== 'success' || empty($result_user_info['data']['unionid'])) {
            return array(
                'title' => '登陸失敗,請重新嘗試!',
                'url' => '/',
                'sec' => 5,
                'msg' => 'alert'
            );
        }
        
        // 檢驗token是否有效
        $check_token_res = $biz_weixin_loginapi->check_token($access_token, $open_id);
        
        if ($check_token_res['msg'] !== 'success') {
            return array(
                'title' => '登陸失敗,請重新嘗試!',
                'url' => '/',
                'sec' => 5,
                'msg' => 'alert'
            );
        }
        
        // 登陸成功 根據unionid查詢weixin_login user 是否有資料 有得話 直接讀取 沒有得話
        
        $biz_login_weixin = new biz_login_weixin();
        $user_id = $biz_login_weixin->get_userid_by_weixin_unionid($result_user_info['data']['unionid']);
        
        if (is_id($user_id['data'])) {
            $biz_login = new biz_login();
            $biz_login->login($user_id['data'], 'is_login');
            return array(
                'title' => '登陸成功!',
                'url' => '/home/welcome',
                'sec' => 3,
                'msg' => 'success'
            );
        }
        
        // 沒有得話 寫入weixin_login user 表各一份資料 微信登陸表 使用者表
        
        $openid = $result_user_info['data']['openid'];
        $nickname = $result_user_info['data']['nickname'];
        $sex = $result_user_info['data']['sex'];
        $language = $result_user_info['data']['language'];
        $city = $result_user_info['data']['city'];
        $province = $result_user_info['data']['province'];
        $country = $result_user_info['data']['country'];
        $headimgurl = $result_user_info['data']['headimgurl'];
        $unionid = $result_user_info['data']['unionid'];
        
        $insert_res = $biz_login_weixin->add_weixin($openid, $nickname, $sex, $language, $city, $province, $country, $headimgurl, $unionid);
        
        if ($insert_res['msg'] !== 'success' || ! is_id($insert_res['data']['user_id'])) {
            return array(
                'title' => '登陸失敗,請重新嘗試!',
                'url' => '/',
                'sec' => 5,
                'msg' => 'alert'
            );
        }
        $biz_login = new biz_login();
        $biz_login->login($insert_res['data']['user_id'], 'is_login');
        return array(
            'title' => '登陸成功!',
            'url' => '/home/welcome',
            'sec' => 3,
            'msg' => 'success'
        );
    }
}

public function get_access_token($code, $type = 1){
		
		if(empty($code))
		{
			return array('msg' => 'code_error');
		}
		$url = self::API_URL;
		if($type === 1)
		{
			$appid = self::APPID;
			$secret = self::APP_SECRET;
		}else{
			$appid = self::APPID_GZ;
			$secret = self::APP_SECRET_GZ;
		}
		$url .= 'sns/oauth2/access_token?appid='.$appid.'&secret='.$secret.'&code='.$code.'&grant_type=authorization_code';
		//獲取access_token
		$res_json = runCurl($url);
		if(!$res_json)
		{
			return array('msg' => 'runCurl_error');	
		}
		$res_arr = json_decode($res_json, true);
		
		if(isset($res_arr['errcode']))
		{
			return array('msg' => $res_arr['errmsg']);
		}
		
		return array('msg' => 'success', 'data' => $res_arr);
	}

public function get_user_info($access_token, $open_id){
		if(empty($access_token) || empty($open_id))
		{
			return array('msg' => 'empty_token_or_openid');
		}
		
		$url = self::API_URL;
		$url .= 'sns/userinfo?access_token='.$access_token.'&openid='.$open_id;
		
		$res_json = runCurl($url);
		if(!$res_json)
		{
			return array('msg' => 'runCurl_error');
		}
		
		$res_arr = json_decode($res_json, true);
		
		if(isset($res_arr['errcode']))
		{
			return array('msg' => $res_arr['errmsg']);
		}
		return array('msg' => 'success', 'data' => $res_arr);
		
		
	}

public function check_token($access_token, $open_id){
		if(empty($access_token) || empty($open_id))
		{
			return array('msg' => 'empty_token_or_openid');
		}
		
		$url = self::API_URL;
		$url .= 'sns/auth?access_token='.$access_token.'&openid='.$open_id;
		$res_json = runCurl($url);
		if(!$res_json)
		{
			return array('msg' => 'runCurl_error');
		}
		
		$res_arr = json_decode($res_json, true);
		
		if( $res_arr['errcode'] !== 0 )
		{
			return array('msg' => $res_arr['errmsg']);
		}
		
		return array('msg' => 'success');
	}