Service.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. namespace addons\yexam\library;
  3. use addons\ygame\model\YgameWechat;
  4. use app\common\model\User;
  5. use fast\Random;
  6. use think\Db;
  7. use think\exception\PDOException;
  8. /**
  9. *
  10. */
  11. class Service
  12. {
  13. public static function connect($type,$params = [])
  14. {
  15. $data = [
  16. 'type' => $type,
  17. 'openid' => $params['openid'],
  18. 'avatar' => $params['headimgurl'],
  19. 'nickname' => isset($params['nickname']) ? $params['nickname'] : '',
  20. ];
  21. $auth = \app\common\library\Auth::instance();
  22. $wechatUser = \app\admin\model\yexam\Third::get(['type'=>$type,'openid' => $params['openid']]);
  23. if ($wechatUser) {
  24. $user = User::get($wechatUser['user_id']);
  25. if (!$user) {
  26. return false;
  27. }
  28. $user->save(['nickname'=>$data['nickname'],'avatar'=>$data['avatar']]);
  29. $wechatUser->save($data);
  30. } else {
  31. // 先随机一个用户名,随后再变更为u+数字id
  32. $username = Random::alnum(20);
  33. $password = Random::alnum(6);
  34. $domain = request()->host();
  35. Db::startTrans();
  36. try {
  37. $result = $auth->register($username, $password, $username . '@' . $domain, '');
  38. if (!$result) {
  39. return false;
  40. }
  41. $user = $auth->getUser();
  42. $fields = [
  43. 'username' => 'wx' . $user->id,
  44. 'email' => 'wx' . $user->id . '@' . $domain,
  45. 'nickname'=>$data['nickname'],
  46. 'avatar'=>$data['avatar']
  47. ];
  48. // 更新会员资料
  49. $user = User::get($user->id);
  50. $user->save($fields);
  51. $data['user_id'] = $user->id;
  52. \app\admin\model\yexam\Third::create($data);
  53. Db::commit();
  54. } catch (PDOException $e) {
  55. Db::rollback();
  56. return false;
  57. }
  58. }
  59. return $auth->direct($user->id);
  60. }
  61. }