app端微信登录调试

详细步骤在微信开发文档中已经写得很明白,开发前仔细看下就好!一定要仔细看。

再次记录下代码,下次可以直接拿来使用! 根据需求进行微调!

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.HashMap;

@Service
public class WeChatLoginServiceImpl implements WeChatLoginService {
    private static final Logger logger = LoggerFactory.getLogger(WeChatLoginController.class);
    //获取需要调用的接口,在微信开发文档有具体说明
    public static final String WX_AUTH_LOGIN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token";

    public static final String WX_USERINFO_URL = "https://api.weixin.qq.com/sns/userinfo";

    //AppId
    @Value("${weChat.appId}")
    private String WX_APP_ID;
    //AppSecret
    @Value("${weChat.appSecret}")
    public String WX_APP_KEY;

    //code参数需要移动端开发获取到传给后台
    public UserInfo checkLogin(String code) {
        //获取授权 access_token
        StringBuffer loginUrl = new StringBuffer();
        loginUrl.append(WX_AUTH_LOGIN_URL).append("?appid=")
                .append(WX_APP_ID).append("&secret=")
                .append(WX_APP_KEY).append("&code=").append(code)
                .append("&grant_type=authorization_code");
        String loginRet = get(loginUrl.toString());
        JSONObject grantObj = null;
        try {
            grantObj = new JSONObject(loginRet);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String errcode = grantObj.optString("errcode");
        if (!StringUtils.isEmpty(errcode)) {
            logger.error("login weixin error" + loginRet);
            jsonResult.setResultInfo(JsonCode.BAD_REQUEST);
            return null;
        }
        //用户对应平台的唯一标识,记住对应平台
        String openId = grantObj.optString("openid");
        if (StringUtils.isEmpty(openId)) {
            logger.error("login weixin getOpenId error" + loginRet);
            jsonResult.setResultInfo(JsonCode.BAD_REQUEST);
            return null;
        }

        String accessToken = grantObj.optString("access_token");
        String expiresIn = grantObj.optString("expires_in");
        String refreshToken = grantObj.optString("refresh_token");
        String scope = grantObj.optString("scope");

        //获取用户信息
        StringBuffer userUrl = new StringBuffer();
        userUrl.append(WX_USERINFO_URL).append("?access_token=").append(accessToken).append("&openid=").append(openId);
        String userRet = get(userUrl.toString());
        JSONObject userObj = null;
        try {
            userObj = new JSONObject(userRet);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setOpenId(openId);
        userInfo.setAuthToken(accessToken);
        userInfo.setAuthRefreshToken(refreshToken);
        userInfo.setScope(scope);
        userInfo.setExpiresIn(Integer.valueOf(expiresIn));
        String nickname = userObj.optString("nickname");
        String sex = userObj.optString("sex");
        String userImg = userObj.optString("headimgurl");
        String unionid = userObj.optString("unionid");
        userInfo.setName(nickname);
        userInfo.setIcon(userImg);
        userInfo.setGender(sex);
        userInfo.setLoginId(unionid);
        return userInfo ;
    }
    //调用微信API
    public static String get(String url) {
        String body = null;
        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
            logger.info("create httppost:" + url);
            HttpGet get = new HttpGet(url);
            get.addHeader("Accept-Charset", "utf-8");
            HttpResponse response = sendRequest(httpClient, get);
            body = parseResponse(response);
        } catch (IOException e) {
            logger.error("send post request failed: {}", e.getMessage());
        }

        return body;
    }

    private static HttpResponse sendRequest(CloseableHttpClient httpclient, HttpUriRequest httpost)
            throws IOException {
        HttpResponse response = null;
        response = httpclient.execute(httpost);
        return response;
    }

    private static String parseResponse(HttpResponse response) {
        logger.info("get response from http server.......");
        HttpEntity entity = response.getEntity();

        logger.info("response status: " + response.getStatusLine());
        Charset charset = ContentType.getOrDefault(entity).getCharset();
        if (charset != null) {
            logger.info(charset.name());
        }

        String body = null;
        try {
            body = EntityUtils.toString(entity, "utf-8");
            logger.info("body " + body);
        } catch (IOException e) {
            logger.warn("{}: cannot parse the entity", e.getMessage());
        }

        return body;
    }

}

你可能感兴趣的:(微信接口对接)