Routine.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. namespace app\api\controller;
  3. use liuniu\MiniProgramService;
  4. use liuniu\UtilService;
  5. use think\Cache;
  6. use app\common\model\User;
  7. class Routine
  8. {
  9. /**
  10. * 无需登录的方法,同时也就不需要鉴权了
  11. * @var array
  12. */
  13. protected $noNeedLogin = ['*'];
  14. /**
  15. * 支付异步回调
  16. */
  17. public function notify()
  18. {
  19. ob_clean();
  20. MiniProgramService::handleNotify(input('cid',0));
  21. }
  22. /**
  23. * 小程序授权登录
  24. * @param Request $request
  25. * @return mixed
  26. * @throws \Psr\SimpleCache\InvalidArgumentException
  27. * @throws \think\db\exception\DataNotFoundException
  28. * @throws \think\db\exception\ModelNotFoundException
  29. * @throws \think\exception\DbException
  30. */
  31. public function mp_auth(Request $request)
  32. {
  33. $cache_key = '';
  34. list($code, $post_cache_key, $login_type) = UtilService::postMore([
  35. ['code', ''],
  36. ['cache_key', ''],
  37. ['login_type', 2]
  38. ], $request, true);
  39. $session_key = Cache::get('eb_api_code_' . $post_cache_key);
  40. if (!$code && !$session_key)
  41. $this->error('授权失败,参数有误');
  42. if ($code && !$session_key) {
  43. try {
  44. $userInfoCong = MiniProgramService::getUserInfo($code);
  45. $session_key = $userInfoCong['session_key'];
  46. $cache_key = md5(time() . $code);
  47. Cache::set('eb_api_code_' . $cache_key, $session_key, 86400);
  48. } catch (\Exception $e) {
  49. $this->error('获取session_key失败,请检查您的配置!');
  50. }
  51. }
  52. $data = UtilService::postMore([
  53. ['spread_spid', 0],
  54. ['spread_code', ''],
  55. ['iv', ''],
  56. ['encryptedData', ''],
  57. ]);//获取前台传的code
  58. try {
  59. //解密获取用户信息
  60. $userInfo = MiniProgramService::encryptor($session_key, $data['iv'], $data['encryptedData']);
  61. } catch (\Exception $e) {
  62. if ($e->getCode() == '-41003') return app('json')->fail('获取会话密匙失败');
  63. }
  64. if (!isset($userInfoCong['openid'])) return app('json')->fail('openid获取失败');
  65. if (!isset($userInfo['unionId'])) $userInfo['unionId'] = '';
  66. $userInfo['openId'] = $userInfoCong['openid'];
  67. $userInfo['spid'] = $data['spread_spid'];
  68. $userInfo['code'] = $data['spread_code'];
  69. $userInfo['session_key'] = $session_key;
  70. $userInfo['login_type'] = $login_type;
  71. $uid = User::setRoutineUser($userInfo);
  72. $user = User::where('uid', $uid)->find();
  73. $this->auth->direct($user['id']);
  74. // 设置推广关系
  75. User::setSpread(intval($data['spread_spid']), $user->id);
  76. return $this->success('登录成功', $this->auth->getUserinfo());
  77. }
  78. }