行业知识
推特API(Twitter API)对接说明,用户code To Token换取
前期准备
���前准备、说明:目前对接推特api开发门户分为3个版本,分别是免费的,100美金一个月的基础版以及5000美金一个月的企业版,免费的目前就两个接口可以调用,所以想要对接和使用推特最基本的也需要付100美元一个月,他们的区别如下图,进入链接https://developer.twitter.com/en/portal/products/free 如下图:
https://developer.twitter.com/en/portal/products/free
而基本的就可以使用很多接口了,这里就不阐述了,可以自己去里面看。
那么推特我们如何对接呢?下面给大家讲一下详细的流程:
1:第一步需要我们创建应用,开发者应用,由于我是开通了基础版(100美金),所以我可以创建两个应用,里面有3个选项包括生产,测试等等,我们直接选择生产就好了,免费的只能创建一个应用,应用链接https://developer.twitter.com/en/portal/dashboard
2:创建成功以后还需要我们进去配置程序的公钥私钥,身份验证设置等等,做好对接前期工作。
上面配置完成以后我们就可以看到我们自己的客户ID了
开始对接
我们对接的是API v2的接口,大家一定要注意看接口文档,别看到1.1获取企业版的的去调别调不通。
说明:推特对接分为V1.1 、V2 以及企业版的Gnip2.0,这里目前使用的是V2的形式来对接的,V1.1对接一直报权限不足不给用,具体什么原因有知道的小伙伴可以告诉我一下,建议大家对接的时候去看一下 文档 。那么如何获取用户的code以及Token呢?下面直接上代码。
https://twitter.com/i/oauth2/authorize?client_id=c3dqYzExdmo4VmpNY2tjbnFPNDM6MTpjaQ&scope=tweet.read%20offline.access%20tweet.write%20tweet.moderate.write%20users.read%20follows.read%20follows.write&response_type=code&redirect_uri=http://8kvjtw.natappfree.cc/test/getTuiteCode&state=profile&code_challenge=0ioze5m20493ny2&code_challenge_method=plain参数说明:client_id = 上面图里面的客户IDscope = 你需要用户给你授权的权限,每个权限都是以%20分割,下图会详细介绍具体怎么来的response_type=code 这个是固定的,表示我们要去用户的coderedirect_uri = 回调地址,获取到code以后会回调到哪里,这里建议回调到前端页面,让前端在地址里面取出code返给后端,类似于这样的 http://8kvjtw.natappfree.cc/test/getTuiteCode?state=profile&code=VmtmRFlDaXdV....code的值state=自己随机定义字符串,回调里面会给你带回来的code_challenge=随机定义一串字符,但是换取Token的时候需要传一样的过去哦,这里重点记一下code_challenge_method=plain 表示不加密随机字符
scope :字段解释,可以去下图里面找出支持用户授权的权限标识就好
直接在浏览器里面打开会出现下面这样的,点击授权应用就会回调到我们上面设置的回调地址里面,并且里面会带两个参数,一个是code,另一个就是我们设置的state也会带给我们,参数都是拼接在回调地址后面的。
根据code换取token
Maven依赖
oauth.signpost signpost-core 1.2.1.2 oauth.signpost signpost-commonshttp4 1.2.1.2 com.twitter twitter-api-java-sdk 1.1.4 commons-httpclient commons-httpclient 3.1 com.google.guava guava 29.0-jre
推特相关配置、文档:https://developer.twitter.com/en/docs/authentication/oauth-2-0/user-access-token
/** * 推特相关配置 */public class TwitterConfig { /** * 客户id和客户私钥 */ public static final String CLIENT_ID = "c3dqYzExdmo4VmpNY2t1111MTpjaQ"; public static final String CLIENT_SECRET = "kfuA39dCX6tEG1111deXZHpOV-fjv9umx55ZdccCkNONjea"; /** * 应用KYE和私钥 */ public static final String CONSUMER_KEY = "lhyfiDV3nX1111ffGeHMR"; public static final String CONSUMER_SECRET = "BRNxnV5LxN23MlW4BCOdiSpQkQ1rn11119jtptduIkcwjB"; /** * 应用的TOKEN */ public static final String ACCESS_TOKEN = "1482941195941633-A8xyN5xuqCrRJwj111dbFgkbStu"; public static final String ACCESS_TOKEN_SECRET = "oZaKBphpooOR7GMBB3EFELIkU1111vzoXPAQ";} @Data@Accessors(chain = true)public class TwitterDto { /** * 获取的访问令牌 */ private String accessToken; /** * 刷新令牌 */ private String refreshToken;} /** * 根据code获取用户token * @param code 根据code换取token * @param refreshToken 根据token刷新token * @return */ public TwitterDto requestBearerToken(String code,String refreshToken) { try { String clientId = URLEncoder.encode(TwitterConfig.CLIENT_ID, "UTF-8"); String clientSecret = URLEncoder.encode(TwitterConfig.CLIENT_SECRET, "UTF-8"); //商户id和商户的私钥 String credentials = clientId + ":" + clientSecret; //对商户id和私钥机密一下 String base64Credentials = Base64.getEncoder().encodeToString(credentials.getBytes()); //这个地址一定要和获取code链接里面填的回调地址保持一致(恶心) String redirectURI = "http://8kvjtw.natappfree.cc/test/getTuiteCode"; //请求、换取Token的地址 URL url = new URL("https://api.twitter.com/2/oauth2/token"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Authorization", "Basic " + base64Credentials); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); connection.setDoOutput(true); connection.setDoInput(true); String data = ""; if(StringUtils.isBlank(refreshToken)){ //authorization_code、refresh_token、client_credentials //我们这里是根据code换取Token所以选择authorization_code String grantType = "authorization_code"; //获取令牌需要的参数 code_verifier 需要和获取code传入参数 code_challenge 保持一致 data = "grant_type=" + grantType + "&code=" + code + "&redirect_uri=" + redirectURI+ "&client_&client_secret="+TwitterConfig.CLIENT_SECRET+"&code_verifier=0ioze5m20493ny2"; }else{ //下面是通过刷新令牌的Token去换取新的Token,房子Token过期 //authorization_code、refresh_token、client_credentials String grantType = "refresh_token"; //刷新令牌需要的参数 data = "refresh_token="+refreshToken+"&grant_type=" + grantType + "&client_&client_secret="+TwitterConfig.CLIENT_SECRET+"&code_verifier=challenge"; } connection.getOutputStream().write(data.getBytes("UTF-8")); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder response = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); String jsonResponse = response.toString(); JSONObject json = JSON.parseObject(jsonResponse); TwitterDto twitterDto = new TwitterDto(); Object accessToken = json.get("access_token"); //我们实际使用Token twitterDto.setAccessToken(accessToken == null ? null : accessToken.toString()); //当我们使用的Token过期以后可以用这个来换取新的Token accessToken = json.get("refresh_token"); twitterDto.setRefreshToken(accessToken == null ? null : accessToken.toString()); return twitterDto; } catch (Exception e) { e.printStackTrace(); return null; } } @Slf4j@RestController@RequestMapping("/test")@Api(tags = "测试")@Transactional(isolation = Isolation.READ_COMMITTED)public class TestController extends BaseComponent { @Autowired private TwitterService twitterService; @GetMapping("getTuiteCode") @ApiOperation("测试推特code") public Map getTuiteCode(String code, String state) { Map map = new HashMap(); TwitterDto bearerToken = twitterService.requestBearerToken(code,null); //刷新一下令牌 //bearerToken = twitterService.requestBearerToken(code,bearerToken.getRefreshToken()); System.out.println("Bearer Token: " + bearerToken.getAccessToken()); map.put("Token", bearerToken.getAccessToken()); map.put("state", state); return map; }} 这就是一个完整的换取Token的流程,后面章节介绍如何使用Token操作用户相关数据
上一篇:没QQ邮箱怎么注册头条?
下一篇:Mac电脑设置hosts的方法