Browse Source

基础方法,小程序登录

lizhen_gitee 2 years ago
parent
commit
9b31b9abeb
3 changed files with 431 additions and 1 deletions
  1. 146 0
      application/api/controller/User.php
  2. 276 0
      application/common.php
  3. 9 1
      application/config.php

+ 146 - 0
application/api/controller/User.php

@@ -345,4 +345,150 @@ class User extends Api
             $this->error($this->auth->getError());
         }
     }
+
+    /**
+     * 获取用户openid
+     */
+    public function getUserOpenid() {
+        // code值
+        $code = $this->request->param('code');
+        if (!$code) {
+            $this->error(__('Invalid parameters'));
+        }
+
+        $config = config('wxMiniProgram');
+        $getopenid = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$config['appid'].'&secret='.$config['secret'].'&js_code='.$code.'&grant_type=authorization_code';
+        $openidInfo = $this->getJson($getopenid);
+        if(!isset($openidInfo['openid'])) {
+            $this->error('用户openid获取失败',$openidInfo);
+        }
+        //  获取的结果存入数据库
+        $find = Db::name('user_sessionkey')->where(['openid'=>$openidInfo['openid']])->find();
+        if($find) {
+            $update = [];
+            $update['sessionkey'] = $openidInfo['session_key'];
+            $update['createtime'] = time();
+            $res = Db::name('user_sessionkey')->where(['openid'=>$openidInfo['openid']])->update($update);
+        } else {
+            $insert = [];
+            $insert['sessionkey'] = $openidInfo['session_key'];
+            $insert['openid'] = $openidInfo['openid'];
+            $insert['unionid'] = isset($openidInfo['unionid']) ? $openidInfo['unionid'] : '';
+            $insert['createtime'] = time();
+            $res = Db::name('user_sessionkey')->insertGetId($insert);
+        }
+
+        if($res !== false) {
+            $this->success('获取成功',$openidInfo);
+        } else {
+            $this->error('获取失败');
+        }
+
+    }
+
+    /**
+     * 微信小程序登录
+     */
+    public function wxMiniProgramLogin() {
+        $openid        = $this->request->request('openid');// openid值
+        $encryptedData = $this->request->request('encryptedData');// 加密数据
+        $iv            = $this->request->request('iv');// 加密算法
+        $signature     = $this->request->request('signature');// 签名验证
+        $rawData       = $this->request->request('rawData');// 签名验证
+        $logintype     = 2;// 登录方式:1=手机号,2=微信授权openid
+
+        if (!$openid || !$encryptedData || !$iv) {
+            $this->error(__('Invalid parameters'));
+        }
+
+        // 获取openid和sessionkey
+        $config = config('wxMiniProgram');
+        $openidInfo = Db::name('user_sessionkey')->where(['openid'=>$openid])->find();
+        $openid = $openidInfo['openid'];
+        $session_key = $openidInfo['sessionkey'];
+
+//        // 数据签名校验
+//        $signature2 = sha1($rawData . $session_key);
+//        if ($signature != $signature2) {
+//            $this->error(__('数据签名验证失败'));
+//        }
+
+        // 根据加密数据和加密算法获取用户信息
+        $pc = new WXBizDataCrypt($config['appid'], $session_key);
+        $data = '';
+        $errCode = $pc->decryptData(urldecode($encryptedData), $iv, $data);
+        if ($errCode != 0) {
+            $this->error('解密失败',['code'=>$errCode]);
+        }
+
+        $data = json_decode($data,true);
+        // 用户登录逻辑 === 开始
+        if($logintype == 1) { // 手机号登录
+            /*$userInfo = Db::name('user')->where(["mobile"=>$data["purePhoneNumber"]])->find();
+            // 用户信息不存在时使用
+            $extend = ["mobile"=>$data["purePhoneNumber"]];*/
+        } else { // 微信授权openid登录
+            $userInfo = Db::name('user')->where(['mini_openid'=>$openid])->find();
+            // 用户信息不存在时使用
+            $extend = [
+                'mini_openid'    => $openid,
+                'nickname'  => $data['nickName'],
+                'avatar'    => $data['avatarUrl'],
+                //'gender'    => $data['gender']==1 ? 1 : 0,
+                'mini_sessionkey'=> $session_key,
+                'unionid'   => $openidInfo['unionid'],
+                //'mobile' => $data['purePhoneNumber'],
+            ];
+        }
+        // 判断用户是否已经存在
+        if($userInfo) { // 登录
+            Db::name('user')->where('id',$userInfo['id'])->update(['logintime'=>time()]);
+            $res = $this->auth->direct($userInfo['id']);
+        } else { // 注册
+            // 先随机一个用户名,随后再变更为u+数字id
+            $username = '';
+            $password = '';
+
+            /*Db::startTrans();
+            try {*/
+            // 默认注册一个会员
+            $result = $this->auth->register($username, $password, '','', $extend);
+            if (!$result) {
+                $this->error("注册失败!");
+            }
+
+            /*     Db::commit();
+             } catch (PDOException $e) {
+                 Db::rollback();
+                 $this->auth->logout();
+                 return false;
+             }*/
+
+            // 写入登录Cookies和Token
+            $res = $this->auth->direct($this->auth->id);
+        }
+        $userInfo = $this->userInfo('return');
+        if($res) {
+            $this->success("登录成功!",$userInfo);
+        } else {
+            $this->error("登录失败!");
+        }
+
+    }
+
+    /**
+     * json 请求
+     * @param $url
+     * @return mixed
+     */
+    private function getJson($url){
+        $ch = curl_init();
+        curl_setopt($ch, CURLOPT_URL, $url);
+        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
+        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
+        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
+        $output = curl_exec($ch);
+        curl_close($ch);
+        return json_decode($output, true);
+    }
 }

