1.使用jar(maven)
me.chanjar
weixin-java-mp
1.3.3
2.创建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);
}
}
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 wxMpUser = wxMpService.userInfo(oauth2AccessToken.getOpenId(),null);
这个只是部分的代码,具体的说明,请亲自查看源码。
5.总结
这个框架非常不错,除了wiki少了些外,希望更多牛人参与进入项目,再次感谢作者(chanjarster)。
6.补充
不知道什么原因,这个项目许久未维护了,所以在这个项目下有说明其分支的新的项目,QQ群(343954419),新分支优化了很多,维护也积极,Demo和说明也全,建议你直接看源码里的说明,聪明的你肯定喜欢上的;另外感谢为该分支的贡献者们,让微信开发变得简单。