WxUserFacadeRepository.php 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. namespace App\Repositories\Eloquent;
  3. use App\Facades\UserFacade;
  4. use App\Repositories\Contracts\WxUserInterface;
  5. use GuzzleHttp\Client as httpClient;
  6. use Illuminate\Support\Facades\Redis;
  7. /**
  8. *
  9. * @author lilin
  10. *
  11. */
  12. class WxUserFacadeRepository extends BaseRepository implements WxUserInterface
  13. {
  14. public function getMPSession(string $code)
  15. {
  16. $url = str_replace(['APPID', 'SECRET', 'JSCODE'], [env('MP_APPID'), env('MP_APPSECRET'), $code], self::MP_JSCODE2SESSION_URL);
  17. try {
  18. $client = new httpClient();
  19. $res = $client->request('get', $url, []);
  20. $body = $res->getBody();
  21. $data = json_decode($body);
  22. $this->setLog(self::TYPENAME.'jscode2session 返回数据', $this->startTime, [$data]);
  23. return $this->response($data);
  24. } catch (\Exception $e) {
  25. $this->setLog(self::TYPENAME.'getAccessToken 远程请求失败', $this->startTime, [$e->getMessage()]);
  26. $this->error()->fail();
  27. }
  28. }
  29. public function getAccessToken(string $code)
  30. {
  31. $url = str_replace(['APPID', 'SECRET', 'CODE'], [env('MP_APPID'), env('MP_APPSECRET'), $code], self::URL_ACCESS_TOKEN);
  32. try {
  33. $client = new httpClient();
  34. $res = $client->request('get', $url, []);
  35. $body = $res->getBody();
  36. $data = json_decode($body);
  37. if (!isset($data->openid)){
  38. $this->setLog(self::TYPENAME.'getAccessToken 失败 没有找到openid', $this->startTime, [$data]);
  39. $this->error()->fail();
  40. }else{
  41. //成功,创建reids
  42. $redisKey = config('console.redis_key.auth_access_token').$data->openid;
  43. Redis::SET($redisKey, $data->access_token);
  44. Redis::EXPIRE($redisKey, $data->expires_in);
  45. return $this->response($data);
  46. }
  47. } catch (\Exception $e) {
  48. $this->setLog(self::TYPENAME.'getAccessToken 远程请求失败', $this->startTime, [$e->getMessage()]);
  49. $this->error()->fail();
  50. }
  51. }
  52. public function getUserInfo(string $accessToken, string $openid)
  53. {
  54. $url = str_replace(['ACCESS_TOKEN', 'OPENID',], [$accessToken, $openid], self::URL_USER_INFO);
  55. try {
  56. $client = new httpClient();
  57. $res = $client->request('get', $url, []);
  58. $body = $res->getBody();
  59. $data = json_decode($body);
  60. if (!isset($data->openid)){
  61. $this->setLog(self::TYPENAME.'getUserInfo 失败 没有找到openid', $this->startTime, [$data]);
  62. $this->error()->fail();
  63. }else{
  64. return $this->response($data);
  65. }
  66. } catch (\Exception $e) {
  67. $this->setLog(self::TYPENAME.'getUserInfo 远程请求失败', $this->startTime, [$e->getMessage()]);
  68. $this->error()->fail();
  69. }
  70. }
  71. }