Преглед изворни кода

添小程序的快捷登录

lvhao пре 8 часа
родитељ
комит
0cfde8bcf1

+ 1 - 0
core/CoreApp/controllers/Lyerpapi/v1/User.php

@@ -75,6 +75,7 @@ class User extends Lyapi_Controller{
         $token = bin2hex(random_bytes(32));
         // 写入缓存,有效期7200秒(2小时)
         $this->cache->save($token, [
+            'userid'=>$userinfo['id'],
             'username'=>$userinfo['userid'],
             'mobile'=>'',
             'token'=>$token,

+ 145 - 0
core/CoreApp/controllers/Lyerpapi/v1/Wechat.php

@@ -0,0 +1,145 @@
+<?php
+defined('BASEPATH') OR exit('No direct script access allowed');
+
+class Wechat extends Lyapi_Controller{
+    // 注意:登录接口不能受基础控制器的登录校验,可以覆盖构造方法或单独处理
+    public function __construct() {
+        // 这里不执行登录校验,只加载缓存驱动
+        parent::__construct(); // 暂时注释,或者使用一个新的不校验的基类
+        // 简便做法:复制 Lyapi_Controller 的部分代码但不调用 _check_api_auth
+       // $this->load->driver('cache'); // 加载缓存驱动
+       $this->load->_model("Model_wechat","wechat");
+       $this->load->_model("Model_user","user");
+       $this->load->_model("Model_power","power");
+    }
+
+    public function bduser(){
+        if($this->input->method(TRUE) != 'POST'){
+
+            $this->_json_error('请求方式错误','500');
+        }
+        $json_str = $this->input->raw_input_stream;
+        $data = json_decode($json_str,true);
+        if(empty($data['code'])){
+            $this->_json_error('参数错误','500');
+        }
+        $code = $data['code'];
+        $r = $this->wechat->getopenid($code);
+        if($r['code'] == -1){
+            $this->_json_error('获取openid失败','500');
+        }
+
+        $user_info = $this->user->read($this->userinfo['userid']);
+       
+        if(empty($user_info['wxopenid'])){
+            $wxopenid = [];
+        }else{
+            $wxopenid = json_decode($user_info['wxopenid'],true);
+        }
+        $openid = $r['data']['openid'];
+        $wxopenid[] = $r['data']['openid'];
+        $wxopenid = array_unique($wxopenid);
+        $auth_token = $this->input->get_request_header('Auth-Token', TRUE);
+        $this->cache->delete($auth_token);
+        $this->db->where('id',$user_info['id'])->update('user',array('wxopenid' => json_encode($wxopenid)));
+
+
+        $power = $this->power->read($user_info['power']);
+        if(empty($power)){
+            $this->_json_error('角色未设置','500');
+        }
+        if(empty($power['lyapiid'])){
+            $this->_json_error('权限未设置','500');
+        }
+       
+        $lyapiids = explode("|",trim($power['lyapiid'],"|"));
+        $res = $this->power->_lyapi();
+        $lyapi_list = $res['lyapi_list'];
+        $all_arr = [];
+        foreach($lyapi_list as $v){
+            if(in_array($v['id'],$lyapiids)){
+                $all_arr[] = $v['shortname'];
+            }
+        }
+        $this->cache->save($openid, [
+            'userid'=>$user_info['id'],
+            'username'=>$user_info['userid'],
+            'mobile'=>'',
+            'token'=>$openid,
+            'power'=>$all_arr
+        ], 7200);
+        $this->_json_error('绑定成功','200',[
+            'username'=>$user_info['userid'],
+            'mobile'=>'',
+            'token'=>$openid,
+            'lypower'=>implode(',',$all_arr)
+        ]);
+        
+
+    }
+
+
+    public function wxlogin(){
+        if($this->input->method(TRUE) != 'POST'){
+
+            $this->_json_error('请求方式错误','500');
+        }
+        $json_str = $this->input->raw_input_stream;
+        $data = json_decode($json_str,true);
+
+        $auth_token = $this->input->get_request_header('Auth-Token', TRUE);
+        if(!empty($auth_token)){
+            $this->cache->delete($auth_token);
+        }
+
+        $code = $data['code'];
+        $r = $this->wechat->getopenid($code);
+        if($r['code'] == -1){
+            $this->_json_error('获取openid失败','500');
+        }
+        $openid = $r['data']['openid'];
+        $user_info_list = $this->user->find_all("wxopenid like '%{$openid}%'");
+        if(empty($user_info_list)){
+            $this->_json_error('用户不存在','500');
+        }
+        $len = count($user_info_list);
+        if($len > 1){
+            $this->_json_error('微信绑定错误,请联系管理员','500');
+        }
+        $user_info = $user_info_list[0];
+        $power = $this->power->read($user_info['power']);
+        if(empty($power)){
+            $this->_json_error('角色未设置','500');
+        }
+        if(empty($power['lyapiid'])){
+            $this->_json_error('权限未设置','500');
+        }
+       
+        $lyapiids = explode("|",trim($power['lyapiid'],"|"));
+        $res = $this->power->_lyapi();
+        $lyapi_list = $res['lyapi_list'];
+        $all_arr = [];
+        foreach($lyapi_list as $v){
+            if(in_array($v['id'],$lyapiids)){
+                $all_arr[] = $v['shortname'];
+            }
+        }
+        $this->cache->save($openid, [
+            'userid'=>$user_info['id'],
+            'username'=>$user_info['userid'],
+            'mobile'=>'',
+            'token'=>$openid,
+            'power'=>$all_arr
+        ], 7200);
+        $this->_json_error('绑定成功','200',[
+            'username'=>$user_info['userid'],
+            'mobile'=>'',
+            'token'=>$openid,
+            'lypower'=>implode(',',$all_arr)
+        ]);
+
+       
+        
+    }
+   
+}

+ 3 - 1
core/CoreApp/core/Lin_Controller.php

@@ -165,6 +165,7 @@ abstract class Admin_Controller extends Lin_Controller {
 
 abstract class Lyapi_Controller extends CI_Controller {
 	public $cache;
+	public $userinfo;
 	function __construct()
 	{
 		parent::__construct();
@@ -183,7 +184,7 @@ abstract class Lyapi_Controller extends CI_Controller {
 		//  if($uri_path != "lyapi/v1/user/login"){
 		// 	$this->_check_api_auth();
 		//  }
-		 if(!in_array($uri_path,["lyapi/v1/user/login"])){
+		 if(!in_array($uri_path,["lyapi/v1/user/login","lyapi/v1/wechat/wxlogin"])){
 			$this->_check_api_auth();
 		 }
 		 
@@ -197,6 +198,7 @@ abstract class Lyapi_Controller extends CI_Controller {
 		if(empty($cache_info)){
 			$this->_json_error('请重新登录',401);
 		}
+		$this->userinfo = $cache_info;
 		$power_name = $this->input->get('p',true);
 		if(!in_array($power_name, $cache_info['power'])){
 			if($power_name != "gy"){

+ 63 - 0
core/CoreApp/models/Model_wechat.php

@@ -0,0 +1,63 @@
+<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 
+class Model_wechat extends Lin_Model 
+{
+	function __construct(){
+		parent::__construct();
+		$this->load->database();
+	}
+
+	public function getopenid($code){
+        $query1 = $this->db->get_where('setting',array('skey' => 'lywx_id'));
+        $app_id = $query1->row_array();
+		$query2 = $this->db->get_where('setting',array('skey' => 'lywx_secret'));
+        $app_secret = $query2->row_array();
+       
+        $url = 'https://api.weixin.qq.com/sns/jscode2session';
+        $params = [
+            'appid' => $app_id['svalue'],
+            'secret' => $app_secret['svalue'],
+            'js_code' => $code,
+            'grant_type' => 'authorization_code'
+        ];
+        $query = http_build_query($params);
+        $requestUrl = $url . '?' . $query;
+    
+        $ch = curl_init();
+        curl_setopt($ch, CURLOPT_URL, $requestUrl);
+        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
+       
+        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
+    
+        $response = curl_exec($ch);
+        $errorNo = curl_errno($ch);
+        $errorMsg = curl_error($ch);
+        curl_close($ch);
+      
+        if ($errorNo !== 0) {
+			$str = "cURL Error ($errorNo): $errorMsg";
+            return  [
+				"code"=>-1,
+				"msg"=>$str
+			];
+        }
+    
+        $result = json_decode($response, true);
+    
+        // 检查微信返回的错误码
+        if (isset($result['errcode'])) {
+            $str ="WeChat API Error: " . $result['errmsg'] . " (Code: " . $result['errcode'] . ")";
+            return  [
+				"code"=>-1,
+				"msg"=>$str
+			];
+        }
+    
+        return [
+			"code"=>1,
+			"msg"=>"success",
+			"data"=>$result
+		];
+    }
+	
+}