WeChat public platform test account application, use HBuilder X and WeChat developer tools to achieve authorized login function and single sign-on

Test account application

Number measurement response process: The client sends a request, and the WeChat server forwards the request to the developer server after receiving the request. After processing, it is sent to the WeChat server, and then returned to the client.

1. Open the WeChat public platform and click Test Account Application. Address: https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login,

Scan the authorization through WeChat to enter the test number management page. You can see your developer ID

The url in the test number needs to have its own server to write the corresponding interface. Click to submit WeChat will send data like the url and judge whether the url is configured successfully according to the returned result; token is a string defined by yourself

Finally, scan the code to add your WeChat as a developer

Download the transit tool NATAPP-Intranet penetration A domestic high-speed intranet mapping tool based on ngrok

After downloading, register on the webpage, perform real-name authentication, apply for a free tunnel, tunnel information will be generated, and natapp will be activated.

Enter the authtoken generated by the natapp -authtoken tunnel information and press Enter

At this time, your own domain name will be generated, and you need to always open natapp during testing.

If you have an enterprise official account, then you don't need the above steps, you can directly configure the developer WX

创建小程序测试:使用微信开发者工具通过扫码登陆,点击创建选择小程序即可,AppID为刚才申请的。选择需要编写的模板即可

Use HBuilder X and WeChat developer tools to achieve authorized login function

First, you need to import the project template on HBuilder, configure the directory of the WeChat developer tools in the security settings, and then click to run to the applet simulator, so that the WeChat developer tools will be automatically opened after running.

Create the main code login.vue of the landing page, mainly to call the api provided by WeChat to obtain the user's code, which also obtains the user's basic information on the front-end and sends it to the back-end

