package com.ifish.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

/**
 * @author: yan.y
 * @Description:
 * @Date: Created in 11:19 2019-12-04
 * @Modified by:
 */
public class WeChatUtils {

    /**
     * 微信应用appid
     */
    private static final String WECHAT_APPID = "wxb3b27d653ec3e3cb";

    /**
     * 微信应用 appsecret
     */
    private static final String WECHAT_SECRET = "79d35215d7ef369b927f7cb21a2b8ff6";

    /**
     * 微信获取token url
     */
    private static final String WECHAT_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?";

    /**
     * 微信获取用户信息url
     */
    private static final String WECHAT_USERINFO_URL = "https://api.weixin.qq.com/sns/userinfo?";

    /**
     * 获取微信用户信息
     * @param code 授权码
     * @return
     */
    public static final JSONObject getWechatUserInfo(String code){
        //授权url
        String accessTokenUrl = String.format("%sappid=%s&secret=%s&code=%s&grant_type=authorization_code", WECHAT_ACCESS_TOKEN_URL, WECHAT_APPID, WECHAT_SECRET, code);
        // 调用微信接口
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet accessTokenGet = new HttpGet(accessTokenUrl);
        JSONObject json = new JSONObject();
        try {
            HttpResponse accessTokenResponse = httpClient.execute(accessTokenGet);
            HttpEntity accessTokenEntity = accessTokenResponse.getEntity();
            String accessTokenResult = EntityUtils.toString(accessTokenEntity, "UTF-8");
            JSONObject wechatToken = JSON.parseObject(accessTokenResult);
            System.out.println("token : " + wechatToken);
            String openId = wechatToken.getString("openid");
            String accessToken = wechatToken.getString("access_token");

            // 查询用户信息
            String userInfoUrl = String.format("%saccess_token=%s&openid=%s&lang-zh_CN", WECHAT_USERINFO_URL, accessToken, openId);
            HttpGet userInfoGet = new HttpGet(userInfoUrl);
            HttpResponse userInfoResponse = httpClient.execute(userInfoGet);
            HttpEntity userInfoEntity = userInfoResponse.getEntity();
            String userInfoResult = EntityUtils.toString(userInfoEntity, "UTF-8");
            System.out.println("userInfo : " + userInfoResult);
            json = JSON.parseObject(userInfoResult);
        } catch (Exception e) {
           e.printStackTrace();
        } finally {
            return json;
        }


    }
}
