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

作者 : 开心源码 本文共6215个字,预计阅读时间需要16分钟 发布时间: 2022-05-13 共265人阅读

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_codeString 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<String, String> 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<String,String> 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<String, String> map = JSONObject.toBean(obj, Map.class);        log.info("getSnsOauth2AccessToken==>{}", map);        return map;    }
说明
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是摆设,本站源码仅提供给会员学习使用!
7. 如遇到加密压缩包,请使用360解压,如遇到无法解压的请联系管理员
开心源码网 » 微信开发获取客户信息及发送模板消息

发表回复