| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373 | <?php/** * Created by PhpStorm. * User: zhengmingwei * Date: 2019/10/25 * Time: 11:09 下午 */namespace addons\unishop\controller;use addons\unishop\extend\Wechat;use addons\unishop\model\UserExtend;use app\common\library\Sms;use think\Cache;use think\Session;use think\Validate;use app\admin\model\weixin\User as WechatUser;class User extends Base{    protected $noNeedLogin = ['login', 'status', 'authSession', 'decryptData', 'register', 'resetpwd', 'loginForWechatMini', 'loginForWeachPublic'];    /**     * 会员登录     *     * @param string $account 账号     * @param string $password 密码     */    public function login()    {        $mobile = $this->request->post('mobile');        $password = $this->request->post('password');        if (!$mobile || !$password) {            $this->error(__('Invalid parameters'));        }        $ret = $this->auth->login($mobile, $password);        if ($ret) {            $data = $this->auth->getUserinfo();            $data['avatar'] = \addons\unishop\model\Config::getImagesFullUrl($data['avatar']);            $this->success(__('Logged in successful'), $data);        } else {            $this->error($this->auth->getError());        }    }    /**     * 重置密码     *     * @param string $mobile 手机号     * @param string $newpassword 新密码     * @param string $captcha 验证码     */    public function resetpwd()    {        $mobile = $this->request->post("mobile");        $newpassword = $this->request->post("password");        $captcha = $this->request->post("captcha");        if (!$newpassword || !$captcha) {            $this->error(__('Invalid parameters'));        }        if (!Validate::regex($mobile, "^1\d{10}$")) {            $this->error(__('Mobile is incorrect'));        }        $user = \app\common\model\User::getByMobile($mobile);        if (!$user) {            $this->error(__('User not found'));        }        $ret = Sms::check($mobile, $captcha, 'resetpwd');        if (!$ret) {            $this->error(__('Captcha is incorrect'));        }        Sms::flush($mobile, 'resetpwd');        //模拟一次登录        $this->auth->direct($user->id);        $ret = $this->auth->changepwd($newpassword, '', true);        if ($ret) {            $this->success(__('Reset password successful'), 1);        } else {            $this->error($this->auth->getError());        }    }    /**     * 注册会员     *     * @param string $username 用户名     * @param string $password 密码     * @param string $email 邮箱     * @param string $mobile 手机号     */    public function register()    {        $username = $this->request->post('username');        $password = $this->request->post('password');        $mobile = $this->request->post('mobile');        $captcha = $this->request->post("captcha");        if (!$username || !$password) {            $this->error(__('Invalid parameters'));        }        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {            $this->error(__('Mobile is incorrect'));        }//        $ret = Sms::check($mobile, $captcha, 'register');//        if (!$ret) {//            $this->error(__('Captcha is incorrect'));//        }        Sms::flush($mobile, 'register');        $avatar = \addons\unishop\model\Config::getByName('avatar')['value'] ?? '';        $ret = $this->auth->register($username, $password, '', $mobile, ['avatar' => $avatar]);        if ($ret) {            $data = ['userinfo' => $this->auth->getUserinfo()];            $this->success(__('Sign up successful'), $data);        } else {            $this->error($this->auth->getError());        }    }    /**     * 更改用户信息     */    public function edit()    {        $userInfo = $this->auth->getUserinfo();        $username = $this->request->post('username', $userInfo['username']);        $mobile = $this->request->post('mobile', $userInfo['mobile']);        $avatar = $this->request->post('avatar', $userInfo['avatar']);        $user = \app\common\model\User::get($this->auth->id);        $user->username = $username;        $user->mobile = $mobile;        $user->avatar = $avatar;        if ($user->save()) {            $this->success(__('Modified'), 1);        } else {            $this->error(__('Fail'), 0);        }    }    /**     * 登录状态     */    public function status()    {        $this->success('', $this->auth->isLogin());    }    /**     * 微信小程序登录     */    public function authSession()    {        $platform = $this->request->header('platform');        switch ($platform) {            case 'MP-WEIXIN':                $code = $this->request->get('code');                $data = Wechat::authSession($code);                // 如果有手机号码,自动登录                if (isset($data['userInfo']['mobile']) && (!empty($data['userInfo']['mobile']) || $data['userInfo']['mobile'] != '')) {                    $this->auth->direct($data['userInfo']['id']);                    if ($this->auth->isLogin()) {                        $data['userInfo']['token'] = $this->auth->getToken();                        // 支付的时候用                        Cache::set('openid_' . $data['userInfo']['id'], $data['openid'], 7200);                    }                }                break;            default:                $data = [];        }        $this->success('', $data);    }    /**     * 微信小程序消息解密     */    public function decryptData()    {        $iv = $this->request->post('iv');        $encryptedData = $this->request->post('encryptedData');        $app = Wechat::initEasyWechat('miniProgram');        $decryptedData = $app->encryptor->decryptData(Session::get('session_key'), $iv, $encryptedData);        $this->success('', $decryptedData);    }    /**     * 微信小程序通过授权手机号登录     */    public function loginForWechatMini()    {        $iv = $this->request->post('iv');        $encryptedData = $this->request->post('encryptedData');        $app = Wechat::initEasyWechat('miniProgram');        $decryptedData = $app->encryptor->decryptData(Session::get('session_key'), $iv, $encryptedData);        if (isset($decryptedData['phoneNumber'])) {            $openid = Session::get('openid');            // 看看有没有这个mobile的用户            $user = \addons\unishop\model\User::getByMobile($decryptedData['phoneNumber']);            if ($user) {                // 有 处理:1,把;user_extend对应的user删除;2,把user_extend表的user_id字段换成已存在的用户id                $userExtend = UserExtend::getByOpenid($openid);                if ($userExtend) {                    if ($userExtend['user_id'] != $user->id) {                        \addons\unishop\model\User::destroy($userExtend['user_id']);                        $userExtend->user_id = $user->id;                        $userExtend->save();                    }                } else {                    UserExtend::create(['user_id' => $user->id, 'openid' => $openid]);                }            } else {                // 没有                $userExtend = UserExtend::getByOpenid($openid);                if ($userExtend) {                    $user = \addons\unishop\model\User::get($userExtend->user_id);                    $user->mobile = $decryptedData['phoneNumber'];                    $user->save();                } else {                    $params = [                        'level'    => 1,                        'score'    => 0,                        'jointime'  => time(),                        'joinip'    => $_SERVER['REMOTE_ADDR'],                        'logintime' => time(),                        'loginip'   => $_SERVER['REMOTE_ADDR'],                        'prevtime'  => time(),                        'status'    => 'normal',                        'avatar'    => '',                        'username'  => __('Tourist'),                        'mobile'    => $decryptedData['phoneNumber']                    ];                    $user = \addons\unishop\model\User::create($params, true);                    UserExtend::create(['user_id' => $user->id, 'openid' => $openid]);                }            }            $userInfo['id'] = $user->id;            $userInfo['openid'] = $openid;            $userInfo['mobile'] = $user->mobile;            $userInfo['avatar'] = \addons\unishop\model\Config::getImagesFullUrl($user->avatar);            $userInfo['username'] = $user->username;            $this->auth->direct($userInfo['id']);            if ($this->auth->isLogin()) {                $userInfo['token'] = $this->auth->getToken();                // 支付的时候用                Cache::set('openid_' . $userInfo['id'], $openid, 7200);            }            $this->success('', $userInfo);        } else {            $this->error(__('Logged in failed'));        }    }    /**     * 微信公众号登陆     */    public function loginForWeachPublic() {        $code = $this->request->param('code');        $wxModel = new \app\admin\model\weixin\Config();        $wxConfigData = $wxModel->where([            'group' => 'weixin', 'name' => ['in', 'appid,appsecret']        ])->select();        $wxConfig = [];        foreach ($wxConfigData as $val) {            $wxConfig[$val['name']] = $val['value'];        }        $oauth2Url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$wxConfig['appid']."&secret=".$wxConfig['appsecret']."&code=$code&grant_type=authorization_code";        $oauth2 = $this->getJson($oauth2Url);        // 获得 access_token 和openid        $access_token = $oauth2["access_token"];        $openid = $oauth2['openid'];        $get_user_info_url = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN";        try {            $userinfo = $this->getJson($get_user_info_url);        } catch (\Exception $e) {            $this->error('授权失败', '', ['message' => $e->getMessage(), 'line' => $e->getLine()]);        }//        $res = json_decode($userinfo,true);//        $res = [];//        $res["openid"]= "oHKyV1bbviniWh4sxBLY8ZUYuKBE";//        $res["nickname"]="科";//        $res["sex"]=1;//        $res["language"]='zh_CN';//        $res["country"]='中国';//        $res["province"]='山东';//        $res["city"]='临沂';//        $res["headimgurl"]="http://thirdwx.qlogo.cn/mmopen/vi_32/ZbiayBPWEriccRkpicE5k5K1zbt9of32ktNCSVg60dGgPdN9ahIy79Yhnx2PmBVEqNeDUy5TwltF1ibCJzsT0uM3EA/132";        //授权成功后        $uid = WechatUser::onWechatOauthAfter($userinfo,0,0);        //登录        $ret = $this->auth->direct($uid);        if ($ret) {            $data = [];            if ($this->auth->isLogin()) {                $data['token'] = $this->auth->getToken();                $userinfo = $this->auth->getUserinfo();                $studentModel = new \app\admin\model\unishop\Student();                $studentinfo = $studentModel->where(["user_id"=>$userinfo["id"]])->find();                if($studentinfo) { // 已经绑定                    $data["is_bond"] = 1;                } else {                    $data["is_bond"] = 0;                }                $this->success('授权登陆成功!', $data);            }            $this->error("登陆失败!请重新获取授权");        } else {            $this->error($this->auth->getError());        }    }    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);    }//    /**//     * 微信公众号登陆//     *///    public function loginForWeachPublic() {////        $code = $this->request->post('code');//        $data = Wechat::authSession($code);////        // 如果有手机号码,自动登录//        if (isset($data['userInfo']['mobile']) && (!empty($data['userInfo']['mobile']) || $data['userInfo']['mobile'] != '')) {//            $this->auth->direct($data['userInfo']['id']);//            if ($this->auth->isLogin()) {//                $data['userInfo']['token'] = $this->auth->getToken();//                // 支付的时候用//                Cache::set('openid_' . $data['userInfo']['id'], $data['openid'], 7200);//            }//        }////        $this->success('', $data);//    }}
 |