微信公众号学习与开发过程

微信公众号开发(java)

一、了解微信开发基本概念

参考微信的开发技术文档,对微信开发整体概念有个印象,对其涉及的名词有所了解

微信官方文档:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141014

二、微信开发环境搭建

1.首先导入weixin4j开发框架,参考网址:http://www.weixin4j.org/

进入weixin4j官网后,选择源码下载,可根据需要下载自己所需框架:

最基本框架weixin4j:https://github.com/ansitech/weixin4j
(weixin4j是一个用Java编写针对微信开发的工具包,为Java微信开发爱好者提供的微信公众开发平台SDK.此框架中封装了微信中最基本、底层的功能、其他框架结构都在此框架基础上进行改写、在此封装)

weixin_springmvc框架:https://github.com/ansitech/weixin4j-spring

weixin_springboot框架:https://github.com/ansitech/weixin4j-spring-boot

2.导入框架后,进行微信环境的部署、配置

若所搭环境为weixin4j、springmvc,则在项目下的weixin4j.properties文件中进行配置:

微信公众号学习与开发过程

如搭建的springboot框架,则也可在application.properties文件中进行配置:

微信公众号学习与开发过程

  • 在此对微信开发环境搭建做了简单的介绍,若了解更多可参考杨启盛的微博https://blog.csdn.net/yakson/article/details/82108649,介绍的很详细。

3.开发者接入

在开发者接入之前,要做一些准备工作,申请公众号(在此以微信测试号为例)

(在申请一个微信公众号的时候,发现如果不是公司或组织只能申请订阅号(并且是个人的),而且不能使用微信提供的高级接口,所以如果想要使用公众平台的高级接口的话,申请一个微信公众平台接口测试账号就会非常方便了。使用微信公众平台接口测试账号,无需公众账号,快速申请接口测试号,能够直接体验和测试公众平台所有高级接口。)

(1)申请微信公众平台接口测试账号
weixin4j项目名:http://sui87u.natappfree.cc/weixin4j/api/weixin4j

springmvc项目名:http://e7qd3n.natappfree.cc/weixin4j-springmvc-example-annotation/weixin/jieru

springboot项目名:http://cbacu4.natappfree.cc/weixin/jieru
  • Token处,须与配置文件weixin4j中的配置相同
(2)申请测试域名

在我们本地测试的时候,需要将我们的本地地址映射到公网,我们使用一个免费且非常方便的工具:natapp。下面的地址是natapp的官网和natapp的使用教程:

参考网址https://blog.csdn.net/rongxiang111/article/details/78765514

  • 完成以上申请流程后,打开cmd命令窗口,输入:

natapp -authtoken=你的authtoken
例如我的:natapp -authtoken=a91c3c0dee0b4ef2 便可看到临时生成的域名微信公众号学习与开发过程


  • 此处以boot项目开发为例:
  • 配置好以上信息,在boot项目中导入现成的JieruController.java(在weixin4j-spring框架工具包中有,就不用自己写)作为微信接入的接口,便可完成微信的接入
至此已完成了微信开发环境的搭建、拥有自己微信测试号,完成开发者的接入,便可进行微信功能的开发工作了。

三、开始开发

(以下是我开发的过程、及遇到的问题,使用springboot集成weixin4j)

1.自定义菜单的创建编辑

可通过接口调试工具可快速创建、编辑、删除菜单

调试网址:https://mp.weixin.qq.com/debug/cgi-bin/apiinfo
微信公众号学习与开发过程

创建菜单格式举例:

{
    "button": [
        {
            "type": "view", 
            "name": "上报", 
            "url": "http://yd5d4w.natappfree.cc/click/issueUrl", 
            "sub_button": [ ]
        }, 
        {
            "type": "view", 
            "name": "查询", 
            "url": "http://yd5d4w.natappfree.cc/click/historyListUrl", 
            "sub_button": [ ]
        }
    ]
}

2.获取code、access_token、oppenId、noceStr、signature、timestamp等信息(当时遇到的一个小难点)

  • 首先必须配置好网页授权回调页面域名:
    微信公众号学习与开发过程
  • 当用户点击微信中的菜单时,通过后台授权处理,用户同意授权后跳转到某个页面,该页面链接上便会携带code参数,此时便能获取到code;
