AppController.php 2.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: guanxl
  5. * Date: 2018/9/7
  6. * Time: 14:07
  7. */
  8. namespace App\Http\Controllers;
  9. use App\Services\CookieService;
  10. use Illuminate\Http\Request;
  11. use Illuminate\Support\Facades\Log;
  12. use Illuminate\Support\Facades\Redis;
  13. use App\Libs\Curl;
  14. class AppController
  15. {
  16. public function index(Request $request){
  17. Log::info('1232');
  18. $token = $request->get("token");
  19. $data = Redis::hGetAll("oauth:".$token);
  20. if($data){
  21. CookieService::setOauth($data);
  22. header("location:http://activity.test.care001.cn/brainstorming?activity_id=709");
  23. }
  24. }
  25. /**
  26. * 根据code获取网页授权access_token
  27. */
  28. public function getAccessTokenByCode($code) {
  29. $uri = sprintf("https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code", env("WX_APP_ID"), env("WX_APP_SECRET"), $code);
  30. Log::info($uri);
  31. $curl = new Curl($uri);
  32. $curl->httpHeader('Content-Type', 'application/json');
  33. $res = $curl -> httpGet();
  34. $resData = json_decode($res, true);
  35. if(isset($resData['access_token'])){
  36. return $resData;
  37. }
  38. return null;
  39. }
  40. /**
  41. * 根据openid和access_token获取用户信息,前提是scope = snsapi_userinfo
  42. */
  43. public function getUserInfo(Request $request) {
  44. $code = $request -> get("code");
  45. $activity_id = $request -> get("activity_id");
  46. $access = $this->getAccessTokenByCode($code);
  47. if(empty($access)) {
  48. return null;
  49. }
  50. $uri = sprintf("https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN", $access['access_token'], $access['openid']);
  51. $curl = new Curl($uri);
  52. $curl->httpHeader('Content-Type', 'application/json');
  53. $res = $curl -> httpGet();
  54. $resData = json_decode($res, true);
  55. if(isset($resData['openid'])){
  56. $data["oauth_open_id"] = $resData['openid'];
  57. $data["oauth_avatar"] = $resData['headimgurl'];
  58. $data["oauth_nickname"] = $resData['nickname'];
  59. $data["oauth_platform"] = "wechat";
  60. $data["oauth_guid"] = $resData['openid'];
  61. CookieService::setOauth($data);
  62. }
  63. header("location:" . env("WEB_URL") . "?activity_id=$activity_id");
  64. }
  65. }