企业微信登录功能和注册

1.先在企业微信注册

https://work.weixin.qq.com/wework_admin/register_wx?from=sem_baidu&keyword=brand&derivative=0012200008
拿到corpid 企业ID,和corpsecret 应用的凭证密钥
****要求配置的授权回调域,必须与访问链接的域名完全一致

  1.  内嵌到网页中去:
    

在需要展示企业微信网页登录二维码的网站引入如下JS文件,(支持https):
http://rescdn.qqmail.com/node/ww/wwopenmng/js/sso/wwLogin-1.0.0.js

步骤二:在需要使用微信登录的地方实例JS对象

window.WwLogin({
        "id" : "wx_reg",  
        "appid" : "",
        "agentid" : "",
        "redirect_uri" :"",
        "state" : "",
        "href" : "",
});
参数必须说明
appid企业微信的CorpID,在企业微信管理端查看
agentid授权方的网页应用ID,在具体的网页应用中查看
redirect_uri重定向地址,需要进行UrlEncode
state用于保持请求和回调的状态,授权请求后原样带回给企业。该参数可用于防止csrf攻击(跨站请求伪造攻击),建议企业带上该参数,可设置为简单的随机数加session进行校验
href自定义样式链接,企业可根据实际需求覆盖默认样式。详见文档底部FAQ
   自己感觉样式不好看,可以自己在css文件修改

    .impowerBox .qrcode {width: 200px;}
.impowerBox .title {display: none;}
.impowerBox .info {width: 200px;}
.status_icon {display:none  !important}
.impowerBox .status {text-align: center;}

2.登陆类