@RequestMapping("/issueUrl")
	public String url(String url,HttpServletRequest res) throws IOException {
		Weixin w = new Weixin(); 
	    String appId = w.getAppId();
	    String secret = w.getSecret();
		Weixin weixin = new Weixin(appId,secret);
        SnsComponent s = new SnsComponent(weixin);
        //授权后重定向的回调链接地址
        String OAuth2CodeUserInfoUrl = s.getOAuth2CodeUserInfoUrl(Url+"/click/index");
        return "redirect:"+OAuth2CodeUserInfoUrl;
	} 
	
	//获取code、token、openid等用户信息,以便传值给index页面。
	@RequestMapping("/index")
	public String getCode(HttpServletRequest request,HttpServletResponse response,Model model) throws IOException {
		System.out.println("/index");
		String code = "";
		String state = "";
		code = request.getParameter("code");
		state = request.getParameter("state");
		System.out.println("code:"+code+",state:"+state);
  • 有了code值,便可获取到用户信息oppenid等,在通过ticket获取到nonceStr、signature、timestamp变量
		Weixin w = new Weixin(); 
		String appId = w.getAppId();
		String secret = w.getSecret();
		Token token = null;
		String accessToken = "";
		try {
			token = w.getToken();
			accessToken = token.getAccess_token();
		} catch (WeixinException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		Weixin weixin = new Weixin(appId,secret);
		SnsComponent s = new SnsComponent(weixin);
		String openId = null;
		try {
			openId = s.getOpenId(code);
		} catch (WeixinException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String ticket = "";
		try {
			Ticket  jsApiTicket = weixin.getJsApiTicket();
			ticket = jsApiTicket.getTicket();
			
		} catch (WeixinException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String url = "http://bmaepa.natappfree.cc/click/index"+"?code="+code+"&state="+state;
		JsSdkComponent js = new JsSdkComponent(weixin);
		WxConfig wxConfig = js.getWxConfig(ticket, url);
		
		String nonceStr= wxConfig.getNonceStr();// 微信加密签名
		String signature= wxConfig.getSignature();// 时间戳
		String timestamp = wxConfig.getTimestamp();       // 随机数

3.springboot框架中前后台进行数据交互

(1)springboot前端介绍

(springboot框架做到真正的前后端分离,后端只需提供相应的restful接口返回前端请求的数据,同时前后端应用也可以完全分开。)

SpringBoot里面没有我们之前常规web开发的WebContent(WebApp),它只有src目录。

在src/main/resources下面有两个文件夹,static和templates
springboot默认 static中放静态页面,而templates中放动态页面

spring boot建议不要使用JSP,默认使用Thymeleaf来做动态页面。
现在pom中要添加Thymeleaf组件

<dependency>  
    <groupId>org.springframework.boot</groupId>  
    <artifactId>spring-boot-starter-thymeleaf</artifactId>  
</dependency>

在templates文件夹下建立index.html,然后通过http://9a253j.natappfree.cc/test便可访问到该页面
微信公众号学习与开发过程

(更多有关static、templates目录的了解请参考:https://blog.csdn.net/ypbsyy/article/details/80887128)

(2)前后台数据交互

我们通常在后台controller中使用model.addAttribute()进行数据绑定,但是由于前台使用html页面,页面中就不能使用常规的$(“xxx”)来获取后台的绑定的数据了,此时,我们需引入thymeleaf模板来获取数据。
微信公众号学习与开发过程

再通过以下标签形式便可完成前后台数据的交互

后台controller:
微信公众号学习与开发过程
前台html:
微信公众号学习与开发过程

可参考博客:https://blog.csdn.net/supermao1013/article/details/62447610/

(3)前台如何引入js、css文件

在html页面中使用的js、css文件,通常作为静态资源放在static文件夹下,如下:

微信公众号学习与开发过程

html页面整合thymeleaf模板,我们需同样使用标签的形式引入js、css文件

引入css文件:
微信公众号学习与开发过程
引入js文件:
微信公众号学习与开发过程

4.微信调用手机相册,完成图片上传

首先我们需要引入jweixin-1.2.0.js文件,该文件中包含微信功能所需的一些接口,然后在
wx.config({…})配置需使用的接口
微信公众号学习与开发过程
注意:此处ocnfig中的appId、timestamp、nonceStr、signature须与后台获取到的数据对应上

可重写图片上传相关接口,例重写调用手机相册chooseImage接口(当点击上传链接时触发photo函数,调动手机相册接口)

function photo() {
	wx.chooseImage({
		count: 3, // 默认9
		sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
		sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
		success: function(res) {
			localIds = res.localIds;
			// 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片
			for (var i = 0; i < localIds.length; i++) {
  				localId = localIds[i];
				if(/ip(hone|od)|ipad/i.test(navigator.userAgent)){
					pi = localId.substring(18);
				}else{
					pi = localId.substring(20);
				}
				imghtml='<div id="'
					+'pimg' + pi 
					+'"class="image-item">'
					+'<div class="image-close" onclick="btnclo()">X</div>'
					+'<img src="'
					+ localId//照片地址
					+'" width="100%" height="100%"/>'
					+'</div>';	
				$("#image-list").prepend(imghtml);
				picArr.push(localId);

			}
			
			if(picArr.length >= 6){
				$("#image-item").remove();	
			}

		}
	});
		
}

5.微信分享功能开发

同样引入jweixin-1.2.0.js文件,在wx.config({…})配置微信分享相关接口
微信公众号学习与开发过程
(在开发此处功能时,遇到个小问题,困扰了我两天才得以解决,当微信将当前页面分享到朋友圈或好友时,可分享成功,但是用户点不开链接,后台报错code值缺失)

针对分享后当前页面code值缺失的问题,原因是分享后又重新进入该页面,此时的页面是没有通过授处理而直接进入页面,此时没有经过授权处理的页面链接上自然没有code参数,因此报code缺失异常

解决方案:在后台进行判断,如果code值为空,进行重新授权处理
微信公众号学习与开发过程

6.自定义菜单管理功能的开发

通过菜单管理页面方便了用户对微信中菜单的管理,也方便使用微信测试号的用户,不用通过接口调试,便可对菜单进行管理(对于没有公众平台账号的、或不用登陆公众平台的用户,对微信菜单的管理更加方便)
微信公众号学习与开发过程

7.apache 端口转发

##<VirtualHost *:80>
    ##ServerAdmin [email protected]
    ##DocumentRoot "/xampp/htdocs/dummy-host.example.com"
    ##ServerName dummy-host.example.com
    ##ServerAlias www.dummy-host.example.com
    ##ErrorLog "logs/dummy-host.example.com-error.log"
    ##CustomLog "logs/dummy-host.example.com-access.log" common
##</VirtualHost>

##<VirtualHost *:80>
    ##ServerAdmin [email protected]
    ##DocumentRoot "/xampp/htdocs/dummy-host2.example.com"
    ##ServerName dummy-host2.example.com
    ##ErrorLog "logs/dummy-host2.example.com-error.log"
    ##CustomLog "logs/dummy-host2.example.com-access.log" common
##</VirtualHost>
<VirtualHost *:80>
	 ServerAdmin [email protected]
	 ServerName  ums.***china.com
	 ServerAlias ums.***china.com
	 ProxyPass / http://47.94.139.***:8003/(这里就是你要转发到的地址,就是Tomcat中的地址)  
	 ProxyPassReverse / http://47.94.139.***:8003/ (指令用于处理重定向时的转发)  
	 ErrorLog "logs/ums.***china.com-error.log"
	 CustomLog "logs/ums.***china.com-access.log" common
</VirtualHost>
<VirtualHost *:80>
	 ServerAdmin [email protected]
	 
	 ServerName  www.***china.com
	 ServerAlias www.***china.com
	 
	 ErrorLog "logs/www.***china.com-error.log"
	 CustomLog "logs/www.***china.com-access.log" common
</VirtualHost>

对apache的配置及参考网址:https://www.cnblogs.com/devcjq/articles/6490327.html