package com.neusoft.smart.pos.order.utils;

import com.alibaba.fastjson.JSON;
import com.neusoft.smart.pos.framework.utils.RedisUtils;

import java.util.Map;

public class WXTokenUtils {

//    public static final String QUERY_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&";
    public static final String QUERY_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?grant_type=authorization_code&";
    public static final Long TOKEN_EXPIRE_TIME = 3600L; //token缓存失效时间

    /**
     * 微信退款通知数据解密
     * @return
     */
    public static String getOpenId(String appId, String secret,String code) {
        Object accessTokenObject = RedisUtils.getRedisValue(code);
        if(accessTokenObject != null){
            Map<String,String> tempMap = JSON.parseObject(accessTokenObject.toString(),Map.class);
            return tempMap.get("openid");
        }
        StringBuffer sb = new StringBuffer();
        sb.append(QUERY_ACCESS_TOKEN_URL);
        sb.append("&appid=").append(appId);
        sb.append("&secret=").append(secret);
        sb.append("&code=").append(code);
        String responseData = HttpClientUtils.getData(sb.toString());

//        { "access_token":"ACCESS_TOKEN",
//                "expires_in":7200,
//                "refresh_token":"REFRESH_TOKEN",
//                "openid":"OPENID",
//                "scope":"SCOPE" }
        Map<String,String> accessTokenMap = JSON.parseObject(responseData,Map.class);
        String openId = accessTokenMap.get("openid");
        RedisUtils.saveRedisValue(code,responseData,TOKEN_EXPIRE_TIME);
        return openId;
    }

}
