User.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: zhengmingwei
  5. * Date: 2019/10/25
  6. * Time: 11:09 下午
  7. */
  8. namespace addons\unishop\controller;
  9. use addons\unishop\extend\Wechat;
  10. use addons\unishop\model\UserExtend;
  11. use app\common\library\Sms;
  12. use think\Cache;
  13. use think\Session;
  14. use think\Validate;
  15. use app\admin\model\weixin\User as WechatUser;
  16. class User extends Base
  17. {
  18. protected $noNeedLogin = ['login', 'status', 'authSession', 'decryptData', 'register', 'resetpwd', 'loginForWechatMini', 'loginForWeachPublic'];
  19. /**
  20. * 会员登录
  21. *
  22. * @param string $account 账号
  23. * @param string $password 密码
  24. */
  25. public function login()
  26. {
  27. $mobile = $this->request->post('mobile');
  28. $password = $this->request->post('password');
  29. if (!$mobile || !$password) {
  30. $this->error(__('Invalid parameters'));
  31. }
  32. $ret = $this->auth->login($mobile, $password);
  33. if ($ret) {
  34. $data = $this->auth->getUserinfo();
  35. $data['avatar'] = \addons\unishop\model\Config::getImagesFullUrl($data['avatar']);
  36. $this->success(__('Logged in successful'), $data);
  37. } else {
  38. $this->error($this->auth->getError());
  39. }
  40. }
  41. /**
  42. * 重置密码
  43. *
  44. * @param string $mobile 手机号
  45. * @param string $newpassword 新密码
  46. * @param string $captcha 验证码
  47. */
  48. public function resetpwd()
  49. {
  50. $mobile = $this->request->post("mobile");
  51. $newpassword = $this->request->post("password");
  52. $captcha = $this->request->post("captcha");
  53. if (!$newpassword || !$captcha) {
  54. $this->error(__('Invalid parameters'));
  55. }
  56. if (!Validate::regex($mobile, "^1\d{10}$")) {
  57. $this->error(__('Mobile is incorrect'));
  58. }
  59. $user = \app\common\model\User::getByMobile($mobile);
  60. if (!$user) {
  61. $this->error(__('User not found'));
  62. }
  63. $ret = Sms::check($mobile, $captcha, 'resetpwd');
  64. if (!$ret) {
  65. $this->error(__('Captcha is incorrect'));
  66. }
  67. Sms::flush($mobile, 'resetpwd');
  68. //模拟一次登录
  69. $this->auth->direct($user->id);
  70. $ret = $this->auth->changepwd($newpassword, '', true);
  71. if ($ret) {
  72. $this->success(__('Reset password successful'), 1);
  73. } else {
  74. $this->error($this->auth->getError());
  75. }
  76. }
  77. /**
  78. * 注册会员
  79. *
  80. * @param string $username 用户名
  81. * @param string $password 密码
  82. * @param string $email 邮箱
  83. * @param string $mobile 手机号
  84. */
  85. public function register()
  86. {
  87. $username = $this->request->post('username');
  88. $password = $this->request->post('password');
  89. $mobile = $this->request->post('mobile');
  90. $captcha = $this->request->post("captcha");
  91. if (!$username || !$password) {
  92. $this->error(__('Invalid parameters'));
  93. }
  94. if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
  95. $this->error(__('Mobile is incorrect'));
  96. }
  97. // $ret = Sms::check($mobile, $captcha, 'register');
  98. // if (!$ret) {
  99. // $this->error(__('Captcha is incorrect'));
  100. // }
  101. Sms::flush($mobile, 'register');
  102. $avatar = \addons\unishop\model\Config::getByName('avatar')['value'] ?? '';
  103. $ret = $this->auth->register($username, $password, '', $mobile, ['avatar' => $avatar]);
  104. if ($ret) {
  105. $data = ['userinfo' => $this->auth->getUserinfo()];
  106. $this->success(__('Sign up successful'), $data);
  107. } else {
  108. $this->error($this->auth->getError());
  109. }
  110. }
  111. /**
  112. * 更改用户信息
  113. */
  114. public function edit()
  115. {
  116. $userInfo = $this->auth->getUserinfo();
  117. $username = $this->request->post('username', $userInfo['username']);
  118. $mobile = $this->request->post('mobile', $userInfo['mobile']);
  119. $avatar = $this->request->post('avatar', $userInfo['avatar']);
  120. $user = \app\common\model\User::get($this->auth->id);
  121. $user->username = $username;
  122. $user->mobile = $mobile;
  123. $user->avatar = $avatar;
  124. if ($user->save()) {
  125. $this->success(__('Modified'), 1);
  126. } else {
  127. $this->error(__('Fail'), 0);
  128. }
  129. }
  130. /**
  131. * 登录状态
  132. */
  133. public function status()
  134. {
  135. $this->success('', $this->auth->isLogin());
  136. }
  137. /**
  138. * 微信小程序登录
  139. */
  140. public function authSession()
  141. {
  142. $platform = $this->request->header('platform');
  143. switch ($platform) {
  144. case 'MP-WEIXIN':
  145. $code = $this->request->get('code');
  146. $data = Wechat::authSession($code);
  147. // 如果有手机号码,自动登录
  148. if (isset($data['userInfo']['mobile']) && (!empty($data['userInfo']['mobile']) || $data['userInfo']['mobile'] != '')) {
  149. $this->auth->direct($data['userInfo']['id']);
  150. if ($this->auth->isLogin()) {
  151. $data['userInfo']['token'] = $this->auth->getToken();
  152. // 支付的时候用
  153. Cache::set('openid_' . $data['userInfo']['id'], $data['openid'], 7200);
  154. }
  155. }
  156. break;
  157. default:
  158. $data = [];
  159. }
  160. $this->success('', $data);
  161. }
  162. /**
  163. * 微信小程序消息解密
  164. */
  165. public function decryptData()
  166. {
  167. $iv = $this->request->post('iv');
  168. $encryptedData = $this->request->post('encryptedData');
  169. $app = Wechat::initEasyWechat('miniProgram');
  170. $decryptedData = $app->encryptor->decryptData(Session::get('session_key'), $iv, $encryptedData);
  171. $this->success('', $decryptedData);
  172. }
  173. /**
  174. * 微信小程序通过授权手机号登录
  175. */
  176. public function loginForWechatMini()
  177. {
  178. $iv = $this->request->post('iv');
  179. $encryptedData = $this->request->post('encryptedData');
  180. $app = Wechat::initEasyWechat('miniProgram');
  181. $decryptedData = $app->encryptor->decryptData(Session::get('session_key'), $iv, $encryptedData);
  182. if (isset($decryptedData['phoneNumber'])) {
  183. $openid = Session::get('openid');
  184. // 看看有没有这个mobile的用户
  185. $user = \addons\unishop\model\User::getByMobile($decryptedData['phoneNumber']);
  186. if ($user) {
  187. // 有 处理:1,把;user_extend对应的user删除;2,把user_extend表的user_id字段换成已存在的用户id
  188. $userExtend = UserExtend::getByOpenid($openid);
  189. if ($userExtend) {
  190. if ($userExtend['user_id'] != $user->id) {
  191. \addons\unishop\model\User::destroy($userExtend['user_id']);
  192. $userExtend->user_id = $user->id;
  193. $userExtend->save();
  194. }
  195. } else {
  196. UserExtend::create(['user_id' => $user->id, 'openid' => $openid]);
  197. }
  198. } else {
  199. // 没有
  200. $userExtend = UserExtend::getByOpenid($openid);
  201. if ($userExtend) {
  202. $user = \addons\unishop\model\User::get($userExtend->user_id);
  203. $user->mobile = $decryptedData['phoneNumber'];
  204. $user->save();
  205. } else {
  206. $params = [
  207. 'level' => 1,
  208. 'score' => 0,
  209. 'jointime' => time(),
  210. 'joinip' => $_SERVER['REMOTE_ADDR'],
  211. 'logintime' => time(),
  212. 'loginip' => $_SERVER['REMOTE_ADDR'],
  213. 'prevtime' => time(),
  214. 'status' => 'normal',
  215. 'avatar' => '',
  216. 'username' => __('Tourist'),
  217. 'mobile' => $decryptedData['phoneNumber']
  218. ];
  219. $user = \addons\unishop\model\User::create($params, true);
  220. UserExtend::create(['user_id' => $user->id, 'openid' => $openid]);
  221. }
  222. }
  223. $userInfo['id'] = $user->id;
  224. $userInfo['openid'] = $openid;
  225. $userInfo['mobile'] = $user->mobile;
  226. $userInfo['avatar'] = \addons\unishop\model\Config::getImagesFullUrl($user->avatar);
  227. $userInfo['username'] = $user->username;
  228. $this->auth->direct($userInfo['id']);
  229. if ($this->auth->isLogin()) {
  230. $userInfo['token'] = $this->auth->getToken();
  231. // 支付的时候用
  232. Cache::set('openid_' . $userInfo['id'], $openid, 7200);
  233. }
  234. $this->success('', $userInfo);
  235. } else {
  236. $this->error(__('Logged in failed'));
  237. }
  238. }
  239. /**
  240. * 微信公众号登陆
  241. */
  242. public function loginForWeachPublic() {
  243. $code = $this->request->param('code');
  244. $wxModel = new \app\admin\model\weixin\Config();
  245. $wxConfigData = $wxModel->where([
  246. 'group' => 'weixin', 'name' => ['in', 'appid,appsecret']
  247. ])->select();
  248. $wxConfig = [];
  249. foreach ($wxConfigData as $val) {
  250. $wxConfig[$val['name']] = $val['value'];
  251. }
  252. $oauth2Url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$wxConfig['appid']."&secret=".$wxConfig['appsecret']."&code=$code&grant_type=authorization_code";
  253. $oauth2 = $this->getJson($oauth2Url);
  254. // 获得 access_token 和openid
  255. $access_token = $oauth2["access_token"];
  256. $openid = $oauth2['openid'];
  257. $get_user_info_url = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN";
  258. try {
  259. $userinfo = $this->getJson($get_user_info_url);
  260. } catch (\Exception $e) {
  261. $this->error('授权失败', '', ['message' => $e->getMessage(), 'line' => $e->getLine()]);
  262. }
  263. // $res = json_decode($userinfo,true);
  264. // $res = [];
  265. // $res["openid"]= "oHKyV1bbviniWh4sxBLY8ZUYuKBE";
  266. // $res["nickname"]="科";
  267. // $res["sex"]=1;
  268. // $res["language"]='zh_CN';
  269. // $res["country"]='中国';
  270. // $res["province"]='山东';
  271. // $res["city"]='临沂';
  272. // $res["headimgurl"]="http://thirdwx.qlogo.cn/mmopen/vi_32/ZbiayBPWEriccRkpicE5k5K1zbt9of32ktNCSVg60dGgPdN9ahIy79Yhnx2PmBVEqNeDUy5TwltF1ibCJzsT0uM3EA/132";
  273. //授权成功后
  274. $uid = WechatUser::onWechatOauthAfter($userinfo,0,0);
  275. //登录
  276. $ret = $this->auth->direct($uid);
  277. if ($ret) {
  278. $data = [];
  279. if ($this->auth->isLogin()) {
  280. $data['token'] = $this->auth->getToken();
  281. $userinfo = $this->auth->getUserinfo();
  282. $studentModel = new \app\admin\model\unishop\Student();
  283. $studentinfo = $studentModel->where(["user_id"=>$userinfo["id"]])->find();
  284. if($studentinfo) { // 已经绑定
  285. $data["is_bond"] = 1;
  286. } else {
  287. $data["is_bond"] = 0;
  288. }
  289. $this->success('授权登陆成功!', $data);
  290. }
  291. $this->error("登陆失败!请重新获取授权");
  292. } else {
  293. $this->error($this->auth->getError());
  294. }
  295. }
  296. private function getJson($url){
  297. $ch = curl_init();
  298. curl_setopt($ch, CURLOPT_URL, $url);
  299. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  300. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
  301. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  302. $output = curl_exec($ch);
  303. curl_close($ch);
  304. return json_decode($output, true);
  305. }
  306. // /**
  307. // * 微信公众号登陆
  308. // */
  309. // public function loginForWeachPublic() {
  310. //
  311. // $code = $this->request->post('code');
  312. // $data = Wechat::authSession($code);
  313. //
  314. // // 如果有手机号码,自动登录
  315. // if (isset($data['userInfo']['mobile']) && (!empty($data['userInfo']['mobile']) || $data['userInfo']['mobile'] != '')) {
  316. // $this->auth->direct($data['userInfo']['id']);
  317. // if ($this->auth->isLogin()) {
  318. // $data['userInfo']['token'] = $this->auth->getToken();
  319. // // 支付的时候用
  320. // Cache::set('openid_' . $data['userInfo']['id'], $data['openid'], 7200);
  321. // }
  322. // }
  323. //
  324. // $this->success('', $data);
  325. // }
  326. }