package com.example.demo.wxutil;

import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @author FXF
 * @date 2018-12-06
 */
public class WxUtils {
	
	/**
	 * 获取微信的access_token
	 * @param appid
	 * @param secret
	 * @return
	 */
	public static String getAccessToken(String appid,String secret) {
		RestTemplate restTemplate = new RestTemplate();
		Map<String,Object> params = new HashMap<>();
		params.put("appid",appid);
		params.put("secret",secret);
		return restTemplate.getForObject("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appid}&secret={secret}",String.class,params);
	}
	
	/**
	 * 网页授权根据code获取openid
	 * @param appid
	 * @param secret
	 * @param code
	 * @return
	 */
	public static String getOpenidByCode(String appid, String secret, String code) {
		RestTemplate restTemplate = new RestTemplate();
		Map<String,Object> params = new HashMap<>();
		params.put("appid",appid);
		params.put("secret",secret);
		params.put("code",code);
		return restTemplate.getForObject("https://api.weixin.qq.com/sns/oauth2/access_token?appid={appid}&secret={secret}&code={code}&grant_type=authorization_code",String.class,params);
	}
	
	/**
	 * 网页授权根据openid和access_token获取用户信息
	 * @param accessToken
	 * @param openid
	 * @return
	 */
	public static String getUserInfo(String accessToken, String openid) {
		RestTemplate restTemplate = new RestTemplate();
		Map<String,Object> params = new HashMap<>();
		params.put("accessToken",accessToken);
		params.put("openid",openid);
		return restTemplate.getForObject("https://api.weixin.qq.com/sns/userinfo?access_token={accessToken}&openid={openid}&lang=zh_CN",String.class,params);
	}
	
	public static void main(String[] args) {
		String result = WxUtils.getUserInfo("16_1WMxSvI3adScflB58Hhd2Uxk2QBGsTKGWeF6jLuWZdxylSfFL69kO_ISggOizI3XN2ORT66smyM6l2LSHeWbvzUGLa48dGu2SXfpNe9-woU","o-V1h1mUfllsP7F3wziroLF9Yjyk");
		System.out.println(result);
	}
}
