1、登录微信公众平台配置业务域名和JS接口安全域名(不带http://)

java公众号微信支付开发 java微信公众号开发源码_github

2、 服务器配置(如果服务器配置开启,则用户发送给公众号的消息和事件都会被微信转发到配置的url中,开发者可自行处理)

java公众号微信支付开发 java微信公众号开发源码_java公众号微信支付开发_02

 

服务器地址(URL)具体代码如下:

微信公众号开发依赖包:

<!--添加微信依赖 begin-->
    <!-- https://mvnrepository.com/artifact/com.github.binarywang/weixin-java-common -->
    <dependency>
      <groupId>com.github.binarywang</groupId>
      <artifactId>weixin-java-common</artifactId>
      <version>2.7.0</version>
    </dependency>
    <dependency>
      <groupId>com.github.binarywang</groupId>
      <artifactId>weixin-java-mp</artifactId>
      <version>2.8.5.BETA</version>
    </dependency>
<!--添加微信依赖 end-->
@Configuration
public class WeChatAccountConfig {

	@Value("${wechat.appId}")
	private String appId;

	@Value("${wechat.appSecret}")
	private String appSecret;

	@Value("${wechat.token}")
	private String token;

	@Value("${wechat.encodingAESKey}")
	private String encodingAESKey;

	public String getAppId() {
		return appId;
	}

	public String getAppSecret() {
		return appSecret;
	}

	public String getToken() {
		return token;
	}

	public String getEncodingAESKey() {
		return encodingAESKey;
	}
}
@Component
public class WeChatConfig {

	@Autowired
	private WeChatAccountConfig weChatAccountConfig;

	@Bean
	public WxMpService wxMpService(){
		WxMpService wxMpService = new WxMpServiceImpl();
		wxMpService.setWxMpConfigStorage(wxMpConfigStorage());
		return wxMpService;
	}

	public WxMpConfigStorage wxMpConfigStorage(){
		WxMpInMemoryConfigStorage wxMpConfigStorage = new WxMpInMemoryConfigStorage();
		wxMpConfigStorage.setAppId(weChatAccountConfig.getAppId());
		wxMpConfigStorage.setSecret(weChatAccountConfig.getAppSecret());
		wxMpConfigStorage.setToken(weChatAccountConfig.getToken());
		wxMpConfigStorage.setAesKey(weChatAccountConfig.getEncodingAESKey());
		return wxMpConfigStorage;
	}

}
@RestController
@RequestMapping(value = "/wechat")
public class WeChatCallBackController {

	@Autowired
	private WxMpService wxMpService;


	/**
	 * 订阅号(监听关注、取关事件处理)
	 * @param signature
	 * @param nonce
	 * @param timestamp
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/callback")
	public String callback(@RequestParam("signature") String signature,
						 @RequestParam("nonce")String nonce,
						 @RequestParam("timestamp")String timestamp,
						 HttpServletRequest request) throws Exception {
		String echostr = "";
		System.out.println("signature:" + signature);
		System.out.println("nonce:" + nonce);
		System.out.println("timestamp:" + timestamp);
		// 验证消息签名,说明不是公众平台发送来的消息
		if (!wxMpService.checkSignature(timestamp, nonce, signature)) {
			return "非法访问";
		}
		// 说明是一个仅仅用来验证的请求,回显echostr
		echostr = request.getParameter("echostr");
		if (!StringUtils.isEmpty(echostr)) {
			return echostr;
		}
		String encryptType = StringUtils.isEmpty(request.getParameter("encrypt_type")) ? "raw" : request.getParameter("encrypt_type");
		if ("raw".equals(encryptType)) {
			// 明文传输的消息
			WxMpXmlMessage message = WxMpXmlMessage.fromXml(request.getInputStream());
			return message.toString();
		}
		if ("aes".equals(encryptType)) {
			// 是aes加密的消息
			String msgSignature = request.getParameter("msg_signature");
			WxMpXmlMessage message = WxMpXmlMessage.fromEncryptedXml(request.getInputStream(), wxMpService.getWxMpConfigStorage(), timestamp, nonce, msgSignature);
			return message.toString();
		}
		return "不可识别的加密类型";
	}


}

3、微信分享功能开发

(1)在需要调用JS接口的页面引入如下JS文件,(支持https):http://res.wx.qq.com/open/js/jweixin-1.4.0.js

(2)通过config接口注入权限验证配置

wx.config({
    debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
    appId: '', // 必填,公众号的唯一标识
    timestamp: , // 必填,生成签名的时间戳
    nonceStr: '', // 必填,生成签名的随机串
    signature: '',// 必填,签名
    jsApiList: [] // 必填,需要使用的JS接口列表
});

config配置Demo

@RestController
@RequestMapping(value = "/wechat")
public class WeChatSharingController {

	@Autowired
	private WxMpService wxMpService;

	@RequestMapping(value = "/share")
	public Result share(@RequestParam("url") String url) {
		Result result = new Result();
		try {
			WxJsapiSignature signature = wxMpService.createJsapiSignature(url);
			Result.getSuccessResult(result, "请求成功", signature);
		} catch (Exception e) {
			Result.getErrorResult(result, "分享出现错误");
		}
		return result;
	}

}
$.ajax('/wechat/share', {
            data: {"url": window.location.href},
            dataType: 'json',//服务器返回json格式数据
            type: 'get',//HTTP请求类型
            timeout: 10000,//超时时间设置为10秒;
            contentType: 'application/json',
            success: function (data) {
                if (data.code == 0) {
                    wx.config({
                        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
                        appId: data.data.appId, // 必填,公众号的唯一标识
                        timestamp: data.data.timestamp, // 必填,生成签名的时间戳
                        nonceStr: data.data.nonceStr, // 必填,生成签名的随机串
                        signature: data.data.signature,// 必填,签名,见附录1
                        jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage'] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
                    });
                }
            },
            error: function (xhr, status, error) {
                //异常处理;
                console.log(error);
            }
        });

(3)通过ready接口处理成功验证

wx.ready(function() {
            wx.hideMenuItems({
                menuList: ['menuItem:share:qq','menuItem:share:weiboApp','menuItem:share:facebook','menuItem:share:QZone'] // 要隐藏的菜单项,只能隐藏“传播类”和“保护类”按钮,所有menu项见附录3
            });
            // 获取"分享到朋友圈"按钮点击状态及自定义分享内容接口
            wx.onMenuShareTimeline({
                title: '#', // 分享标题
                link: '#',
                imgUrl: '#' // 分享图标
            });


            // 获取"分享给朋友"按钮点击状态及自定义分享内容接口
            wx.onMenuShareAppMessage({
                title: '#', // 分享标题
                desc: '#', // 分享描述
                link: window.location.href,
                imgUrl: '#', // 分享图标
                type: 'link' // 分享类型,music、video或link,不填默认为link
            });
        })