<?php

namespace addons\weixin\controller;

use app\common\library\Auth;
use think\Config;
use addons\weixin\library\WechatService;
use app\admin\model\weixin\User as WechatUser;
use app\admin\model\User;
use think\Hook;
use think\Cookie;
use think\Session;
//注意表价了主键自增id uin取消主键
//微信需要加授权域名和ip白名单
/**
 * 微信公众号接口
 */
class Index extends \think\addons\Controller
{

    public $auth = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->auth = $auth = Auth::instance();

        //监听注册登录注销的事件
        Hook::add('user_login_successed', function ($user) use ($auth) {
            $expire = input('post.keeplogin') ? 30 * 86400 : 0;
            Cookie::set('uid', $user->id, $expire);
            Cookie::set('token', $auth->getToken(), $expire);
        });
    }

    /**
     * 微信公众号授权登录和jssdk分享演示
     * http://你的域名/addons/weixin
     */
    public function index()
    {
        //token
        $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
        //初始化
        $this->auth->init($token);
        //检测是否登录
        if (!$this->auth->isLogin()) {
            $this->login();
        }


        $wxModel = new \app\admin\model\weixin\Config();
        $wxConfigData = $wxModel->where([
            'group' => 'weixin', 'name' => ['in', 'share_title,share_img,share_synopsis,avatar']
        ])->select();
        $wxConfig = [];
        foreach ($wxConfigData as $val) {
            $wxConfig[$val['name']] = $val['value'];
        }
        $wxConfig['debug'] = false;
        $jsSdk = WechatService::jsSdk(urldecode($_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['PATH_INFO']));
        if(isset($jsSdk['jsApiList'])){
            $jsSdk['jsApiList'] =  json_encode($jsSdk['jsApiList']);
            $this->assign('wxConfig', array_merge($wxConfig, $jsSdk));
        }else{
            $this->assign('wxConfig', []);
        }
        
        return $this->fetch();
    }

    /**
     * 微信公众号服务
     * http://你的域名/addons/weixin/index/serve
     */
    public function serve()
    {
        ob_clean();
        return WechatService::serve();
    }

    /**
     * jssdk配置信息获取--废弃
     * http://你的域名/addons/weixin/index/config
     */
    public function config()
    {
        $wxModel = new \app\admin\model\weixin\Config();
        $wxConfigData = $wxModel->where([
            'group' => 'weixin', 'name' => ['in', 'share_title,share_img,share_synopsis,avatar']
        ])->select();
        $wxConfig = [];
        foreach ($wxConfigData as $val) {
            $wxConfig[$val['name']] = $val['value'];
        }
        $jsSdk = WechatService::jsSdk(urldecode($this->request->post('url')));
        return json(['code' => 1, 'data' => array_merge($wxConfig, $jsSdk)]);
    }

    /*
     * 微信公众号发起授权登录
     * http://你的域名/addons/weixin/index/login
     * */
    public function login()
    {
        $wechat_data = \app\admin\model\weixin\Config::where(['group' => 'weixin'])->select();
        foreach ($wechat_data as $k => $v) {
            $value = $v->toArray();
            if (in_array($value['type'], ['selects', 'checkbox', 'images', 'files'])) {
                $value['value'] = explode(',', $value['value']);
            }
            if ($value['type'] == 'array') {
                $value['value'] = (array)json_decode($value['value'], true);
            }
            $wechat[$value['name']] = $value['value'];
        }
        $return_url = "http://" . $_SERVER['HTTP_HOST'] . "/addons/weixin/index/auth/login_type/login";
        $redirect_uri = urlencode($return_url);
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$wechat['appid']}&redirect_uri={$redirect_uri}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
        header('location:' . $url);
        exit();
    }


     /*
     * 微信公众号发起授权绑定
     * http://你的域名/addons/weixin/index/bind
     * */
    public function bind()
    {
        $wechat_data = \app\admin\model\weixin\Config::where(['group' => 'weixin'])->select();
        foreach ($wechat_data as $k => $v) {
            $value = $v->toArray();
            if (in_array($value['type'], ['selects', 'checkbox', 'images', 'files'])) {
                $value['value'] = explode(',', $value['value']);
            }
            if ($value['type'] == 'array') {
                $value['value'] = (array)json_decode($value['value'], true);
            }
            $wechat[$value['name']] = $value['value'];
        }
        $return_url = "http://" . $_SERVER['HTTP_HOST'] . "/addons/weixin/index/auth/login_type/bind";
        $redirect_uri = urlencode($return_url);
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$wechat['appid']}&redirect_uri={$redirect_uri}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
        header('location:' . $url);
        exit();
    }

    /**
     * 公众号授权回调登陆或绑定
     * http://你的域名/addons/weixin/index/auth
     */
    public function auth()
    {
        $spreadId = intval($this->request->param('spread'));
        $login_type = $this->request->param('login_type', '');
        try {
            $wechatInfo = WechatService::oauthService()->user()->getOriginal();
        } catch (\Exception $e) {
            $this->error('授权失败', '', ['message' => $e->getMessage(), 'line' => $e->getLine()]);
        }
        if (!isset($wechatInfo['nickname'])) {
            $wechatInfo = WechatService::getUserInfo($wechatInfo['openid']);
            //没有关注公众号也没有会的微信用户昵称
            if (!$wechatInfo['subscribe'] && !isset($wechatInfo['nickname'])) {
                exit(WechatService::oauthService()->scopes(['snsapi_userinfo'])
                    ->redirect($this->request->url(true))->send());
            }
            //得到标签列表
            if (isset($wechatInfo['tagid_list'])) {
                $wechatInfo['tagid_list'] = implode(',', $wechatInfo['tagid_list']);
            }
        } else {
            //用户特权信息,json 数组,如微信沃卡用户为(chinaunicom)
            if (isset($wechatInfo['privilege'])) {
                unset($wechatInfo['privilege']);
            }
        }
        trace($wechatInfo,"wechatInfo");

        //原始功能,授权成功后(如果存在则更新会员信息,否则会新增会员)
        //$uid = WechatUser::onWechatOauthAfter($wechatInfo, $spreadId, $login_type);
        if($login_type=="login"){ //登录
            //不使用原版新增会员的功能,判断如果登录时未找到绑定会员则提示当前微信未绑定
            if (isset($wechatInfo['unionid'])) {
                $where['unionid'] = $wechatInfo['unionid'];
            } else {
                $where['openid'] = $wechatInfo['openid'];
            }
            $uid = WechatUser::where($where)->value('uid');
            if (empty($uid)) {
                $this->error("当前微信暂未绑定");
            }
            //更新微信信息 多绑定根据uid更新会出错。
            //WechatUser::updateWechatUser($wechatInfo, $uid, 'uid');
            //检查是否存在主会员数据
            if (!\app\admin\model\User::get($uid)) {
                $this->error("当前微信绑定的会员已删除,请联系管理员处理!");
            }
            //登录
            $ret = $this->auth->direct($uid);
            if ($ret) {
                $this->success('授权登录成功', url('index/user/index'));
            } else {
                $this->error($this->auth->getError());
            }
        }elseif($login_type=="bind"){ //绑定
            if(!$this->auth->isLogin()){
                $this->error('请先登录后再绑定!');
            }
            if (isset($wechatInfo['unionid'])) {
                $where['unionid'] = $wechatInfo['unionid'];
            } else {
                $where['openid'] = $wechatInfo['openid'];
            }
            $uid = WechatUser::where($where)->value('uid');
            if ($uid) {
                $this->error("该微信已绑定至会员:{$uid},请勿多次绑定。", url('index/user/weixin'));
            }
            //设置推荐人
            $wechatInfo['parent_id'] = $spreadId;
            //设置会员主表ID
            $wechatInfo['uid'] = $this->auth->id;
            //新增微信会员
            WechatUser::addWechatUser($wechatInfo);
            $this->success('绑定成功', url('index/user/weixin'));
        }
    }


     /*
     * 解除绑定
     * http://你的域名/addons/weixin/index/unbind
     * */
    public function unbind()
    {
       $id=$this->request->param("id/d");
       if(empty($id)){
        $this->error("参数错误");
       }
       $res=WechatUser::where("uid",$this->auth->id)->where('id',$id)->delete();
       if(empty($res)){
            $this->error("解绑失败");

       }else{
            $this->success('解绑成功', url('index/user/weixin'));
       }
       
    }
}

