微信テスト番号は個人の第三者PCのウェブサイトのQRコードの登録を実現します(コードの実現編)


私のページはQRコードを生成するjsを使って、ネット上で手に入れたのです(転載が多すぎて、具体的な作者は何なのか分かりません(#^.^#))
QRコードjsを生成するリンクを開いて直接jsをコピーすればOKです.
はい、本文は来て、私のコードの中でspringboot(SSM)+redis+shiroを使いました...
ページコード:
 



    
           
    
    
    
    /*<![CDATA[*/
    
    function checkLogin(){
    	var i = 0;
    	var sessionId = $("#sessionId").val();
    	if(sessionId!=""){
    		$.ajax({
                url: "/wechat/polling",
                type: "POST",
                data:{sessionId:sessionId},
                success: function (data) {
                	if(data.status=="200"){
                		window.clearInterval(c);
                		alert(data.message);
                		location.href = "/";
                	}else{
                		i++;
                		if(i>60){
                			window.clearInterval(c);
                			alert("      !      。");
                		}
                	}
                }
        	});
    	}
    }
    
    function wechatLogin(){
    	$.ajax({
            url: "/wechat/wxLoginPage",
            type: "POST",
            success: function (data) {
            	$("#sessionId").val(data.sessionId);
            	
            	var qrcode = new QRCode(document.getElementById("code"), {
                    width : 200,//    
                    height : 200
                });
                qrcode.makeCode(data.uri);
                c = setInterval(checkLogin,5000);//    
            }
    	});
    }
    /*]]>*/
    


	
		
	
	
		
	
	
	




后台controller(@RequestMapping("/wechat"))代码:

 

 

//pc      ,       
    @RequestMapping(value = "/wxLoginPage",method = RequestMethod.POST)
    @ResponseBody
    public Map wxLoginPage(HttpServletRequest request) throws Exception {
    	String sessionId = request.getSession().getId();
    	logger.info("sessionId:"+sessionId);
        String uri = weChatAuthService.getAuthorizationUrl("pc",sessionId);//  redirect_uri state=sessionId       ,    url
        logger.info(uri);
        Map map = new HashMap();
        map.put("sessionId", sessionId);
        map.put("uri", uri);//         
        return map;
    }
    
    //         ,  code,    
    @RequestMapping(value = "/pcAuth")
    @ResponseBody
    public String pcCallback(String code,String state,HttpServletRequest request,HttpServletResponse response) throws Exception {
        String result = weChatAuthService.getAccessToken(code);//  code  access_token openId,       
        JSONObject jsonObject = JSONObject.parseObject(result);
        
        //String refresh_token = jsonObject.getString("refresh_token");
        String access_token = jsonObject.getString("access_token");
        String openId = jsonObject.getString("openId");
        
        logger.info("------------    ----------------");
        JSONObject infoJson = weChatAuthService.getUserInfo(access_token,openId);//  token openId        ,                
        if(infoJson!=null){
        	String nickname = infoJson.getString("nickName");
            logger.info("-----nickname-----"+nickname);
            logger.info("-----sessionId-----"+state);
            infoJson.put("openId", openId);
            redisTemplate.opsForValue().set(state, infoJson, 10*60, TimeUnit.SECONDS);
            return "    !";
        }
	    return "    !";
    }
//    key
    @RequestMapping(value="/polling",method=RequestMethod.POST)
    @ResponseBody
    public Map polling(String sessionId,HttpServletRequest request,HttpServletResponse response){
    	Map resultMap = new LinkedHashMap();
    	
    	if(redisTemplate.hasKey(sessionId)){
    		JSONObject infoJson = (JSONObject)redisTemplate.opsForValue().get(sessionId);
    		redisTemplate.opsForValue().getOperations().delete(sessionId);
    		String openId = (String)infoJson.get("openId");
    		//  openId             ,           
            User user = userService.selectUserByWechat(openId);
            if (user == null) {
            	String nickname = (String)infoJson.get("nickName");
            	String sex = (String)infoJson.get("sex");
            	User newuser = new User();
            	newuser.setSex(sex);
            	newuser.setWechat(openId);
            	newuser.setNickname(nickname);
            	int i = userService.insertUser(newuser);//    
            	if(i<1){
            		resultMap.put("status", 500);
        	        resultMap.put("message", "    :");
        	        return resultMap;
            	}
            }
            //    
    	    try {
    	    	UsernamePasswordToken token = new UsernamePasswordToken(openId, openId);//    shiro  ,   openId        
    	        SecurityUtils.getSubject().login(token);
    	        resultMap.put("status", 200);
    	        resultMap.put("message", "    ");
    	        
    	        //          
    	        Subject  currentUser = SecurityUtils.getSubject(); 
    			User luser = (User) currentUser.getPrincipal();
    	        User user1 = new User();
    	        user1.setId(luser.getId());
    	        user1.setLastLogDate(new Date());
    	        userService.updateUserByIdSelective(user1);//      
    	        
    	        
    	    } catch (Exception e) {
    	        resultMap.put("message", "      :" + e.getMessage());
    	    }
    	    return resultMap;
    	}else{//not has key
    		resultMap.put("status", 0);
    		return resultMap;
    	}
    }

ServiceImplコード
package com.kun.service.impl;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.util.UriComponentsBuilder;

import com.alibaba.fastjson.JSONObject;
import com.kun.service.WeChatAuthService;

@Service
public class WeChatAuthServiceImpl extends DefaultAuthServiceImpl implements WeChatAuthService {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	//                
    private static final String AUTHORIZATION_URL =
            "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=%s#wechat_redirect";

    //      openid  access——toke   URL
    private static final String ACCESSTOKE_OPENID_URL =
            "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";

    private static final String REFRESH_TOKEN_URL =
            "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=%s&grant_type=refresh_token&refresh_token=%s";

    private static final String USER_INFO_URL =
            "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN";

    private static final String APP_ID="wx957421889a04804d";
    private static final String APP_SECRET="9155791266381e14c670ea7fa1abb90b";
    private static final String SCOPE = "snsapi_userinfo";//  snsapi_userinfo  snsapi_base

    private String pcCallbackUrl = "https://7dc6440a.ngrok.io//wechat/pcAuth"; //pc    
    
    private String mobileCallbackUrl = "https://7dc6440a.ngrok.io//wechat/mobileAuth"; //mobile    

    /**
     *    ,    
     * appid:        
     * redirect_uri:             
     * response_type:    ,  code
     * scope:       ,snsapi_base / snsapi_userinfo
     * state:   ,       state  ,       a-zA-Z0-9    ,  128  
     * wechat_redirect:           302     ,      
     * */
    @Override
    public String getAuthorizationUrl(String type,String state) throws UnsupportedEncodingException {
    	String callbackUrl = "";
    	Object urlState = "";
    	if("pc".equals(type)){//    pc         
    		callbackUrl = URLEncoder.encode(pcCallbackUrl,"utf-8");
    		urlState = state;
    	}else if("mobile".equals(type)){
    		callbackUrl = URLEncoder.encode(mobileCallbackUrl,"utf-8");
    		urlState = System.currentTimeMillis();
    	}
        String url = String.format(AUTHORIZATION_URL,APP_ID,callbackUrl,SCOPE,urlState);
        return url;
    }

    /**
     *    
     *  appid  secret code grant_type=authorization_code
     *    access_token openId 
     * */
    @Override
    public String getAccessToken(String code) {
        String url = String.format(ACCESSTOKE_OPENID_URL,APP_ID,APP_SECRET,code);

        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
        URI uri = builder.build().encode().toUri();

        String resp = getRestTemplate().getForObject(uri, String.class);
        logger.error("getAccessToken resp = "+resp);
        if(resp.contains("openid")){
            JSONObject jsonObject = JSONObject.parseObject(resp);
            String access_token = jsonObject.getString("access_token");
            String openId = jsonObject.getString("openid");;

            JSONObject res = new JSONObject();
            res.put("access_token",access_token);
            res.put("openId",openId);
            res.put("refresh_token",jsonObject.getString("refresh_token"));

            return res.toJSONString();
        }else{
            logger.error("        ,msg = "+resp);
        	return null;
        }
    }

    //     ,token openId     ,        
    @Override
    public String getOpenId(String accessToken) {
        return null;
    }

    @Override
    public JSONObject getUserInfo(String accessToken, String openId){
        String url = String.format(USER_INFO_URL, accessToken, openId);
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
        URI uri = builder.build().encode().toUri();

        String resp = getRestTemplate().getForObject(uri, String.class);
        logger.error("getUserInfo resp = "+resp);
        if(resp.contains("errcode")){
        	logger.error("        ,msg = "+resp);
        	return null;
        }else{
            JSONObject data =JSONObject.parseObject(resp);

            JSONObject result = new JSONObject();
            result.put("id",data.getString("unionid"));
            result.put("sex",data.getString("sex"));
            result.put("nickName",data.getString("nickname"));
            result.put("avatar",data.getString("headimgurl"));

            return result;
        }
    }

    //   token  2      ,        ,       
    //  refresh_token     token   ,          
    //  ,       ,            
    @Override
    public String refreshToken(String refresh_token) {

        String url = String.format(REFRESH_TOKEN_URL,APP_ID,refresh_token);

        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
        URI uri = builder.build().encode().toUri();

        ResponseEntity resp = getRestTemplate().getForEntity(uri,JSONObject.class);
        JSONObject jsonObject = resp.getBody();

        String access_token = jsonObject.getString("access_token");
        return access_token;
    }
}

クラス継承を実装したクラスDefaultAuthServiceImpl
package com.kun.service.impl;

import java.nio.charset.StandardCharsets;
import java.util.LinkedList;
import java.util.List;

import javax.xml.transform.Source;

import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.ResourceHttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter;
import org.springframework.http.converter.xml.SourceHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import com.kun.service.AuthService;

public abstract class DefaultAuthServiceImpl implements AuthService{
    public static RestTemplate getRestTemplate() {//     
        SimpleClientHttpRequestFactory requestFactory=new SimpleClientHttpRequestFactory();
        requestFactory.setReadTimeout(120000);
        List> messageConverters = new LinkedList<>();
        messageConverters.add(new ByteArrayHttpMessageConverter());
        messageConverters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8));
        messageConverters.add(new ResourceHttpMessageConverter());
        messageConverters.add(new SourceHttpMessageConverter());
        messageConverters.add(new AllEncompassingFormHttpMessageConverter());
        messageConverters.add(new MappingJackson2HttpMessageConverter());
        RestTemplate restTemplate=new RestTemplate(messageConverters);
        restTemplate.setRequestFactory(requestFactory);
        return restTemplate;
    }
}


------------------
package com.kun.service;

import java.io.UnsupportedEncodingException;

import com.alibaba.fastjson.JSONObject;

public interface AuthService {
    public abstract String getAccessToken(String code);
    public abstract String getOpenId(String accessToken);
    public abstract String refreshToken(String code);
    public abstract String getAuthorizationUrl(String type,String state) throws UnsupportedEncodingException;
    public abstract JSONObject getUserInfo(String accessToken,String openId);
}

 
 
 
下一篇文章《微信测试号实现个人第三方电脑端网站QRコード登录》
ここまで来れば、ウィーチャットのQRコードを私たちの個人サイトに登録することができます~~~~~~~