WeChat scan code login-java

 

step:

1. WeChat open platform registration https://open.weixin.qq.com/

2. Improve developer information

3. Apply to create a website application 

4. Fill in the corresponding information and wait for the approval

important point:

Apply to create a website application authorization callback address must be a domain name and cannot use ip or port 

af9c1147a28843ba8813c02fe79976ec.png

If your callback address is www.test.com/login/callBack, you only need to fill in www.test.com here, and you need to fill in the specific callback address in your code


Backend development:

process:

1. Obtain WeChat QR code

2. The user scans the code to confirm the login to generate code and state, WeChat will bring the code and state according to the callback address

3. Change the access_token according to the code and do local operations

code:

<!-这里用到的依赖-->
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.8.11</version>
</dependency>
#微信appid应用唯一标识
wx.open.app_id=wx123456
#微信appSecret
wx.open.app_secret=3e8de831138d
#回调地址 这里是具体的回调地址
wx.open.redirect_url=http://www.test.com/wxLogin/callBack
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class ConstantPropertiesUtil implements InitializingBean {

    @Value("${wx.open.app_id}")
    private String appId;

    @Value("${wx.open.app_secret}")
    private String appSecret;

    @Value("${wx.open.redirect_url}")
    private String redirectUrl;

    public static String WX_OPEN_APP_ID;
    public static String WX_OPEN_APP_SECRET;
    public static String WX_OPEN_REDIRECT_URL;

    
    @Override
    public void afterPropertiesSet() throws Exception {
        WX_OPEN_APP_ID = appId;
        WX_OPEN_APP_SECRET = appSecret;
        WX_OPEN_REDIRECT_URL = redirectUrl;
    }
}

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/wxLogin")
public class WeChatLogin {


    @ApiOperation(value = "获取微信二维码")
    @GetMapping("/getWxCode")
    public ApiResult getWxCode() {
         //微信开放平台授权baseUrl
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";
        String redirectUrl = ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL;
        try {
            redirectUrl = URLEncoder.encode(redirectUrl, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
       
        String qrcodeUrl = String.format(
                baseUrl,
                ConstantPropertiesUtil.WX_OPEN_APP_ID,
                redirectUrl,
        //这里的onlineEdu 微信建议第三方带上这个参数 可随机为任何
                "onlineEdu");
        return ApiResult.successWithObject("redirect:" + qrcodeUrl);
    }


    @ApiOperation(value = "回调地址")
    @GetMapping ("/callBack")
    public ApiResult callBack(
            @RequestParam("code") String code,
            @RequestParam("state") String state,
            ) throws Exception{

   
        //获取access_token
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
        url = url.replace("APPID", ConstantPropertiesUtil.WX_OPEN_APP_ID)
                .replace("SECRET", ConstantPropertiesUtil.WX_OPEN_APP_SECRET)
                .replace("CODE", code);
        String tokenInfoStr = HttpClientUtil.doGet(url);
        JSONObject tokenInfoObject = JSONUtil.parseObj(tokenInfoStr);

        //获取用户信息
        String userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";
        userInfoUrl = userInfoUrl.replace("ACCESS_TOKEN", tokenInfoObject.getStr("access_token"))
                .replace("OPENID", tokenInfoObject.getStr("openid"));
        String userInfoStr = HttpClientUtil.doGet(userInfoUrl);

        JSONObject wxUserInfo = JSONUtil.parseObj(userInfoStr);

        //判断是否存该用户
        String openid = tokenInfoObject.getStr("openid");
        String unionId = tokenInfoObject.getStr("unionid");
        User userInfo = userService.getByOpenid(openid);
        if (userInfo == null){
            //业务上进行保存用户各信息
            
        }

        //存在直接进行登录 生成token或其他 根据自己需求来 
        String token = "token";
        return ApiResult.successWithObject(token);
    }
}

 

 

Guess you like

Origin blog.csdn.net/qq_42990433/article/details/128654491