<?php
    
    namespace frontend\controllers;
    
    use Yii; 
    use app\models\MmcUsers;
    use app\components\Controller;
    use common\models\MmcDayCount;
    use common\plugins\corwechat\Core;
     
    /**
     * Site controller
     */
    class UserwxController extends Controller {
    
    
        /**
         * 企业微信扫码登录测试
         * @return type
         */
        public function actionAuthlogin() {   
            $code = \yii\helpers\HtmlPurifier::process(Yii::$app->request->post('code',''));
    //        $state = \yii\helpers\HtmlPurifier::process(Yii::$app->request->post('state','MMC')); 
            $rep = ['status' => -2000, 'message' => '参数错误', 'data' => []];
            if (empty($code)) {
                return $rep;
            }   
            $wechat = new Core();
            $userInfoRet = $wechat->getUserByCode($code);//企业微信获取用户UserId
            $userInfo = json_decode($userInfoRet, true);  
            if(!isset($userInfo['UserId'])){
                $rep = ['status' => -2001, 'message' => '您尚未注册公司企业微信账号,请使用账号进行密码登录', 'data' => []];
                return $rep;
            } 
            //查询用户身份存在 
            $user = \backend\models\MmcUsers::find()->where(['msn' => $userInfo['UserId'],'is_delete'=>0])->one();  
            if(empty($user)){
                $userInfoRet = $wechat->getUserInfoById($userInfo['UserId']);  
                if($userInfoRet['errcode']!=0){
                    $rep = ['status' => -2001, 'message' => '获取信息出错,请使用账号密码登录', 'data' => []];
                    return $rep;
                }
                $this->_bindUser($userInfoRet);
                $user = \backend\models\MmcUsers::find()->where(['msn' => $userInfo['UserId'],'is_delete'=>0])->one();   
                if(empty($user)){ 
                    $rep = ['status' => -2001, 'message' => '获取信息出错,请使用账号密码登录', 'data' => []];
                    return $rep;
                }
            }  
            if($user->can_login!=1){
                $rep = ['status' => -2001, 'message' => '该账号已被禁用', 'data' => []];
                return $rep;
            }
            if (!empty($user->user_name)) {
                $model =  \app\models\MmcUsers::findByUsername($user->user_name); 
                if(empty($model)){
                    $model =  \app\models\MmcUsers::findByUsername($user->alias);
                } 
                if (!empty($model)&&Yii::$app->user->login($model, 0)) {
                    $this->_loginDone($model);//登录活跃
                    return ['status' => 0, 'user_id' => $model->user_id,
                    'user_name' => $model->user_name, 'message' => 'success'];
                }
            }
            return ['status' => 1002, 'message' => '请检查用户名和密码是否正确!'];
        }
          
        /**
         * 绑定为绑定的用户
         * @param type $userInfo
         */
        public function _bindUser($userInfo){
            $model = new \backend\models\MmcUsers(); 
            $user = [];
            if(isset($userInfo['mobile'])&&!empty($userInfo['mobile'])){
                $user = $model->find()->where(['mobile_phone' => $userInfo['mobile'],'is_delete'=>0])->one(); 
            }
            if(empty($user)){
                $user = $model->find()->where(['user_name' => $userInfo['userid'],'is_delete'=>0])->one(); 
            }
            if(empty($user)&&!empty($userInfo['email'])){
                $user = $model->find()->where(['email' => $userInfo['email'],'flag'=>0,'is_delete'=>0])->one(); 
            }
            if(empty($user)&&!empty($userInfo['name'])){
                $user = $model->find()->where(['real_name' => $userInfo['name'],'flag'=>0,'is_delete'=>0])->one(); 
            } 
            if(!empty($user)){
                $user->flag=1;
                $user->alias=$userInfo['name'];
                $user->msn=$userInfo['userid'];
                $user->update();
                return FALSE;
            } 
            $this->_registerUser($userInfo,$model);
        }
        
        /**
         * 企业微信注册系统账号
         * @param type $userInfo
         * @param type $model
         */
        private function _registerUser($userInfo,$model){ 
            $pwd = 'mmc'.mt_rand(1, 9).mt_rand(1, 9).mt_rand(1, 9).mt_rand(1, 9).mt_rand(1, 9).mt_rand(1, 9);
            $model->setIsNewRecord(TRUE);
            $model->mobile_phone = $userInfo['mobile'];
            $model->user_name = strtolower($userInfo['userid']);
            $model->real_name = $userInfo['name'];
            $model->email = empty($userInfo['email'])?strtolower($userInfo['userid']).'@mmcuav.cn':$userInfo['email'];
            $model->password = md5($pwd);
            $model->msn = $userInfo['userid'];
            $model->alias = $userInfo['name'];
            $model->flag = 1;
            $model->can_login = 1;
            $model->role = 2;
            $model->save();  
            $data['touser'] = $userInfo['userid'].'|LiYang';    
            $wechat = new Core();
            $data['msgtype'] = 'text';
            $data['text']['content'] = '恭喜您('.$userInfo['name'].')注册该系统账号成功,您的账号:'.strtolower($userInfo['userid'])' 。请勿泄露账号密码给他人使用。';
            $wechat->sendMessage($data); 
            return false;
        }
         
        /**
         * 登录活跃
         * @param type $model
         */
        private function _loginDone($model) {
            $loginTime =!empty($model->last_time)?$model->last_time:time();
            $condition = ['user_id' => Yii::$app->user->identity->id];
            $attributes = ['last_time' => time(), 'last_login' => $loginTime, 'login_ip' => Yii::$app->request->userIP];
            MmcUsers::updateAll($attributes, $condition);
            //日活跃用户统计
            if (date('Ymd') != date('Ymd', $loginTime)) {
                $dayCount = new MmcDayCount();
                $ret = $dayCount->findOne(['type' => 1, 'date' => date('Ymd')]);
                if (!empty($ret)) {
                    $ret->count = $ret->count + 1;
                    $ret->update();
                } else {
                    $dayCount->isNewRecord;
                    $dayCount->date = date('Ymd');
                    $dayCount->type = 1;
                    $dayCount->count = 1;
                    $dayCount->save();
                }
            }
        }
     
    
        public function actionSendmsg(){
            $wechat = new Core();  
    //        $data['touser'] = '@all';
            $data['touser'] = 'GuChaoHui|DengWanCheng';
            $data['msgtype'] = 'text';
            $data['text']['content'] = '测试消息推送。\n出发前可查看<a href=\"http://work.weixin.qq.com\">邮件中心视频实况</a>,聪明避开排队。';
            $res = $wechat->sendMessage($data);
            var_dump($res);die;
        }
    
    }

3。Core.php

<?php 
namespace common\plugins\corwechat;
use Yii;

class Core {
    private $corpId='ww3784cdcfd7d75068';     
    private $secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
    private $product_secret='xxxxxxxxxxxxxxxxx'; 
    private $agentId='xxxxx';    
    private $appConfigs; 

    /**
     * AccessToken构造器
     * @param [Number] $agentId 两种情况:1是传入字符串“txl”表示获取通讯录应用的Secret;2是传入应用的agentId
     */
    public function __construct() {
        
            
    }
    /**
     * 获取部门列表
     * @param  integer $id [部门id]
     * @return [type]     [description]
     */
    public function getDepartment($id=1){
        $this->access_token = $this->getAccessToken($this->secret,'contact');
        $data = http_get('https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token='.$this->access_token.'&id='.$id);
        return $data;
    }
    /**
     * 获取部门用户
     * @param  integer $department_id [部门id]
     * @param  integer $fetch_child   [是否获取子部门用户  1是]
     * @return [type]                 [description]
     */
    public function getDepartmentUser($department_id=1,$fetch_child=1){
        $this->access_token = $this->getAccessToken($this->secret,'contact');
        $data = http_get('https://qyapi.weixin.qq.com/cgi-bin/user/simplelist?access_token='.$this->access_token.'&department_id='.$department_id.'&fetch_child='.$fetch_child);
        return $data;
    }
    /**
     * 获取用户部门名称
     * @param  [type] $userid [description]
     * @return [type]         [description]
     */
    public function getDepartmentName($userid){
        $userinfo = $this->getUserinfo($userid);
        $name = '';
        if($userinfo){
            $ids = $userinfo['department'];
            foreach($ids as $v){
                $userInfo = http_get('https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token='.$this->access_token.'&id='.$v);
                $name .= json_decode($userInfo,true)['department'][0]['name'].',';
            }
            
        }
        return trim($name,',');
    }

