Wechat.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. <?php namespace App\Http\Controllers\Api;
  2. use App\Http\Controllers\Api\Api;
  3. use App\Models\Custom;
  4. use App\Facades\Servers\WechatMini\Mini;
  5. /**
  6. * 微信接口
  7. *
  8. * @author 刘相欣
  9. *
  10. * */
  11. class Wechat extends Api{
  12. /**
  13. * 小程序手机号授权 /api/wechat/phone_number
  14. *
  15. * @param string $code 授权码
  16. *
  17. * */
  18. public function phone_number(Custom $Custom){
  19. // 接口验签
  20. // $this->verify_sign();
  21. // 接收参数
  22. $code = request('code','');
  23. // 授权结果
  24. $result = Mini::getUserPhone($code);
  25. // 如果所需字段不存在
  26. if( isset($result['error']) ) return json_send(['code'=>'error','msg'=>'授权失败','data'=>['error'=>$result['error']]]);
  27. // 如果所需字段不存在
  28. if( empty($result['purePhoneNumber']) ) return json_send(['code'=>'error','msg'=>'未获取到手机号','data'=>['error'=>'未获取到手机号']]);
  29. // 获取不包含区号的手机号(因为绑定手机号字段会有国际区号)
  30. $phone = $result['purePhoneNumber'];
  31. // 查询用户
  32. $custom = $Custom->getOneByPhone($phone);
  33. // 如果用户状态被拉黑,不允许登录
  34. if( !empty($custom['status']) ) return json_send(['code'=>'error','msg'=>'禁用账号','data'=>['error'=>'禁用账号']]);
  35. // 如果没有ID
  36. if( empty($custom['uid']) ) {
  37. // 注册账号
  38. $custom['uid'] = $Custom->add(['phone'=>$phone,'username'=>hide_phone($phone)]);
  39. // 注册失败
  40. if( empty($custom['uid']) ) return json_send(['code'=>'error','msg'=>'注册失败,请重试','data'=>['error'=>'注册失败,请重试']]);
  41. }
  42. // 进行登录
  43. $token = $Custom->createLoginAuthcode($custom['uid'],time());
  44. // 返回结果
  45. return json_send(['code'=>'success','msg'=>'登录成功','data'=>$token]);
  46. }
  47. }