公众号开发笔记二

摘要:
access_token=access_token返回的数据:调用接口删除account://Request方法:POSThttps://api.weixin.qq.com/cgi-bin/template/del_private_template?access_token=ACCESS_TOKEN必需:OPENIDtemplate_Idulminiprogram成功调用模板消息接口:{“errcode”:0,“errmsg”:“ok”,“msgid”:200228332}事件推送消息模板已成功发送到公众号,微信服务器将作为服务器配置地址通知开发中心发送成功。推送XML代码:模板消息接口文档https://www.cnblogs.com/jiqing9006/p/5220571.html查看模板的详细信息:#可以分组发送到指定的openIDhttps://segmentfault.com/a/1190000012828138php实施https://www.cnblogs.com/jiqing9006/p/5220571.html实例化--˃获取appid,appsecret获取access_令牌发送模板消息,组合消息数据以获取openid,并发送消息。发送模板消息的接口为:https://api.weixin.qq.com/cgi-bin/message/template/send?

标题图

前言

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

只有认证后的服务号才能申请模板消息,需要选择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 点赞

免责声明:文章转载自《公众号开发笔记二》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇Charles的使用关于箭头函数下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

使用RemObjects Pascal Script (转)

http://www.cnblogs.com/MaxWoods/p/3304954.html 摘自RemObjects Wiki 本文提供RemObjects Pascal Script的整体概要并演示如何创建一些简单的脚本. Pascal Script包括两个不同部分: 编译器 (uPSCompiler.pas) 运行时 (uPSRuntime.pas...

kafka-producer kerberos 原理和配置

kerberos简单介绍 kerberos这一名词来源于希腊神话“三个头的狗---地狱之门守护者”后来沿用作为安全认证的概念,该系统设计上 采用客户端/服务器结构与DES(Data Encryption Standard标准加密技术),AES(Advanced Encryption Standerd 高级加密技术)等加密技术,并且能够进行相互认证,即客户端...

在MDK中使用 printf 函数

microlib 提供了一个有限的 stdio 子系统,它仅支持未缓冲的 stdin、stdout 和 stderr。 这样,即可使用 printf() 来显示应用程序中的诊断消息。 要使用高级 I/O 函数,您必须提供自己实现的以下基本函数,以便与您自己的 I/O 设备配合使用。 fputc()  为所有输出函数实现此基本函数。 例如,fprintf(...

总结:String类型与Int类型的转换【实现插入操作主键自增】

1、String类型(此类型是数字格式的字符串类型)转换成Int类型 String str = "10000"; 转换成Int类型: int num = Integer.parseInt(str); 得到的结果是:int类型的10000 2、int类型转换成String类型 int n = 1000; n = n +1; String str = Stri...

java过滤特殊字符的正则表达式

// 过滤特殊字符 public staticString StringFilter(String str) throws PatternSyntaxException { // 只允许字母和数字 // String regEx ="[^a-zA-Z0-9]"; // 清除掉所有特殊字符 String regEx="[`~!@#$%^&*()+...

【Win32 API学习】RegisterWindowMessage小记

RegisterWindowMessage函数定义了一个新的窗口消息,该消息在系统范围内是唯一的。通常调用SendMessage或者PostMessage函数时可以使用该函数返回的消息值。 函数原型:   UINT RegisterWindowMessage( lpString);参数说明:   lpString指向一个以NULL结束的字符串,指定待注册的消...