Wechat.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. * @param string $openid 微信openid
  17. *
  18. * */
  19. public function phone_number(Custom $Custom){
  20. // 接口验签
  21. // $this->verify_sign();
  22. // 接收参数
  23. $code = request('code','');
  24. $openid = request('openid','');
  25. // 授权手机号结果
  26. $result = Mini::getUserPhone($code);
  27. // 如果所需字段不存在
  28. if( isset($result['error']) ) return json_send(['code'=>'error','msg'=>'授权失败','data'=>['error'=>$result['error']]]);
  29. // 如果所需字段不存在
  30. if( empty($result['purePhoneNumber']) ) return json_send(['code'=>'error','msg'=>'未获取到手机号','data'=>['error'=>'未获取到手机号']]);
  31. // 获取不包含区号的手机号(因为绑定手机号字段会有国际区号)
  32. $phone = $result['purePhoneNumber'];
  33. // 查询用户
  34. $custom = $Custom->getOneByPhone($phone);
  35. // 如果用户状态被拉黑,不允许登录
  36. if( !empty($custom['status']) ) return json_send(['code'=>'error','msg'=>'禁用账号','data'=>['error'=>'禁用账号']]);
  37. // 如果没有ID
  38. if( empty($custom['uid']) ) {
  39. // 注册账号
  40. $custom['uid'] = $Custom->add(['phone'=>$phone,'username'=>hide_phone($phone),'openid'=>$openid]);
  41. // 注册失败
  42. if( empty($custom['uid']) ) return json_send(['code'=>'error','msg'=>'注册失败,请重试','data'=>['error'=>'注册失败,请重试']]);
  43. }
  44. // 进行登录
  45. $token = $Custom->createLoginAuthcode($custom['uid'],time());
  46. // 返回结果
  47. return json_send(['code'=>'success','msg'=>'登录成功','data'=>$token]);
  48. }
  49. public function jscode2session()
  50. {
  51. $code = request('code','');
  52. // 授权手机号结果
  53. $result = Mini::jscode2session($code);
  54. if (!$result['openid']) return json_send(['code'=>'error','msg'=>'获取openid失败','data'=>$result['error']]);
  55. return json_send(['code'=>'success','msg'=>'获取openid成功','data'=>$result['openid']]);
  56. }
  57. }