    public function getUserinfo($userid){
        $this->access_token = $this->getAccessToken($this->secret,'contact');
        $info = http_get('https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token='.$this->access_token.'&userid='.$userid);
        return json_decode($info,true);
    }
    /**
     * 企业微信授权登录链接
     * @param  [type] $url [description]
     * @return [type]      [description]
     */
    public function oauthUrl($url){
        return 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$this->corpId.'&redirect_uri='.$url.'&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect';
    }
    /**
     * 企业微信根据授权code获取用户
     * @param  [type] $code [description]
     * @return [type]       [description]
     */
    public function getUserByCode($code){
        $this->access_token = $this->getAccessToken($this->product_secret,'product');
        $data = http_get('https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token='.$this->access_token.'&code='.$code);
        return $data;
    }
    
     /**
      * 企业微信获取用户信息
      * @param type $userId
      * @return type
      */
    public function getUserInfoById($userId){
        $this->access_token = $this->getAccessToken($this->product_secret,'product');
        $info = http_get('https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token='.$this->access_token.'&userid='.$userId);
        return json_decode($info,true);
    }
    
    /**
     * 发送消息
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public function sendMessage($data){
        if(!Yii::$app->params['switch']['wxMessage']){
            return false;
        }
        $this->access_token = $this->getAccessToken($this->product_secret,'product');
        $data['agentid'] = $this->agentId;
        $res = http_post('https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token='.$this->access_token,json_encode($data));
       return $res;
    }

    /**
     * [getAccessToken description]
     * @param  [type] $secret [description]
     * @param  [type] $type   [description]
     * @return [type]         [description]
     */
    public function getAccessToken($secret,$type) {
      
        //TODO: access_token 应该全局存储与更新,以下代码以写入到文件中做示例      
        //NOTE: 由于实际使用过程中不同的应用会产生不同的token,所以示例按照agentId做为文件名进行存储
        
        $path = __DIR__."/access_token.json";
        $data = json_decode(file_get_contents($path));
        if(!isset($data->$type)){
            //$data->$type->expire_time = 213;
            //$data->$type->access_token =123;
            $data->$type = (object)array('expire_time'=>123,'access_token'=>123);
        }
        if($data->$type->expire_time < time()) {    

            $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->corpId&corpsecret=$secret";    
            $res = json_decode(http_get($url));

            $access_token = $res->access_token;
            
            if($access_token) {
                $data->$type->expire_time = time() + 3600;
                $data->$type->access_token = $access_token;        
                file_put_contents($path, json_encode($data));
            }
        } else {
            $access_token = $data->$type->access_token;
        }
        return $access_token;    
    }
    
}
function http_get($url){
    $oCurl = curl_init();
    if(stripos($url,"https://")!==FALSE){
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
    }
    curl_setopt($oCurl, CURLOPT_URL, $url);
    curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt($oCurl, CURLOPT_VERBOSE, 1);
    curl_setopt($oCurl, CURLOPT_HEADER, 0);

    // $sContent = curl_exec($oCurl);
    // $aStatus = curl_getinfo($oCurl);
    $sContent = curl_exec($oCurl);
    curl_close($oCurl);

    return $sContent;
}
/**
 * POST 请求
 * @param string $url
 * @param array $param
 * @param boolean $post_file 是否文件上传
 * @return string content
 */
function http_post($url,$data,$post_file=false){
    $oCurl = curl_init();

    if(stripos($url,"https://")!==FALSE){
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
    }
    
    
    
    curl_setopt($oCurl, CURLOPT_URL, $url);
    curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt($oCurl, CURLOPT_POST,true);
    curl_setopt($oCurl, CURLOPT_POSTFIELDS,$data);
    curl_setopt($oCurl, CURLOPT_VERBOSE, 1);
    curl_setopt($oCurl, CURLOPT_HEADER, 0);

    // $sContent = curl_exec($oCurl);
    // $aStatus  = curl_getinfo($oCurl);

    $sContent = curl_exec($oCurl);
    curl_close($oCurl);

    return $sContent;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
YOLO高分设计资源源码,详情请查看资源内容中使用说明 YOLO高分设计资源源码,详情请查看资源内容中使用说明 YOLO高分设计资源源码,详情请查看资源内容中使用说明 YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值