1.controller
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
@Slf4j
@Api(tags = "小程序认证")
@CrossOrigin
@RequestMapping("/idp/wechat")
@RestController
public class WeChatIdpController {
@Autowired
private AuthenticationContext context;
@Autowired
private HttpServletRequest request;
@Autowired
private WeChatIdpService weChatIdpService;
@ApiOperation(value = "根据Code登录")
@GetMapping(value = "/login")
public ResponseData<WeChatTokenVo> login(@Validated @RequestParam("code") String code) {
String openId = weChatIdpService.getOpenId(code);
if (StringUtils.isNullOrEmpty(openId)){
return ResponseData.success(WeChatTokenVo.create(-2, "获取OPENID失败") );
}
UserManager manager = context.getObject(UserManager.class);
ApiResult<Token> tokenResult = manager.loginByOpenId(openId);
if (tokenResult.isSuccessful()){
return ResponseData.success(WeChatTokenVo.create(0, "success")
.accessToken(tokenResult.getData().getAccessToken())
.openId(openId));
}
if (tokenResult.getMessage().contains("OpenIdNotFound")){
return ResponseData.success(WeChatTokenVo.create(-1,"用户未注册").openId(openId));
}
return ResponseData.success(WeChatTokenVo.create(-3, "服务器内部错误"));
}
@ApiOperation(value = "根据Code注册、登录")
@GetMapping(value = "/register")
public ResponseData<WeChatTokenVo> register(@Validated @RequestParam("co
小程序获取openid以及注册登录
于 2022-11-28 16:42:18 首次发布
本文详细介绍了小程序中如何获取openid,以及利用openid进行用户注册和登录的实现步骤,包括微信API的调用、openid的验证和结合自身系统的用户管理。通过实例解析关键代码和注意事项,帮助开发者理解这一核心功能。
摘要由CSDN通过智能技术生成