1.使用jar(maven)
me.chanjar
weixin-java-mp
1.3.3
2.创建weixin包,添加类
package com.weixin;
import java.io.InputStream;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import org.xml.sax.InputSource;
@XmlRootElement(name = "xml")
@XmlAccessorType(XmlAccessType.FIELD)
class WxMpXMLInMemoryConfigStorage extends WxMpInMemoryConfigStorage {
public static WxMpXMLInMemoryConfigStorage fromXml(InputStream is)
throws JAXBException {
Unmarshaller um = JAXBContext.newInstance(
WxMpXMLInMemoryConfigStorage.class).createUnmarshaller();
InputSource inputSource = new InputSource(is);
inputSource.setEncoding("utf-8");
return (WxMpXMLInMemoryConfigStorage) um.unmarshal(inputSource);
}
}
package com.weixin;
import java.io.InputStream;
import me.chanjar.weixin.mp.api.WxMpConfigStorage;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.WxMpServiceImpl;
public class WxMpServiceInstance {
private WxMpService wxMpService;
private WxMpConfigStorage wxMpConfigStorage;
private WxMpMessageRouter wxMpMessageRouter;
private static WxMpServiceInstance instance = null;
public static WxMpServiceInstance getInstance() {
if (instance == null) {
try {
instance = new WxMpServiceInstance();
} catch (Exception e) {
e.printStackTrace();
}
}
return instance;
}
private WxMpServiceInstance() throws Exception {
wxMpService = new WxMpServiceImpl();
// 读取配置文件
InputStream inputStream = WxMpServiceInstance.class
.getResourceAsStream("/config/weixin.xml");
wxMpConfigStorage = WxMpXMLInMemoryConfigStorage.fromXml(inputStream);
wxMpService.setWxMpConfigStorage(wxMpConfigStorage);
wxMpMessageRouter = new WxMpMessageRouter(wxMpService);
}
public WxMpService getWxMpService() {
return wxMpService;
}
public WxMpConfigStorage getWxMpConfigStorage() {
return wxMpConfigStorage;
}
public WxMpMessageRouter getWxMpMessageRouter() {
return wxMpMessageRouter;
}
}
3.配置文件(src/config/weixin.xml)
123456789
123456789
123456789
123456789
123456789
123456789
123456789
4.使用示例获取登录用户信息
采用snsapi_base为scope发起的网页授权,是用来获取进入页面的用户的openid的方式,具体请查看微信相关文档
String code = request.getParameter("code");
WxMpService wxMpService = WxMpServiceInstance.getInstance()
.getWxMpService();
// 获取授权
WxMpOAuth2AccessToken oauth2AccessToken = wxMpService
.oauth2getAccessToken(code);
// 授权信息获取用户
wxMpUser = wxMpService.userInfo(oauth2AccessToken.getOpenId(),
null);
这个只是部分的代码,具体的说明,请亲自查看源码。
5.总结
这个框架非常不错,除了wiki少了些外,希望更多牛人参与进入,再次感谢作者。