+ 276 - 0
application/common.php

@@ -512,3 +512,279 @@ EOT;
         return $icon;
     }
 }
+
+//我的
+//结果集信息里,生日转换年龄
+function list_birthday_age($list){
+    if(!$list || empty($list)){
+        return $list;
+    }
+    foreach($list as $vo => $info){
+        $list[$vo]['age'] = birthtime_to_age($info['birthday']);
+    }
+    return $list;
+}
+
+//结果集信息里,多个字段需要增加domain_cdnurl
+function list_domain_image($list,$field){
+    if(!$list || empty($list)){
+        return $list;
+    }
+    foreach($list as $vo => $info){
+        $list[$vo] = info_domain_image($info,$field);
+    }
+    return $list;
+}
+//单条信息里,多个字段需要增加domain_cdnurl
+//支持image,images
+function info_domain_image($data,$field){
+    if(!$data || empty($data)){
+        return $data;
+    }
+    foreach($data as $key => $val){
+        if(in_array($key,$field)){
+            $data[$key] = one_domain_image($val);
+        }
+    }
+    return $data;
+}
+//支持单个字段,需要增加domain_cdnurl
+//支持image,images
+function one_domain_image($one){
+    if(!$one){
+        return $one;
+    }
+    if(strpos($one,',')){
+        //逗号隔开的多个图片
+        $one = explode(',',$one);
+        foreach($one as $k => $v){
+            $one[$k] = localpath_to_netpath($v);
+        }
+        $one = implode(',',$one);
+    }else{
+        $one = localpath_to_netpath($one);
+    }
+    return $one;
+}
+//本地地址转换为网络地址
+function localpath_to_netpath($path)
+{
+    if (empty($path)) {
+        return '';
+    } elseif (strrpos($path, 'http') !== false) {
+        return $path;
+    } else {
+        return config('site.domain_cdnurl') . str_replace("\\", "/", $path);
+    }
+}
+
+//秒 转换 日月分
+function Sec2Time($time){
+    if(is_numeric($time)){
+        $value = array(
+            'years' => 0, 'days' => 0, 'hours' => 0,
+            'minutes' => 0, 'seconds' => 0,
+        );
+        /*if($time >= 31556926){
+            $value['years'] = floor($time/31556926);
+            $time = ($time%31556926);
+        }*/
+        if($time >= 86400){
+            $value['days'] = floor($time/86400);
+            $time = ($time%86400);
+        }
+        if($time >= 3600){
+            $value['hours'] = floor($time/3600);
+            $time = ($time%3600);
+        }
+        if($time >= 60){
+            $value['minutes'] = floor($time/60);
+            $time = ($time%60);
+        }
+        $value['seconds'] = floor($time);
+        //return (array) $value;
+        //$t=$value['years'] .'年'. $value['days'] .'天'.' '. $value['hours'] .'小时'. $value['minutes'] .'分'.$value['seconds'].'秒';
+        $t = $value['days'] .'天' . $value['hours'] .'小时'. $value['minutes'] .'分';
+        return $t;
+
+    }else{
+        return '0天';
+    }
+}
+//生日转年龄
+function birthtime_to_age($birthtime){
+//    $birthtime = strtotime('1990-11-06');
+    if(!$birthtime){
+        return 0;
+    }
+
+    list($y1,$m1,$d1) = explode("-",date("Y-m-d",$birthtime));
+
+    list($y2,$m2,$d2) = explode("-",date("Y-m-d",time()));
+
+    $age = $y2 - $y1;
+    if((int)($m2.$d2) < (int)($m1.$d1))
+    {$age -= 1;}
+
+    if($age < 0){
+        $age = 0;
+    }
+
+    return $age;
+}
+if(!function_exists('mk_dir')) {
+    /**
+     * 新建目录
+     */
+    function mk_dir($dir, $mode = 0770, $tmp = true)
+    {
+        $mode = 0770;
+        if(is_file($dir)) {
+            //有同名文件
+            return false;
+        } else {
+            if(!is_dir($dir)) { //目录不存在
+                $dir_up = dirname($dir); //上级目录
+                if(!is_dir($dir_up)) {
+                    //上级不存在
+                    $rs = @mk_dir($dir_up);
+                    if(!$rs) return false;
+                }
+                $rs = @mkdir($dir, $mode); //新建
+                if(!$rs) return false;
+                $rs = @chmod($dir, $mode); //改权限
+                if(!$rs) return false;
+            }
+            return true;
+        }
+    }
+}
+/**
+ * 在线支付日志
+ */
+function filePut($info,$text='notify.txt'){
+    if(is_array($info)) {
+        $info = json_encode($info, JSON_UNESCAPED_UNICODE);
+    }
+    if(!file_exist(RUNTIME_PATH.'paylog/')) {
+        mk_dir(RUNTIME_PATH.'paylog/');
+    }
+    $file = RUNTIME_PATH.'paylog/'.$text;
+    touch_file($file);
+    file_put_contents($file, "\r\n".date('Y-m-d H:i:s').' '.$info, FILE_APPEND);
+}
+if(!function_exists('touch_file')) {
+    /**
+     * 新建文件
+     */
+    function touch_file($file = '')
+    {
+        if($file) {
+            if(!file_exists($file)) {
+                @touch($file);
+                @chmod($file, 0770);
+            }
+        }
+    }
+}
+if(!function_exists('file_exist')) {
+    /**
+     * 检测文件是否存在
+     * @param $file
+     * @return string
+     */
+    function file_exist($file)
+    {
+        if(false === strpos($file, 'http')) { //本地文件
+
+            if(0 === strpos($file, '/upload')) {
+                $file = '.'.$file;
+            }
+            return file_exists($file);
+        } else { //网络文件
+
+            $ch = curl_init();
+            curl_setopt($ch, CURLOPT_URL, $file);
+            curl_setopt($ch, CURLOPT_TIMEOUT, 2);
+            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
+            curl_exec($ch);
+            $status =  curl_getinfo($ch,CURLINFO_HTTP_CODE);
+            curl_close($ch);
+            if(in_array(substr($status, 0, 1), [2, 3])) {
+                return true;
+            } else {
+                return false;
+            }
+        }
+    }
+}
+
+/**
+ * 发起HTTPS请求
+ */
+function curl_post($url, $data, $header = '', $timeOut = 0)
+{
+    //初始化curl
+    $ch = curl_init();
+    //参数设置
+    curl_setopt($ch, CURLOPT_URL, $url);
+    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
+    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
+    curl_setopt($ch, CURLOPT_TIMEOUT, $timeOut);
+    curl_setopt($ch, CURLOPT_HEADER, 0);
+    curl_setopt($ch, CURLOPT_POST, 1);
+    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
+    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
+    if($header != '') {
+        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
+    }
+    $result = curl_exec($ch);
+    //连接失败
+    if($result == FALSE) {
+        //\think\Log::record('[ CURL ] ERROR ' . curl_error($ch)."\n".var_export(debug_backtrace(), true)."\n", 'error');
+    }
+    curl_close($ch);
+    return $result;
+}
+/**
+ * 发起HTTP GET请求
+ */
+function curl_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_TIMEOUT, 3);
+    curl_setopt($oCurl, CURLOPT_URL, $url);
+    curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
+    $sContent = curl_exec($oCurl);
+    $aStatus = curl_getinfo($oCurl);
+    $error = curl_error($oCurl);
+    curl_close($oCurl);
+    if($error) {
+        $sContent = file_get_contents($url);
+        return $sContent;
+    }
+
+    if(intval($aStatus["http_code"]) == 200) {
+        return $sContent;
+    } else {
+        return false;
+    }
+}
+//创建订单号
+function createUniqueNo($prifix = 'P',$id = 0)
+{
+    $s = 0;
+    $ms = 0;
+    list($ms, $s) = explode(' ', microtime());
+
+    $ms = substr($ms, 2, 6); //获取微妙
+
+    $rt = $prifix.date('ymdHis', $s).$ms.rand(10, 99).$id; //年月日时分秒.用户id对10取余.微秒
+
+    return $rt;
+}

+ 9 - 1
application/config.php

@@ -295,10 +295,18 @@ return [
         //插件纯净模式,插件启用后是否删除插件目录的application、public和assets文件夹
         'addon_pure_mode'       => true,
         //允许跨域的域名,多个以,分隔
-        'cors_request_domain'   => 'localhost,127.0.0.1',
+        'cors_request_domain'   => 'localhost,127.0.0.1,*',
         //版本号
         'version'               => '1.3.4.20220530',
         //API接口地址
         'api_url'               => 'https://api.fastadmin.net',
     ],
+
+    //我的
+
+    //小程序
+    'wxMiniProgram' => [
+        'appid'=>'wxfbf1d5e8ade16b4d', //公司测试
+        'secret'=>'eea1bbac593f085d726b752300ba6ee7', //公司测试
+    ],
 ];