天天看点

微信网页授权(基于springboot)

一、设置微信管理后台的公众号设置的功能设置,将对应的域名填写完整,将txt文件放在对应的路径下,保证填写的域名加txt能够访问到。

微信网页授权(基于springboot)

二、验证服务器的可用性

微信网页授权(基于springboot)

1、AppController(验证是否是微信服务器传来的消息)

@RequestMapping(value = "/check", method = {RequestMethod.GET})
@ResponseBody
public void check(HttpServletResponse response, WXInfo wxInfo) {
    if (CheckUtil.checkSignature(wxInfo.getSignature(), wxInfo.getTimestamp(), wxInfo.getNonce())) {
        response.setCharacterEncoding("UTF-8");
        PrintWriter w;

        try {
            w = response.getWriter();
            w.write(wxInfo.getEchostr());
            w.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}      

2、校验

import com.sairobo.heart.modules.wechat.util.WechatUtil;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

/**
 * Created by zp on 2018/2/5.
 */
public class CheckUtil {
    private static final String token = WechatUtil.instance.getMessage("check.token");//微信后台填写的token

    public static boolean checkSignature(String signature,String timestamp,String nonce){
        String[] arr = new String[]{token,timestamp,nonce};
        //排序
        Arrays.sort(arr);

        //生成字符串
        StringBuffer content = new StringBuffer();
        for (int i = 0; i < arr.length; i++) {
            content.append(arr[i]);
        }

        //sha1加密
        String temp = getSha1(content.toString());

        return temp.equals(signature);

    }

    public static String getSha1(String str){
        if (null == str || 0 == str.length()){
            return null;
        }
        char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
            mdTemp.update(str.getBytes("UTF-8"));

            byte[] md = mdTemp.digest();
            int j = md.length;
            char[] buf = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
                buf[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(buf);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }
}
      

三、引导打开页面

https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=《这里写微信回调接口地址》&response_type=code&scope=SCOPE&state=STATE#wechat_redirect 
           

四、获取openid,保存

1 service(我是讲openid放在redis中,key是uuid,value是对应的openid,然后将uuid放在cookie里,这样后面的操作openid可以直接从cookie中取)

@Override
public void saveWXUserInfo(String code, String state, HttpServletRequest request, HttpServletResponse response) {
    try {
        request.setCharacterEncoding("utf-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    response.setCharacterEncoding("utf-8");
    HttpSession session  = request.getSession();

    Map<String, Object> result = null;
    String url = String.format(ConstantUtil.CONSTANT_AUTH,
            ConstantUtil.CONSTANF_APPID, ConstantUtil.CONSTANF_APPSECRET, code);
    OAuthInfo oAuthInfo =  WeChatUtils.getOAuthOpenId(url);

    System.out.println("openid"+oAuthInfo.getOpenId());

    String uuid = UUID.randomUUID().toString().replace("-", "");
    redisService.set(uuid,oAuthInfo.getOpenId(),60*60*24*30L);
    System.out.println("uuid"+uuid);

   Cookie cookie = new Cookie("openid",uuid);
   cookie.setPath("/");
   cookie.setMaxAge(60*60*24*30);
    response.addCookie(cookie);

    String url1 = String.format(ConstantUtil.CONSTANT_GETINFO, oAuthInfo.getAccessToken(), oAuthInfo.getOpenId(), ConstantUtil.CONSTANT_LANG);
    System.out.println(url1);
    Wxuserinfo wxuserinfo = WeChatUtils.getWXUserInfo(url1);


    Wxuserinfo wxuserinfoexist = appManager.getInfoByOpenid(wxuserinfo.getOpenid());
    if(StringUtils.isEmpty(wxuserinfoexist)){
        wxuserinfoManager.saveWxuserinfo(wxuserinfo);
    }      

2、wechatutils

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.sairobo.heart.modules.app.entity.OAuthInfo;
import com.sairobo.heart.modules.app.entity.Wxuserinfo;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

/**
 * Created by Administrator on 2018/2/8.
 */
public class WeChatUtils {
    public static OAuthInfo getOAuthOpenId(String url) {
        OAuthInfo oAuthInfo = null;

        JsonObject jsonObject = getTokenFromWX(url);


        if (jsonObject != null) {

            oAuthInfo = new OAuthInfo();
            oAuthInfo.setAccessToken(jsonObject.get("access_token").toString().replaceAll("\"", ""));
            oAuthInfo.setExpiresIn(Integer.parseInt(jsonObject.get("expires_in").toString().replaceAll("\"", "")));
            oAuthInfo.setRefreshToken(jsonObject.get("refresh_token").toString().replaceAll("\"", ""));
            oAuthInfo.setOpenId(jsonObject.get("openid").toString().replaceAll("\"", ""));
            oAuthInfo.setScope(jsonObject.get("scope").toString().replaceAll("\"", ""));

        }
        return oAuthInfo;
    }

    public static Wxuserinfo getWXUserInfo(String url) {
        Wxuserinfo wxuserInfo = null;

        JsonObject jsonObject = getTokenFromWX(url);


        if (jsonObject != null) {

            wxuserInfo = new Wxuserinfo();


            wxuserInfo.setOpenid(jsonObject.get("openid").toString().replaceAll("\"", ""));
            wxuserInfo.setNickname(jsonObject.get("nickname").toString().replaceAll("\"", ""));
            wxuserInfo.setSex(jsonObject.get("sex").toString().replaceAll("\"", ""));

            wxuserInfo.setCity(jsonObject.get("city").toString().replaceAll("\"", ""));
            wxuserInfo.setProvince(jsonObject.get("province").toString().replaceAll("\"", ""));
            wxuserInfo.setCountry(jsonObject.get("country").toString().replaceAll("\"", ""));
            wxuserInfo.setHeadimgurl(jsonObject.get("headimgurl").toString().replaceAll("\"", ""));

            // wxuserInfo.setUnionid(jsonObject.get("unionid").toString().replaceAll("\"", ""));


        }

        return wxuserInfo;
    }

    public static JsonObject getTokenFromWX(String url) {
        JsonObject object = null;
        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            String tokens = EntityUtils.toString(httpEntity, "utf-8");
            System.out.println("tokens" + tokens);
            Gson token_gson = new Gson();
            object = token_gson.fromJson(tokens, JsonObject.class);

        } catch (Exception ex) {
        }
        return object;
    }
}
      

继续阅读