抖音授权登录-获取用户授权调用凭证

实现微信小程序获取抖音授权,使用Java实现抖音授权登录,您需要使用抖音开放平台提供的API

第一步 :抖音获取授权码

前提条件

•需要去官网为应用申请 scope 的使用权限。

•需要在本接口的 scope 传参中填上需要用户授权的 scope,多个 scope 以逗号分割。

•用户授权通过后,应用有权限通过 access_token 调用相应接口。

我这边是实现的微信小程序绑定抖音,附上微信小程序代码:

<view class="container">
	  <button class="login-btn"  @click="handleDouyinLogin">登录抖音2</button>
	  <view class="web-view-container" v-if="aDouyinLogin.showWebView">
	    <web-view :src="aDouyinLogin.authUrl">{aDouyinLogin.loading}}">登录中...</view>
	</view>

const aDouyinLogin = ref({

    showWebView: false,
    authUrl: 'https://***/api/dy/codeauth',
    loading: false,
  });

// 点击登录按钮,打开抖音授权页
const handleDouyinLogin = () => {

     aDouyinLogin.value.loading =true
     aDouyinLogin.value.showWebView =true
};
// 接收 web-view 消息(后端回调后传递的信息)
const handleMessage = ((e) => {

    const { data } = e.detail;
    if (data && data.type === 'douyin_login') {

      // 后端返回的登录结果
      handleLoginResult(data);
    }
  });

  // 处理登录结果
const  handleLoginResult= ((result) => { 
    //(result) { 
     aDouyinLogin.value.loading = false
    if (result.success) {

      // 登录成功,存储用户信息和会话令牌
      wx.setStorageSync('douyin_user_info', result.userInfo);
      wx.setStorageSync('douyin_session_token', result.sessionToken);
      wx.showToast({

        title: '登录成功',
        icon: 'success'
      });
      
      // 跳转到首页或指定页面
      setTimeout(() => {

        wx.switchTab({ url: '/pages/index/index' });
      }, 1500);
    } else {

      // 登录失败
      wx.showToast({

        title: result.error || '登录失败',
        icon: 'none'
      });
    }
  });

  // 关闭 web-view(用户手动取消授权时调用)
const  closeWebView = () => {

     aDouyinLogin.value.showWebView = false
  }
  

后台代码:

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping(“/api/dy”)
@Api(tags = {“抖音API”})
public class DouyinController {

@Value(“${douyin.open.authorize_url}”)
private String authorizeUrl = “”;
@Value(“${douyin.open.client_key}”)
private String clientKey;
@Value(“${douyin.open.client_secret}”)
private String clientSecret;
@Value(“${douyin.open.redirect_uri}”)
private String redirectUri;

/**
* 抖音授权登录
*
* @throws IOException
*/
@GetMapping(value = “codeauth”)
public void codeauth(HttpServletResponse response) throws IOException {

Map<String, String> params = new HashMap<>();
params.put(“redirect_uri”, redirectUri);
params.put(“client_key”, clientKey);
params.put(“response_type”, “code”);
params.put(“scope”, “user_info,trial.whitelist”);
params.put(“state”, UUID.randomUUID().toString().replace(“-“, “”));
StringBuilder urlBuilder = new StringBuilder(authorizeUrl);
urlBuilder.append(“?”);
for (Map.Entry<String, String> param : params.entrySet()) {

urlBuilder.append(param.getKey()).append(“=”).append(param.getValue()).append(“&”);
}
urlBuilder.deleteCharAt(urlBuilder.length() – 1); //
// return urlBuilder.toString();
response.sendRedirect(urlBuilder.toString());
}

/**
* 抖音授权登录
*
* @throws IOException
*/
@PostMapping(value = “codeauth”)
public String codeauth() {

Map<String, String> params = new HashMap<>();
params.put(“redirect_uri”, redirectUri);
params.put(“client_key”, clientKey);
params.put(“response_type”, “code”);
params.put(“scope”, “user_info,trial.whitelist”);
params.put(“state”, UUID.randomUUID().toString().replace(“-“, “”));
StringBuilder urlBuilder = new StringBuilder(authorizeUrl);
urlBuilder.append(“?”);
for (Map.Entry<String, String> param : params.entrySet()) {

urlBuilder.append(param.getKey()).append(“=”).append(param.getValue()).append(“&”);
}
urlBuilder.deleteCharAt(urlBuilder.length() – 1); //
return urlBuilder.toString();
}

/**
* 抖音授权回调
*
* @param request
* @return
*/
@RequestMapping(value = “authCallback”)
public void authCallback(HttpServletRequest request) throws Exception {

log.error(“进入了回调抖音授权回调,回调响应是:{}”, JSON.toJSONString(request.getParameterMap()));
String code = request.getParameter(“code”);
String state = request.getParameter(“state”);
log.error(“进入了回调抖音授权回调,回调响应code是:{}”, code);
log.error(“进入了回调抖音授权回调,回调响应state是:{}”, state);
getAccessToken(code);
}

@RequestMapping(value = “getAccessToken”)
public String getAccessToken(String code) throws Exception {

String url = “https://open.douyin.com/oauth/access_token/”;
try {

Map<String, String> params = new HashMap<>();
params.put(“client_key”, clientKey);
params.put(“client_secret”, clientSecret);
params.put(“grant_type”, “authorization_code”);
params.put(“code”, code);

HttpRequest post = HttpUtil.createPost(url);
// 添加请求头
post.header(“content-type”, “application/json”);
String jsonBody = JSON.toJSONString(params);
log.error(“jsonBody{}:”, jsonBody);
post.body(jsonBody);
HttpResponse response = post.execute();
if (response.getStatus() != 200) {

System.out.println(“请求获取accessToken失败”);
}
log.error(“response{}:”, response);
if (response.getStatus() == 200) {

JSONObject result = new JSONObject(response.body());
log.error(“response{}:”, result.get(“data”));
if (result.optString(“message”, “error”).equals(“success”)) {

DyAccessToken dyAccessToken = com.alibaba.fastjson2.JSONObject.parseObject(result.get(“data”).toString(), DyAccessToken.class);
String newAccessToken = dyAccessToken.getAccessToken();
long expiresIn = result.optLong(“expires_in”, 7200); // 默认7200秒
// 保存到缓存
return newAccessToken;
} else {

throw new Exception(“获取accessToken失败: ” + result);
}
} else {

throw new Exception(“HTTP请求失败,状态码: ” + response.getStatus());
}
} catch (Exception e) {

System.err.println(“获取token: ” + e.getMessage());
e.printStackTrace();
}
return “”;
}
}

© 版权声明
THE END
如果内容对您有所帮助,就支持一下吧!
点赞0 分享
幻儿朵朵FZ的头像 - 宋马
评论 抢沙发

请登录后发表评论

    暂无评论内容