微信开发获取用户信息及发送模板消息

0,官网地址

https://mp.weixin.qq.com/wiki?t=resource/res_main

1,获取用户信息:获取用户信息主要有微信网页授权以及UnionID机制(关注后获取),先来说说网页授权方式

1.1,引导授权地址,获取code

授权需要使用到oauth2认证,首先需要引导用户打开地址,格式如下
https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
其中SCOPE为授权作用域(snsapi_userinfo),STATE为参数,可通过state传参,也可以通过传统url拼接方式(需进行编码),REDIRECT_URL为授权后回调地址,授权后微信会携带code跳转到REDIRECT_URL
例:
https://open.weixin.qq.com/connect/oauth2/authorize?appid=****&redirect_uri=****&response_type=code&scope=snsapi_userinfo&state=#wechat_redirect

1.2,通过code换取access_token和openid

请求微信接口:
https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
微信方会返回token(此token仅用于步骤4获取userinfo,不同于其他token),此接口返回openid,accesstoken,openid以及refresh_token;

1.3 刷新access_token(非必需)

如果accesstoken过期,可通过refresh_token刷新token;请求接口为:https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN;

1.4拉取用户信息(需scope为 snsapi_userinfo)

微信方接口
https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN;
全部代码如下:

//https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
String openid = "";
        String soap_url1 = Constant.WEIXIN.WX_URL + "sns/oauth2/access_token?appid=" + Constant.WEIXIN.APP_ID
                + "&secret=" + Constant.WEIXIN.SECRET + "&code=" + code + "&grant_type=authorization_code";
        String ret1 = WeiXinUtil.connectWeiXinInterfaceGet(soap_url1, "");
        if (ret1 != null && ret1.trim().length() > 0) {
            JSONObject obj = JSONObject.fromObject(ret1);
            if (obj.get("errcode") != null) {
                // 跳转到失败界面去
            }else {
                openid = obj.getString("openid");
                String access_token = obj.getString("access_token");
                                //https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
                String soap_url2 = Constant.WEIXIN.WX_URL + "sns/userinfo?access_token=" + access_token + "&openid="
                        + openid + "&lang=zh_CN";
                String ret2 = WeiXinUtil.connectWeiXinInterfaceGet(soap_url2, "");
                if (ret2 != null && ret2.trim().length() > 0) {
                    JSONObject obj2 = JSONObject.fromObject(ret2);
                    if (obj2.get("errcode") != null) {
                        // 跳转到失败界面去
                    }else {
                        String nickname = String.valueOf(obj2.get("nickname"));
                        String sex = String.valueOf(obj2.get("sex"));
                        String headimgurl = String.valueOf(obj2.get("headimgurl"));
                    }
                }
                
            }
        }

