目前國內常見的第三方開放平臺有: QQ開放平臺 微信開放平臺 新浪微博開放平臺 我們可以通過集成這些第三方平臺來實現: 第三方登錄 內容分享到第三方平臺 獲取第三方平臺用戶資源 ...... 下麵以新浪微博開放平臺為例看下Java系統具體的集成步驟,QQ和微信類似,只需少許修改(具體請參考源碼中示例 ...
目前國內常見的第三方開放平臺有:
- QQ開放平臺
- 微信開放平臺
- 螞蟻金服開放平臺
- 新浪微博開放平臺
- 第三方登錄
- 第三方支付
- 內容分享到第三方平臺
- 獲取第三方平臺用戶資源
- ......
/** * Step 1: 重定向到sina微博登錄,請求授權碼CODE * https://api.weibo.com/oauth2/authorize?client_id=123050457758183&redirect_uri=http://www.example.com/response&response_type=code * * @param resp * @throws Exception */ @RequestMapping("/weibo/login") public void weiboLogin(HttpServletResponse resp) throws Exception { String authorizeUrl = baseAuthorizeUrl + "?client_id=" + appKey + "&redirect_uri=" + redirectUri + "&response_type=code"; resp.sendRedirect(authorizeUrl); }baseAuthorizeUrl為 https://api.weibo.com/oauth2/authorize client_id為 平臺應用對應的appKey 2.登錄回調,獲取授權碼code
/** * Step 2: 登錄回調,獲取Code * * @param req * @throws Exception */ @RequestMapping("/weibo/callback") public String qqCallback(HttpServletRequest req) throws Exception { String code = req.getParameter("code"); //獲取Access Token,並返回給頁面 return getAccessToken(code); }
3.通過 授權code獲取access_token
/** * Step 3: 通過code獲取access_token * * @param resp * @param code 認證碼 * @return * @throws Exception */ private String getAccessToken(String code) throws Exception { //拼接請求URL String tokenUrl = baseTokenUrl + "?client_id=" + appKey + "&client_secret=" + appSecret + "&grant_type=authorization_code&code=" + code + "&redirect_uri=" + redirectUri; //發送post請求,獲取響應字元串 String resp = RestHttpClient.sendHttpPostRequest(tokenUrl); return resp; }
baseTokenUrl為 https://api.weibo.com/oauth2/access_token
4.通過token和uid調用微博api,例如查詢微博用戶信息
/** * Step 4: 根據Token和用戶ID獲取用戶信息 * access_token:2.00AZrTrB5jlucE809b31fc07I9H_XC, uid:1706396054 * * @param access_token * @param uid * @return * @throws Exception */ @RequestMapping("/weibo/userInfo") public String getUserInfo(String access_token, String uid) throws Exception { //拼接請求URL String userInfoUrl = baseUserInfoUrl + "?access_token=" + access_token + "&uid=" + uid; System.out.println(userInfoUrl); //發送請求,獲取響應字元串 String resp = RestHttpClient.sendHttpGetRequest(userInfoUrl); //返迴響應字元串 return resp; }
baseUserInfoUrl為 https://api.weibo.com/2/users/show.json
源碼地址:https://github.com/13babybear/bounter-openapi