Miniapp.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. declare (strict_types = 1);
  3. namespace app\api\controller;
  4. use app\common\model\Third;
  5. class Miniapp extends Api
  6. {
  7. protected $noNeedLogin = ['login','getMobile','mockLogin'];
  8. public function login()
  9. {
  10. $code=$this->request->post('code');
  11. $config=[
  12. 'appid'=>site_config("uniapp.miniapp_id"),
  13. 'appsecret'=>site_config("uniapp.miniapp_secret")
  14. ];
  15. $mini = new \WeMini\Crypt($config);
  16. $data = $mini->session($code);
  17. $openid=$data['openid'];
  18. $unionid=isset($data['unionid'])?$data['unionid']:'';
  19. $avatar=$this->request->post('avatar');
  20. $nickname=$this->request->post('nickname');
  21. $mobile=$this->request->post('mobile');
  22. //判断是否启用账号绑定
  23. $third=Third::connect(Third::PLATFORM('微信小程序'), compact('openid', 'unionid', 'avatar', 'nickname', 'mobile'));
  24. $this->auth->loginByThirdPlatform(Third::PLATFORM('微信小程序'),$third);
  25. $token=$this->auth->getToken();
  26. $userinfo=$this->auth->userinfo();
  27. $this->success('登录成功',compact('token','userinfo'));
  28. }
  29. public function getMobile()
  30. {
  31. $code=$this->request->post('code');
  32. $config=[
  33. 'appid'=>site_config("uniapp.miniapp_id"),
  34. 'appsecret'=>site_config("uniapp.miniapp_secret")
  35. ];
  36. $mini = new \WeMini\Crypt($config);
  37. $result=$mini->getPhoneNumber($code);
  38. $this->success('',$result['phone_info']['phoneNumber']);
  39. }
  40. //模拟登陆
  41. public function mockLogin()
  42. {
  43. $openid=$this->request->post('openid');
  44. $third=Third::where(['openid'=>$openid,'platform'=>Third::PLATFORM('微信小程序')])->find();
  45. $this->auth->loginByThirdPlatform(Third::PLATFORM('微信小程序'),$third);
  46. $token=$this->auth->getToken();
  47. $userinfo=$this->auth->userinfo();
  48. $this->success('登录成功',compact('token','userinfo'));
  49. }
  50. }