快捷键:weixin授权

源:

sublime_text格式

<snippet>
    <content><![CDATA[
<?php

namespace addons\weixin\controller;

use app\common\library\Auth;
use think\Config;
use addons\weixin\library\WechatService;
use app\admin\model\weixin\User as WechatUser;
use app\admin\model\User;
use think\Hook;
use think\Cookie;
use think\Session;
//注意表价了主键自增id uin取消主键
//微信需要加授权域名和ip白名单
/**
 * 微信公众号接口
 */
class Index extends \think\addons\Controller
{

    public \$auth = null;

    public function _initialize()
    {
        parent::_initialize();
        \$this->auth = \$auth = Auth::instance();

        //监听注册登录注销的事件
        Hook::add('user_login_successed', function (\$user) use (\$auth) {
            \$expire = input('post.keeplogin') ? 30 * 86400 : 0;
            Cookie::set('uid', \$user->id, \$expire);
            Cookie::set('token', \$auth->getToken(), \$expire);
        });
    }

    /**
     * 微信公众号授权登录和jssdk分享演示
     * http://你的域名/addons/weixin
     */
    public function index()
    {
        //token
        \$token = \$this->request->server('HTTP_TOKEN', \$this->request->request('token', \think\Cookie::get('token')));
        //初始化
        \$this->auth->init(\$token);
        //检测是否登录
        if (!\$this->auth->isLogin()) {
            \$this->login();
        }


        \$wxModel = new \app\admin\model\weixin\Config();
        \$wxConfigData = \$wxModel->where([
            'group' => 'weixin', 'name' => ['in', 'share_title,share_img,share_synopsis,avatar']
        ])->select();
        \$wxConfig = [];
        foreach (\$wxConfigData as \$val) {
            \$wxConfig[\$val['name']] = \$val['value'];
        }
        \$wxConfig['debug'] = false;
        \$jsSdk = WechatService::jsSdk(urldecode(\$_SERVER['REQUEST_SCHEME'] . '://' . \$_SERVER['HTTP_HOST'] . \$_SERVER['PATH_INFO']));
        if(isset(\$jsSdk['jsApiList'])){
            \$jsSdk['jsApiList'] =  json_encode(\$jsSdk['jsApiList']);
            \$this->assign('wxConfig', array_merge(\$wxConfig, \$jsSdk));
        }else{
            \$this->assign('wxConfig', []);
        }
        
        return \$this->fetch();
    }

    /**
     * 微信公众号服务
     * http://你的域名/addons/weixin/index/serve
     */
    public function serve()
    {
        ob_clean();
        return WechatService::serve();
    }

    /**
     * jssdk配置信息获取--废弃
     * http://你的域名/addons/weixin/index/config
     */
    public function config()
    {
        \$wxModel = new \app\admin\model\weixin\Config();
        \$wxConfigData = \$wxModel->where([
            'group' => 'weixin', 'name' => ['in', 'share_title,share_img,share_synopsis,avatar']
        ])->select();
        \$wxConfig = [];
        foreach (\$wxConfigData as \$val) {
            \$wxConfig[\$val['name']] = \$val['value'];
        }
        \$jsSdk = WechatService::jsSdk(urldecode(\$this->request->post('url')));
        return json(['code' => 1, 'data' => array_merge(\$wxConfig, \$jsSdk)]);
    }

    /*
     * 微信公众号发起授权登录
     * http://你的域名/addons/weixin/index/login
     * */
    public function login()
    {
        \$wechat_data = \app\admin\model\weixin\Config::where(['group' => 'weixin'])->select();
        foreach (\$wechat_data as \$k => \$v) {
            \$value = \$v->toArray();
            if (in_array(\$value['type'], ['selects', 'checkbox', 'images', 'files'])) {
                \$value['value'] = explode(',', \$value['value']);
            }
            if (\$value['type'] == 'array') {
                \$value['value'] = (array)json_decode(\$value['value'], true);
            }
            \$wechat[\$value['name']] = \$value['value'];
        }
        \$return_url = "http://" . \$_SERVER['HTTP_HOST'] . "/addons/weixin/index/auth/login_type/login";
        \$redirect_uri = urlencode(\$return_url);
        \$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={\$wechat['appid']}&redirect_uri={\$redirect_uri}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
        header('location:' . \$url);
        exit();
    }


     /*
     * 微信公众号发起授权绑定
     * http://你的域名/addons/weixin/index/bind
     * */
    public function bind()
    {
        \$wechat_data = \app\admin\model\weixin\Config::where(['group' => 'weixin'])->select();
        foreach (\$wechat_data as \$k => \$v) {
            \$value = \$v->toArray();
            if (in_array(\$value['type'], ['selects', 'checkbox', 'images', 'files'])) {
                \$value['value'] = explode(',', \$value['value']);
            }
            if (\$value['type'] == 'array') {
                \$value['value'] = (array)json_decode(\$value['value'], true);
            }
            \$wechat[\$value['name']] = \$value['value'];
        }
        \$return_url = "http://" . \$_SERVER['HTTP_HOST'] . "/addons/weixin/index/auth/login_type/bind";
        \$redirect_uri = urlencode(\$return_url);
        \$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={\$wechat['appid']}&redirect_uri={\$redirect_uri}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
        header('location:' . \$url);
        exit();
    }

    /**
     * 公众号授权回调登陆或绑定
     * http://你的域名/addons/weixin/index/auth
     */
    public function auth()
    {
        \$spreadId = intval(\$this->request->param('spread'));
        \$login_type = \$this->request->param('login_type', '');
        try {
            \$wechatInfo = WechatService::oauthService()->user()->getOriginal();
        } catch (\Exception \$e) {
            \$this->error('授权失败', '', ['message' => \$e->getMessage(), 'line' => \$e->getLine()]);
        }
        if (!isset(\$wechatInfo['nickname'])) {
            \$wechatInfo = WechatService::getUserInfo(\$wechatInfo['openid']);
            //没有关注公众号也没有会的微信用户昵称
            if (!\$wechatInfo['subscribe'] && !isset(\$wechatInfo['nickname'])) {
                exit(WechatService::oauthService()->scopes(['snsapi_userinfo'])
                    ->redirect(\$this->request->url(true))->send());
            }
            //得到标签列表
            if (isset(\$wechatInfo['tagid_list'])) {
                \$wechatInfo['tagid_list'] = implode(',', \$wechatInfo['tagid_list']);
            }
        } else {
            //用户特权信息,json 数组,如微信沃卡用户为(chinaunicom)
            if (isset(\$wechatInfo['privilege'])) {
                unset(\$wechatInfo['privilege']);
            }
        }
        trace(\$wechatInfo,"wechatInfo");

        //原始功能,授权成功后(如果存在则更新会员信息,否则会新增会员)
        //\$uid = WechatUser::onWechatOauthAfter(\$wechatInfo, \$spreadId, \$login_type);
        if(\$login_type=="login"){ //登录
            //不使用原版新增会员的功能,判断如果登录时未找到绑定会员则提示当前微信未绑定
            if (isset(\$wechatInfo['unionid'])) {
                \$where['unionid'] = \$wechatInfo['unionid'];
            } else {
                \$where['openid'] = \$wechatInfo['openid'];
            }
            \$uid = WechatUser::where(\$where)->value('uid');
            if (empty(\$uid)) {
                \$this->error("当前微信暂未绑定");
            }
            //更新微信信息 多绑定根据uid更新会出错。
            //WechatUser::updateWechatUser(\$wechatInfo, \$uid, 'uid');
            //检查是否存在主会员数据
            if (!\app\admin\model\User::get(\$uid)) {
                \$this->error("当前微信绑定的会员已删除,请联系管理员处理!");
            }
            //登录
            \$ret = \$this->auth->direct(\$uid);
            if (\$ret) {
                \$this->success('授权登录成功', url('index/user/index'));
            } else {
                \$this->error(\$this->auth->getError());
            }
        }elseif(\$login_type=="bind"){ //绑定
            if(!\$this->auth->isLogin()){
                \$this->error('请先登录后再绑定!');
            }
            if (isset(\$wechatInfo['unionid'])) {
                \$where['unionid'] = \$wechatInfo['unionid'];
            } else {
                \$where['openid'] = \$wechatInfo['openid'];
            }
            \$uid = WechatUser::where(\$where)->value('uid');
            if (\$uid) {
                \$this->error("该微信已绑定至会员:{\$uid},请勿多次绑定。", url('index/user/weixin'));
            }
            //设置推荐人
            \$wechatInfo['parent_id'] = \$spreadId;
            //设置会员主表ID
            \$wechatInfo['uid'] = \$this->auth->id;
            //新增微信会员
            WechatUser::addWechatUser(\$wechatInfo);
            \$this->success('绑定成功', url('index/user/weixin'));
        }
    }


     /*
     * 解除绑定
     * http://你的域名/addons/weixin/index/unbind
     * */
    public function unbind()
    {
       \$id=\$this->request->param("id/d");
       if(empty(\$id)){
        \$this->error("参数错误");
       }
       \$res=WechatUser::where("uid",\$this->auth->id)->where('id',\$id)->delete();
       if(empty(\$res)){
            \$this->error("解绑失败");

       }else{
            \$this->success('解绑成功', url('index/user/weixin'));
       }
       
    }
}

]]></content>
   <tabTrigger>weixin授权(微信的绑定登录 绑定 解绑 分享)</tabTrigger>
   <scope></scope>
</snippet>
点赞(0)

评论列表 共有 0 条评论

暂无评论
立即
投稿
发表
评论
返回
顶部