企業微信登錄功能和注冊教程
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; }