附上WeiXinUtil代码

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class WeiXinUtil {

    private static final Logger logger =LoggerFactory.getLogger(WeiXinUtil.class);
    public static  String connectWeiXinInterfaceGet(String action,String json){

        URL url;

       try {

           url = new URL(action);

           HttpURLConnection http = (HttpURLConnection) url.openConnection();

           http.setRequestMethod("GET");

           http.setRequestProperty("Content-Type",

                   "application/x-www-form-urlencoded");

           http.setDoOutput(true);

           http.setDoInput(true);

           System.setProperty("sun.net.client.defaultConnectTimeout", "60000");// 连接超时60秒

           System.setProperty("sun.net.client.defaultReadTimeout", "60000"); // 读取超时60秒

           http.connect();

           OutputStream os = http.getOutputStream();

           os.write(json.getBytes("UTF-8"));// 传入参数

           InputStream is = http.getInputStream();

           int size = is.available();

           byte[] jsonBytes = new byte[size];

           is.read(jsonBytes);

           String result = new String(jsonBytes, "UTF-8");

           logger.info("请求返回结果:"+result);

           os.flush();

           os.close();
           return result;

       } catch (Exception e) {
           logger.info("请求微信接口失败,失败信息:"+e.getMessage());
           return "";
       }
    }
    
    public static  String connectWeiXinInterfacePost(String action,String json){

        URL url;

       try {

           url = new URL(action);

           HttpURLConnection http = (HttpURLConnection) url.openConnection();

           http.setRequestMethod("POST");

           http.setRequestProperty("Content-Type",

                   "application/x-www-form-urlencoded");

           http.setDoOutput(true);

           http.setDoInput(true);

           System.setProperty("sun.net.client.defaultConnectTimeout", "60000");// 连接超时60秒

           System.setProperty("sun.net.client.defaultReadTimeout", "60000"); // 读取超时60秒

           http.connect();

           OutputStream os = http.getOutputStream();

           os.write(json.getBytes("UTF-8"));// 传入参数

           InputStream is = http.getInputStream();

           int size = is.available();

           byte[] jsonBytes = new byte[size];

           is.read(jsonBytes);

           String result = new String(jsonBytes, "UTF-8");

           logger.info("请求返回结果:"+result);

           os.flush();

           os.close();
           return result;

       } catch (Exception e) {
           logger.info("请求微信接口失败,失败信息:"+e.getMessage());
           return "";
       }
    }
}

2.UnionID机制获取用户信息

2.1获取access_token;

请求微信接口:
https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET,
该接口返回accesstoken。

2.2 获取用户基本信息:

请求微信接口:
https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN;
该接口返回subscribe属性为是否已关注标识,0为未关注1为已关注,如已关注返回用户信息如头像等,如为未关注则不返回用户信息,返回数据如图:

image.png

代码如下:

public static Map getAccessUserInfo(String openId) {
        String result = WeiXinUtil.connectWeiXinInterface(String.format(Constant.URL.USER_INFO, getAccessToken(), openId), "");
        return JSON.parseObject(result, Map.class);
    }
public static String  getAccessToken(){
         
        String result = WeiXinUtil.connectWeiXinInterface(String.format(Constant.URL.ACCESS_TOKEN_URL, Constant.WEIXIN.APP_ID, Constant.WEIXIN.SECRET), "");
        JSONObject json = JSONObject.fromObject(result);
        String token = StrUtil.getNotNullStrValue(json.get("access_token"));
        return token;
    }

总的来说UnionID机制获取用户信息有局限性,比如参数需openid,且返回数据如果未关注则获取不到用户信息;但UnionID方式获取用户信息来的更简单;需要配合场景权衡;

3,发送模板消息

3.1获取openid,此步骤同UnionID机制获取accesstoken

3.2 发送模板消息

首先在公众号配置模板id如图:


image.png

部分代码如下:

public class NotifyTemplate {
    private String template_id;
    private String touser;
    private String url;
    private String first;
    private String keyword1;
    private String keyword2;
    private String keyword3;
    private String keyword4;
    private String keyword5;
    private String remark;
    private String color;
        public NotifyTemplate() {
        super();
    }
    
    public NotifyTemplate(String template_id, String touser, String url,
            String first, String keyword1, String keyword2,
            String remark) {
        super();
        this.template_id = template_id;
        this.touser = touser;
        this.url = url;
        this.first = first;
        this.keyword1 = keyword1;
        this.keyword2 = keyword2;
        this.remark = remark;
        this.color="#173177";
    }
}
public static Map sendTemplateMsg(NotifyTemplate template){
        String msg= template.toJsonMsg();
        String result = WeiXinUtil.connectWeiXinInterface(String.format(Constant.URL.TEMPLATE_SEND_URL,getAccessToken()), msg);
                JSONObject obj= JSONObject.fromObject(result);
                    
        Map map = JSONObject.toBean(obj, Map.class);
        log.info("getSnsOauth2AccessToken==>{}", map);
        return map;
    }

你可能感兴趣的:(微信开发获取用户信息及发送模板消息)