<button class="confirm-btn" @click="wxlogin" :disabled="logining">登录</button>
//对应逻辑
methods: {
			wxlogin(){
			uni.getUserProfile({
					desc:"获取资料",
					success: (res) => {
						console.log(res)
						this.encryptedData=res.encryptedData
						this.rawData=res.rawData
						this.iv=res.iv
						this.signature=res.signature
						this.avatarUrl=res.userInfo.avatarUrl
						this.name=res.userInfo.nickName
					}
				});//获取用户资料
				uni.login({
				  provider: 'weixin',
				  success: (res) => {
					
					 this.code=res.code;
					// console.log(this.code);
					
				  }
				});
				console.log(this.name)
				console.log(this.avatarUrl)
				//发送请求
				uni.request({
					url:"http://localhost:8081/api/dsxs/company/token",
					method:"POST",
				 data: {
					// encryptedData:this.encryptedData,
					// rawData:this.rawData,
					// iv:this.iv,
					// signature:this.signature,
					code:this.code,
					img:this.avatarUrl,
					name:this.name
				    },
					success: (e) => {
						
						console.log("向后端请求成功");
					}
					
				})
			},

The backend can obtain the user's openID and session_key through the previously applied appID, appSecret and the code from the frontend

Create a springboot project and add dependencies

 <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>4.7.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--mybatis-plus-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.1</version>
        </dependency>
        <!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!--lombok用来简化实体类-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.3.1</version>
        </dependency>

        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.0</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.62</version>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.3.1</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>

After configuring the entity class and data-related code, put your appID and appSecret in the configuration file

wx.open.app_id=xxxxxxxx
wx.open.app_secret=xxxxxxxxx

Create a class to get configuration information

@Component
//@PropertySource("classpath:application.properties")
public class ConstantPropertiesUtil implements InitializingBean {
    //读取配置文件并赋值
    @Value("${wx.open.app_id}")
    private String appId;
    @Value("${wx.open.app_secret}")
    private String appSecret;

    public static String WX_OPEN_APP_ID;
    public static String WX_OPEN_APP_SECRET;

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

Write the user login control layer. My implementation logic here is to obtain the user's openID as the unique identifier of the user according to the code sent from the front end. First, query the database for whether there is a current user, and create a token to return the corresponding information to the front end. Because the front-end is written to pass the code and user information all at one time, the user will jump to the authorization page after clicking to log in. If the user clicks to reject, the user information will not be passed, only the code. At this time, my processing logic is It is judged whether there is user information. If not, it is not stored in the database. Since the user clicks authorization will have time to respond, a short hibernation process is performed.

public class LoginController {
    @Autowired
    private UserService userService;

    @PostMapping("token")
    public R login(@RequestBody LoginBO loginBO) throws IOException, InterruptedException {
    //拼接对应信息
        StringBuffer baseAccessTokenUrl = new StringBuffer()
                .append("https://api.weixin.qq.com/sns/jscode2session")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&js_code=%s")
                .append("&grant_type=authorization_code");
        String accessTokenUrl = String.format(baseAccessTokenUrl.toString(),
                ConstantPropertiesUtil.WX_OPEN_APP_ID,
                ConstantPropertiesUtil.WX_OPEN_APP_SECRET,
                loginBO.getCode());
         //像网站发送请求
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(accessTokenUrl).build();
        Response response = client.newCall(request).execute();
        //请求成功会返回对应信息,解析为json
        if (response.isSuccessful()){
            String body = response.body().string();
            JSONObject jsonObject = JSONObject.parseObject(body);
            String session_key = jsonObject.getString("session_key");
            String openid = jsonObject.getString("openid");
            HashMap<String, Object> map = new HashMap<>();
            Thread.sleep(1000);
            //判断数据中有无当前用户
            User userInfo = userService.getByOpenId(openid);
            if (userInfo==null){
                User user = new User();
                user.setOpenid(openid);

                if (loginBO.getName().equals("")){
                    return R.error().message("授权失败");
                }
                user.setNickName(loginBO.getName());
                user.setAvatarUrl(loginBO.getImg());
                user.setStat(1);
                userService.save(user);
                userInfo = userService.getByOpenId(openid);
            }
                String token = JwtHelper.createToken(userInfo.getOpenid(),userInfo.getNickName(),userInfo.getAvatarUrl());
                map.put("token",token);
                map.put("nickname",userInfo.getNickName());
                map.put("img",userInfo.getAvatarUrl());
                return R.ok().data(map);
        }
        return R.error().message("授权失败,请重试");
    }

Create JWT to generate token tool class

public class JwtHelper {
    //过期时间  毫秒
    private static long tokenExpiration = 60*60*1000;
    //自定义秘钥
    private static String tokenSignKey = "123456";
    public static String createToken(String openid,String nickName,String img) {
        String token = Jwts.builder()
                //设置分组
                .setSubject("DSXS-USER")
                //设置字符串过期时间
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                //私有部分
                .claim("userId", openid)
                .claim("userName", nickName)
                .claim("img",img)
                //设置秘钥
                .signWith(SignatureAlgorithm.HS512, tokenSignKey)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
        return token;
    }
    //从生成token字符串获取userId值
    public static String getUserId(String token) {
        if(StringUtils.isEmpty(token)) return null;
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        String userId = (String)claims.get("userId");
        return (String)claims.get("userId");
    }
    public static String getUserName(String token) {
        if(StringUtils.isEmpty(token)) return "";
        Jws<Claims> claimsJws
                = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        return (String)claims.get("userName");
    }
    public static String getImg(String token) {
        if(StringUtils.isEmpty(token)) return "";
        Jws<Claims> claimsJws
                = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        return (String)claims.get("img");
    }

Create a method to obtain user information based on token

//根据token获取用户信息
    @GetMapping("auth/getUserInfo")
    public R getUserInfo(HttpServletRequest request) {
        try{
            String userId = AuthContextHolder.getUserId(request);
            String userName = AuthContextHolder.getUserName(request);
            String userImg = AuthContextHolder.getUserImg(request);
            User user = new User();
            user.setOpenid(userId);
            user.setNickName(userName);
            user.setAvatarUrl(userImg);
            return R.ok().data("userInfo",user);
        }catch (ExpiredJwtException e){
            System.out.println("token失效");
        }
        return R.error().message("token失效");
    }

If there are other implementation methods, welcome to discuss

Guess you like

Origin blog.csdn.net/weixin_52210557/article/details/124318265