zoukankan      html  css  js  c++  java
  • 公众号开发笔记二

    标题图

    前言

    微信公众平台开发模板消息,用于公众号向用户发送服务通知,如学生进校门,用校卡滴,就可以在公众号接收服务通知,表明学生进校.在公众号内申请功能,添加模板消息.

    只有认证后的服务号才能申请模板消息,需要选择2个行业,MP(维基百科,自由的百科全书),模板消息需要模板的ID,和模板中各种参数,内容以".DATA"结尾,否则视为保留字,模板保留符号"{{ }}".

    设置行业可以在公众平台后台完成,接口调用:

    这个步骤需要access_token

    // 请求方式: POST
    https://api.weixin.qq.com/cgi-bin/template/api_set_industry?access_token=ACCESS_TOKEN
    

    数据:

    {
        "industry_id1":"1",
        "industry_id2":"4"
    }
    

    参数说明

    参数 说明
    access_token 接口调用凭证
    industry_id1 行业编号
    industry_id2 行业编号

    行业代码查询:

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

    获取设置的行业信息:

    // 请求方式:GET
    https://api.weixin.qq.com/cgi-bin/template/get_industry?access_token=ACCESS_TOKEN
    

    需要access_token接口调用凭证,返回示例:

    {
    "primary_industry":{"first_class":"运输与仓储","second_class":"快递"},
    "secondary_industry":{"first_class":"IT科技","second_class":"互联网|电子商务"}
    }
    

    primary_industry: 主营行业
    secondary_industry: 副营行业

    获取模板ID: 可以在公众平台后获取模板ID:

    // 请求方式: POST
    https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token=ACCESS_TOKEN
    

    需要access_token

    post后的数据:

    {
     "template_id_short":"TM00015"
    }
    

    template_id_short: 是模板库中模板的编号.

    返回模板消息的接口,获取json数据:

    {
     "errcode":0,
     "errmsg":"ok",
     "template_id":"Doclyl5uP7Aciu-qZ7mJNPtWkbkYnWBWVja26EGbNyk"
    }
    

    获取模板列表

    获取帐号下所有模板信息:

    提供的接口:

    // 请求方式:GET
    https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token=ACCESS_TOKEN
    

    返回的数据:

    图1

    调用接口进行删除某账号下的模板:

    // 请求方式:POST
    
    https://api.weixin.qq.com/cgi-bin/template/del_private_template?access_token=ACCESS_TOKEN
    
    POST数据说明如下:
    
     {
         "template_id" : "Dyvp3-Ff0cnail_CDSzk1fIc6-9lOkxsQE7exTJbwUE"
     }
    

    template_id: 模板消息ID

    删除成功:

    {
       "errcode" : 0,
       "errmsg" : "ok"
    }
    

    发送模板消息

    调用接口:

    // 请求方式: POST
    https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN
    

    图2

    需要:

    OPENID
    template_id
    url
    miniprogram
    

    图3

    调用模板消息接口成功:

    {
    "errcode":0,
    "errmsg":"ok",
    "msgid":200228332
    }
    

    事件推送

    消息模板发送成功到公众号,微信服务器会将是否发送成功作为通知到开发者中心的服务器配置地址中.

    推送xml代码:

    图4

    图5

    图6

    模版消息接口文档

    https://www.cnblogs.com/jiqing9006/p/5220571.html

    对模板进行查看详情:

    图7

    # 可向指定openID群发

    https://segmentfault.com/a/1190000012828138

    php的实现

    https://www.cnblogs.com/jiqing9006/p/5220571.html

    1. 实例化 --> 获取appid,appsecret
    2. 获取access_token
    3. 发送模板消息
    4. 组合消息数据
    5. 获取openid, 并发送消息

    发送模板消息的接口:

    https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN

    发送模板的方法:

        //发送模板消息的接口
        public static final String SEND_TEMPLATE_URL = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
        /**
         * 发送模板
         *
         */
        public static void sendTemplate(String data){
            String result = HttpUtil.post(SEND_TEMPLATE_URL.replace("ACCESS_TOKEN", getAccessToken()),data);
            System.out.println(result);
        }
    

    getAccessToken的方法:

    验证接入

    图8

    微信公众平台接口测试帐号申请

    https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login

    公众号开发:

    appidappsecret

    配置参数: URL(自己的服务器地址)和Token(可任意填写)

    图9

    使用java语言,SpringMVC+Spring+MyBatis框架
    

    保证url的有效性:

    图10

    图11

    代码示例:

    @Controller
    public class WeChatController {
            /**
             * 微信URL接入验证
             * @param signature
             * @param timestamp
             * @param nonce
             * @param echostr
             * @return
             */
            @RequestMapping(value="/weChat",method= RequestMethod.GET)
            @ResponseBody
            public String validate(String signature,String timestamp,String nonce,String echostr){
                //1. 将token、timestamp、nonce三个参数进行字典序排序
                String[] arr = {timestamp,nonce,WeChatUtil.TOKEN};
                Arrays.sort(arr);
                //2. 将三个参数字符串拼接成一个字符串进行sha1加密
                StringBuilder sb = new StringBuilder();
                for (String temp : arr) {
                   sb.append(temp);
                }
                //3. 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信
                if(SecurityUtil.SHA1(sb.toString()).equals(signature)){
                    //接入成功
                    return echostr;
                }
                //接入失败
                return null;
            }
    }
    
    WeChatUtil.TOKEN是常量要与填入的token值相同
    SecurityUtil是工具类,提供sha1加密方法
    

    获取access_token

    public class WeChatUtil {
        //URL验证时使用的token
        public static final String TOKEN = "wolfcode";
        //appid
        public static final String APPID = "wx59687be81dd3d388";
        //secret
        public static final String SECRET = "d4624c36b6795d1d99dcf0547af5443d";
            //创建菜单接口地址
        public static final String CREATE_MENU_URL = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";
        //获取access_token的接口地址
        public static final String GET_ACCESSTOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
        //缓存的access_token
        private static String accessToken;
        //access_token的失效时间
        private static long expiresTime;
     
        /**
         * 获取accessToken
         * @return
         */
        public static String getAccessToken(){
            //判断accessToken是否已经过期,如果过期需要重新获取
            if(accessToken==null||expiresTime < new Date().getTime()){
                //发起请求获取accessToken
                String result = HttpUtil.get(GET_ACCESSTOKEN_URL.replace("APPID", APPID).replace("APPSECRET", SECRET));
                //把json字符串转换为json对象
                JSONObject json = JSON.parseObject(result);
                //缓存accessToken
                accessToken = json.getString("access_token");
                //设置accessToken的失效时间
                long expires_in = json.getLong("expires_in");
                //失效时间 = 当前时间 + 有效期(提前一分钟)
                expiresTime = new Date().getTime()+ (expires_in-60) * 1000;
            }
            return accessToken;
        }
    }
    

    HttpUtil是发起http请求的工具类

    https://blog.csdn.net/frankcheng5143/article/details/50070591

    官方文档中的示例:

    //1.获得一个httpclient对象
    CloseableHttpClient httpclient = HttpClients.createDefault();
    //2.生成一个get请求
    HttpGet httpget = new HttpGet("http://localhost/");
    //3.执行get请求并返回结果
    CloseableHttpResponse response = httpclient.execute(httpget);
    try {
        //4.处理结果
    } finally {
        response.close();
    }
    

    HttpGetHttpPost

    发送HttpGet

    	/**
    	 * 发送HttpGet请求
    	 * @param url
    	 * @return
    	 */
    	public static String sendGet(String url) {
    		//1.获得一个httpclient对象
    		CloseableHttpClient httpclient = HttpClients.createDefault();
    		//2.生成一个get请求
    		HttpGet httpget = new HttpGet(url);
    		CloseableHttpResponse response = null;
    		try {
    			//3.执行get请求并返回结果
    			response = httpclient.execute(httpget);
    		} catch (IOException e1) {
    			e1.printStackTrace();
    		}
    		String result = null;
    		try {
    			//4.处理结果,这里将结果返回为字符串
    			HttpEntity entity = response.getEntity();
    			if (entity != null) {
    				result = EntityUtils.toString(entity);
    			}
    		} catch (ParseException | IOException e) {
    			e.printStackTrace();
    		} finally {
    			try {
    				response.close();
    			} catch (IOException e) {
    				e.printStackTrace();
    			}
    		}
    		return result;
    	}
    

    发送HttpPost

    	/**
    	 * 发送不带参数的HttpPost请求
    	 * @param url
    	 * @return
    	 */
    	public static String sendPost(String url) {
    		//1.获得一个httpclient对象
    		CloseableHttpClient httpclient = HttpClients.createDefault();
    		//2.生成一个post请求
    		HttpPost httppost = new HttpPost(url);
    		CloseableHttpResponse response = null;
    		try {
    			//3.执行get请求并返回结果
    			response = httpclient.execute(httppost);
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    		//4.处理结果,这里将结果返回为字符串
    		HttpEntity entity = response.getEntity();
    		String result = null;
    		try {
    			result = EntityUtils.toString(entity);
    		} catch (ParseException | IOException e) {
    			e.printStackTrace();
    		}
    		return result;
    	}
    

    HttpClient通过UrlEncodedFormEntity提交带参数的请求

    图12

    使用apacheHttpClient发送post请求

    https://blog.csdn.net/xiaoyaoyulinger/article/details/77315694

    JAVA http请求工具类http-request

    https://www.jianshu.com/p/e955b01e2e16

    获取微信用户信息

    https://blog.csdn.net/wolfcode_cn/article/details/80755359

    图13

    两种scope授权作用域
    配置授权域名

    引导用户打开授权界面:

    https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect

    图14

    code来获取网页授权专用的access_token凭据

    地址:

    https://blog.csdn.net/wolfcode_cn/article/details/80755359

    达叔小生:往后余生,唯独有你
    You and me, we are family !
    90后帅气小伙,良好的开发习惯;独立思考的能力;主动并且善于沟通
    简书博客: 达叔小生
    https://www.jianshu.com/u/c785ece603d1

    结语

    • 下面我将继续对 其他知识 深入讲解 ,有兴趣可以继续关注
    • 小礼物走一走 or 点赞
  • 相关阅读:
    微信小程序HTTPS
    微信商城-1简介
    va_list
    Event log c++ sample.
    EVENT LOGGING
    Analyze Program Runtime Stack
    unknow table alarmtemp error when drop database (mysql)
    This application has request the Runtime to terminate it in an unusual way.
    How to check if Visual Studio 2005 SP1 is installed
    SetUnhandledExceptionFilter
  • 原文地址:https://www.cnblogs.com/dashucoding/p/9867809.html
Copyright © 2011-2022 走看看