微信小程式 獲取 open-id --- SpringBoot
阿新 • • 發佈:2018-12-11
1.Pom.xml加入依賴
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-miniapp</artifactId>
<version>3.0.0</version>
</dependency>
2.設定配置類 WxMaConfiguration 類
@Configuration @ConditionalOnClass(WxMaService.class) @EnableConfigurationProperties(WxMaProperties.class) public class WxMaConfiguration { private static final WxMaMessageHandler templateMsgHandler = (wxMessage, context, service, sessionManager) -> service.getMsgService().sendTemplateMsg(WxMaTemplateMessage.builder() .templateId("此處更換為自己的模板id") .formId("自己替換可用的formid") .data(Lists.newArrayList( new WxMaTemplateMessage.Data("keyword1", "339208499", "#173177"))) .toUser(wxMessage.getFromUser()) .build()); private final WxMaMessageHandler logHandler = (wxMessage, context, service, sessionManager) -> { System.out.println("收到訊息:" + wxMessage.toString()); service.getMsgService().sendKefuMsg(WxMaKefuMessage.newTextBuilder().content("收到資訊為:" + wxMessage.toJson()) .toUser(wxMessage.getFromUser()).build()); }; private final WxMaMessageHandler textHandler = (wxMessage, context, service, sessionManager) -> service.getMsgService().sendKefuMsg(WxMaKefuMessage.newTextBuilder().content("回覆文字訊息") .toUser(wxMessage.getFromUser()).build()); private final WxMaMessageHandler picHandler = (wxMessage, context, service, sessionManager) -> { try { WxMediaUploadResult uploadResult = service.getMediaService() .uploadMedia("image", "png", ClassLoader.getSystemResourceAsStream("tmp.png")); service.getMsgService().sendKefuMsg( WxMaKefuMessage .newImageBuilder() .mediaId(uploadResult.getMediaId()) .toUser(wxMessage.getFromUser()) .build()); } catch (WxErrorException e) { e.printStackTrace(); } }; private final WxMaMessageHandler qrcodeHandler = (wxMessage, context, service, sessionManager) -> { try { final File file = service.getQrcodeService().createQrcode("123", 430); WxMediaUploadResult uploadResult = service.getMediaService().uploadMedia("image", file); service.getMsgService().sendKefuMsg( WxMaKefuMessage .newImageBuilder() .mediaId(uploadResult.getMediaId()) .toUser(wxMessage.getFromUser()) .build()); } catch (WxErrorException e) { e.printStackTrace(); } }; @Autowired private WxMaProperties properties; @Bean @ConditionalOnMissingBean public WxMaConfig maConfig() { WxMaInMemoryConfig config = new WxMaInMemoryConfig(); config.setAppid(this.properties.getAppid()); config.setSecret(this.properties.getSecret()); config.setToken(this.properties.getToken()); config.setAesKey(this.properties.getAesKey()); config.setMsgDataFormat(this.properties.getMsgDataFormat()); return config; } @Bean @ConditionalOnMissingBean public WxMaService wxMaService(WxMaConfig maConfig) { WxMaService service = new WxMaServiceImpl(); service.setWxMaConfig(maConfig); return service; } @Bean public WxMaMessageRouter router(WxMaService service) { final WxMaMessageRouter router = new WxMaMessageRouter(service); router .rule().handler(logHandler).next() .rule().async(false).content("模板").handler(templateMsgHandler).end() .rule().async(false).content("文字").handler(textHandler).end() .rule().async(false).content("圖片").handler(picHandler).end() .rule().async(false).content("二維碼").handler(qrcodeHandler).end(); return router; } }
R類
/** * 返回資料 * * @author chenshun * @email [email protected] * @date 2016年10月27日 下午9:59:27 */ public class R extends HashMap<String, Object> { private static final long serialVersionUID = 1L; public R() { put("code", 0); put("msg", "success"); } public static R error() { return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, "未知異常,請聯絡管理員"); } public static R error(String msg) { return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, msg); } public static R error(int code, String msg) { R r = new R(); r.put("code", code); r.put("msg", msg); return r; } public static R ok(String msg) { R r = new R(); r.put("msg", msg); return r; } public static R ok(Map<String, Object> map) { R r = new R(); r.putAll(map); return r; } public static R ok() { return new R(); } public R put(String key, Object value) { super.put(key, value); return this; } }
3.微信賬號相關的寫個配置 WxMaProperties.java
@ConfigurationProperties(prefix = "wechat.miniapp") public class WxMaProperties { /** * 設定微信小程式的appid */ private String appid; /** * 設定微信小程式的Secret */ private String secret; /** * 設定微信小程式的token */ private String token; /** * 設定微信小程式的EncodingAESKey */ private String aesKey; /** * 訊息格式,XML或者JSON */ private String msgDataFormat; public String getAppid() { return this.appid; } public void setAppid(String appid) { this.appid = appid; } public String getSecret() { return this.secret; } public void setSecret(String secret) { this.secret = secret; } public String getToken() { return this.token; } public void setToken(String token) { this.token = token; } public String getAesKey() { return this.aesKey; } public void setAesKey(String aesKey) { this.aesKey = aesKey; } public String getMsgDataFormat() { return msgDataFormat; } public void setMsgDataFormat(String msgDataFormat) { this.msgDataFormat = msgDataFormat; } @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE); } }
4.專案配置檔案中配置 application.yml中
miniapp:
appid: 自己的appid
secret: 自己的 mpAppSecret
token: 111
aesKey: 111
msgDataFormat: JSON
5.寫Controller類 WechatController
@RestController
@RequestMapping("/wechat")
public class WechatController {
@Autowired
private WxMaService wxMaService;
@ResponseBody
@RequestMapping(value = "/getSessionInfo",method = RequestMethod.GET)
@ApiOperation("根據code獲取SessionInfo")
public R getSessionInfo(String code) {
if (code != null && code.length() < 0) {
return R.error("Code為空!");
}
try {
WxMaJscode2SessionResult session = this.wxMaService.getUserService().getSessionInfo(code);
return R.ok().put("session", session);
} catch (WxErrorException e) {
return R.error(e.toString());
}
}
}
執行程式測試一下吧 測試地址 : http://localhost:8080/wechat/getSessionInfo 用小程式測試一下吧