cn.binarywang.wx.miniapp.api.WxMaService Java Examples

The following examples show how to use cn.binarywang.wx.miniapp.api.WxMaService. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WxMaDemoServer.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(WxMaMessage wxMessage, Map<String, Object> context,
                   WxMaService service, WxSessionManager sessionManager) throws WxErrorException {
  try {
    WxMediaUploadResult uploadResult = service.getMediaService()
      .uploadMedia(WxMaConstants.MediaType.IMAGE, "png",
        ClassLoader.getSystemResourceAsStream("tmp.png"));
    service.getMsgService().sendKefuMsg(
      WxMaKefuMessage
        .newImageBuilder()
        .mediaId(uploadResult.getMediaId())
        .toUser(wxMessage.getFromUser())
        .build());
  } catch (WxErrorException e) {
    e.printStackTrace();
  }
}
 
Example #2
Source File: WxMaUser.java    From yue-library with Apache License 2.0 6 votes vote down vote up
@PostConstruct
private void init() {
    List<WxMaProperties.Config> configs = wxMaProperties.getConfigs();
    if (ListUtils.isEmpty(configs)) {
    	throw new RuntimeException("无效的小程序配置...");
    }
    
    maServices = configs.stream()
        .map(a -> {
            WxMaInMemoryConfig config = new WxMaInMemoryConfig();
            config.setAppid(a.getAppid());
            config.setSecret(a.getSecret());
            WxMaService service = new WxMaServiceImpl();
            service.setWxMaConfig(config);
            return service;
        }).collect(Collectors.toMap(s -> s.getWxMaConfig().getAppid(), a -> a));
}
 
Example #3
Source File: WxMaDemoServer.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(WxMaMessage wxMessage, Map<String, Object> context,
                   WxMaService service, WxSessionManager sessionManager) throws WxErrorException {
  try {
    final File file = service.getQrcodeService().createQrcode("123", 430);
    WxMediaUploadResult uploadResult = service.getMediaService().uploadMedia(WxMaConstants.MediaType.IMAGE, file);
    service.getMsgService().sendKefuMsg(
      WxMaKefuMessage
        .newImageBuilder()
        .mediaId(uploadResult.getMediaId())
        .toUser(wxMessage.getFromUser())
        .build());
  } catch (WxErrorException e) {
    e.printStackTrace();
  }
}
 
Example #4
Source File: ApiTestModule.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
@Override
public void configure(Binder binder) {
  try (InputStream inputStream = ClassLoader.getSystemResourceAsStream(TEST_CONFIG_XML)) {
    if (inputStream == null) {
      throw new RuntimeException("测试配置文件【" + TEST_CONFIG_XML + "】未找到,请参照test-config-sample.xml文件生成");
    }
    TestConfig config = TestConfig.fromXml(inputStream);
    config.setAccessTokenLock(new ReentrantLock());

    WxMaService wxService = new cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl();
    wxService.setWxMaConfig(config);

    binder.bind(WxMaService.class).toInstance(wxService);
    binder.bind(WxMaConfig.class).toInstance(config);
  } catch (IOException e) {
    this.log.error(e.getMessage(), e);
  }
}
 
Example #5
Source File: WxUserController.java    From oneplatform with Apache License 2.0 6 votes vote down vote up
/**
 * <pre>
 * 获取用户信息接口
 * </pre>
 */
@GetMapping("/info")
@ApiPermOptions(perms = PermissionType.Logined)
public String info(@PathVariable String appid, String sessionKey,
                   String signature, String rawData, String encryptedData, String iv) {
    final WxMaService wxService = weixinAppManager.getMaService(appid);

    // 用户信息校验
    if (!wxService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
        return "user check failed";
    }

    // 解密用户信息
    WxMaUserInfo userInfo = wxService.getUserService().getUserInfo(sessionKey, encryptedData, iv);

    return JsonUtils.toJson(userInfo);
}
 
Example #6
Source File: WxUserController.java    From oneplatform with Apache License 2.0 6 votes vote down vote up
/**
 * <pre>
 * 获取用户绑定手机号信息
 * </pre>
 */
@GetMapping("/phone")
@ApiPermOptions(perms = PermissionType.Logined)
public String phone(@PathVariable String appid, String sessionKey, String signature,
                    String rawData, String encryptedData, String iv) {
    final WxMaService wxService = weixinAppManager.getMaService(appid);

    // 用户信息校验
    if (!wxService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
        return "user check failed";
    }

    // 解密
    WxMaPhoneNumberInfo phoneNoInfo = wxService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);

    return JsonUtils.toJson(phoneNoInfo);
}
 
Example #7
Source File: WxMaDemoServer.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(WxMaMessage wxMessage, Map<String, Object> context,
                   WxMaService service, WxSessionManager sessionManager)
  throws WxErrorException {
  service.getMsgService().sendKefuMsg(WxMaKefuMessage.newTextBuilder().content("回复文本消息")
    .toUser(wxMessage.getFromUser()).build());
}
 
Example #8
Source File: WxMaDemoServer.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(WxMaMessage wxMessage, Map<String, Object> context,
                   WxMaService service, WxSessionManager sessionManager) throws WxErrorException {
  System.out.println("收到消息:" + wxMessage.toString());
  service.getMsgService().sendKefuMsg(WxMaKefuMessage.newTextBuilder().content("收到信息为:" + wxMessage.toJson())
    .toUser(wxMessage.getFromUser()).build());
}
 
Example #9
Source File: WxMaServiceImpl.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Override
public String getAccessToken(boolean forceRefresh) throws WxErrorException {
  Lock lock = this.getWxMaConfig().getAccessTokenLock();
  try {
    lock.lock();

    if (this.getWxMaConfig().isAccessTokenExpired() || forceRefresh) {
      String url = String.format(WxMaService.GET_ACCESS_TOKEN_URL, this.getWxMaConfig().getAppid(),
        this.getWxMaConfig().getSecret());
      try {
        HttpGet httpGet = new HttpGet(url);
        if (this.getRequestHttpProxy() != null) {
          RequestConfig config = RequestConfig.custom().setProxy(this.getRequestHttpProxy()).build();
          httpGet.setConfig(config);
        }
        try (CloseableHttpResponse response = getRequestHttpClient().execute(httpGet)) {
          String resultContent = new BasicResponseHandler().handleResponse(response);
          WxError error = WxError.fromJson(resultContent);
          if (error.getErrorCode() != 0) {
            throw new WxErrorException(error);
          }
          WxAccessToken accessToken = WxAccessToken.fromJson(resultContent);
          this.getWxMaConfig().updateAccessToken(accessToken.getAccessToken(),
            accessToken.getExpiresIn());
        } finally {
          httpGet.releaseConnection();
        }
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
    }
  } finally {
    lock.unlock();
  }

  return this.getWxMaConfig().getAccessToken();
}
 
Example #10
Source File: WxMaDemoServer.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(WxMaMessage wxMessage, Map<String, Object> context,
                   WxMaService service, WxSessionManager sessionManager)
  throws WxErrorException {
  service.getMsgService().sendTemplateMsg(WxMaTemplateMessage.builder()
    .templateId(templateId).data(Lists.newArrayList(
      new WxMaTemplateMessage.Data("keyword1", "339208499", "#173177")))
    .toUser(wxMessage.getFromUser())
    .formId("自己替换可用的formid")
    .build());
}
 
Example #11
Source File: WxOpenComponentServiceImpl.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Override
public WxMaService getWxMaServiceByAppid(String appId) {
  WxMaService wxMaService = WX_OPEN_MA_SERVICE_MAP.get(appId);
  if (wxMaService == null) {
    synchronized (WX_OPEN_MA_SERVICE_MAP) {
      wxMaService = WX_OPEN_MA_SERVICE_MAP.get(appId);
      if (wxMaService == null) {
        wxMaService = new WxOpenMaServiceImpl(this, appId, getWxOpenConfigStorage().getWxMaConfig(appId));
        WX_OPEN_MA_SERVICE_MAP.put(appId, wxMaService);
      }
    }
  }
  return wxMaService;
}
 
Example #12
Source File: WechatMiniAppAutoConfiguration.java    From fast-family-master with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean
public WxMaService wxMaService(WxMaConfig maConfig) {
    WxMaService service = new WxMaServiceImpl();
    service.setWxMaConfig(maConfig);
    return service;
}
 
Example #13
Source File: WechatMaConfiguration.java    From cola-cloud with MIT License 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean
public WxMaService wxMaService(WxMaConfig config) {
    WxMaService service = new WxMaServiceImpl();
    service.setWxMaConfig(config);
    return service;
}
 
Example #14
Source File: WxMaMessageRouter.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
public WxMaMessageRouter(WxMaService wxMaService) {
  this.wxMaService = wxMaService;
  ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("WxMaMessageRouter-pool-%d").build();
  this.executorService = new ThreadPoolExecutor(DEFAULT_THREAD_POOL_SIZE, DEFAULT_THREAD_POOL_SIZE,
    0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), namedThreadFactory);
  this.messageDuplicateChecker = new WxMessageInMemoryDuplicateChecker();
  this.sessionManager = new StandardSessionManager();
  this.exceptionHandler = new LogExceptionHandler();
}
 
Example #15
Source File: WxMaMessageRouterRule.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
/**
 * 处理微信推送过来的消息
 */
protected void service(WxMaMessage wxMessage,
                       Map<String, Object> context,
                       WxMaService wxMaService,
                       WxSessionManager sessionManager,
                       WxErrorExceptionHandler exceptionHandler) {
  if (context == null) {
    context = new HashMap<>(16);
  }

  try {
    // 如果拦截器不通过
    for (WxMaMessageInterceptor interceptor : this.interceptors) {
      if (!interceptor.intercept(wxMessage, context, wxMaService, sessionManager)) {
        return;
      }
    }

    // 交给handler处理
    for (WxMaMessageHandler handler : this.handlers) {
      // 返回最后handler的结果
      if (handler == null) {
        continue;
      }
      handler.handle(wxMessage, context, wxMaService, sessionManager);
    }
  } catch (WxErrorException e) {
    exceptionHandler.handle(e);
  }
}
 
Example #16
Source File: WinxinUserSerivce.java    From oneplatform with Apache License 2.0 5 votes vote down vote up
public Integer findUserIdByWeAppCode(String group,String code){
	final WxMaService wxService = weixinAppManager.getMaService(group);
       try {
           WxMaJscode2SessionResult wxsession = wxService.getUserService().getSessionInfo(code);
           Integer userId = findUserIdByOpenId(wxsession.getOpenid());
           return userId;
       } catch (WxErrorException e) {
           throw new JeesuiteBaseException(500, e.getMessage());
       }
}
 
Example #17
Source File: WeixinAppManager.java    From oneplatform with Apache License 2.0 5 votes vote down vote up
public WxMaService getMaService(String appAlias) {
    WxMaService wxService = maServices.get(appAlias);
    if (wxService == null) {
        throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置,请核实!", appAlias));
    }

    return wxService;
}
 
Example #18
Source File: WeixinAppManager.java    From oneplatform with Apache License 2.0 5 votes vote down vote up
private WxMaMessageRouter newRouter(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;
}
 
Example #19
Source File: WxMaConfiguration.java    From sdb-mall with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean
public WxMaService wxMaService(WxMaConfig maConfig) {
    WxMaService service = new WxMaServiceImpl();
    service.setWxMaConfig(maConfig);
    return service;
}
 
Example #20
Source File: WxMaConfiguration.java    From mall4j with GNU Affero General Public License v3.0 5 votes vote down vote up
@Bean
public WxMaService wxMaService() {
    WxMaServiceClusterImpl service = new WxMaServiceClusterImpl();
    service.setWxMaConfig(wxMaInRedisConfig);
    service.setRedissonClient(redissonClient);
    return service;
}
 
Example #21
Source File: MiniAppConfiguration.java    From springboot-seed with MIT License 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean
public WxMaService wxMaService(WxMaConfig maConfig) {
    WxMaService service = new WxMaServiceImpl();
    service.setWxMaConfig(maConfig);
    return service;
}
 
Example #22
Source File: WxMaUser.java    From yue-library with Apache License 2.0 5 votes vote down vote up
/**
 * <pre>
 * 获取用户信息
 * </pre>
 * 
 * @param appid	APPID
 * @param sessionKey 会话密钥
 * @param signature 数据签名
 * @param rawData 微信用户基本信息
 * @param encryptedData 消息密文
 * @param iv 加密算法的初始向量
 * @return {@linkplain WxMaUserInfo} 微信小程序用户信息
 */
public WxMaUserInfo getUserInfo(String appid, String sessionKey, String signature, 
                   String rawData, String encryptedData, String iv) {
    WxMaService wxService = getMaService(appid);
    
    // 用户信息校验
    if (!wxService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
    	throw new ParamException("user check failed");
    }

    // 解密用户信息
    WxMaUserInfo wxMaUserInfo = wxService.getUserService().getUserInfo(sessionKey, encryptedData, iv);

    return wxMaUserInfo;
}
 
Example #23
Source File: WxMaUser.java    From yue-library with Apache License 2.0 5 votes vote down vote up
/**
* 获取登录后的session信息
* 
* @param appid APPID
* @param code 授权CODE码
* @return {@linkplain WxMaJscode2SessionResult} <code style="color:red">unionid 用户在开放平台的唯一标识符,在满足 UnionID 下发条件的情况下会返回,详见 <a href="https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/union-id.html">UnionID 机制说明</a> 。</code>
*/
  public WxMaJscode2SessionResult getSessionInfo(String appid, String code) {
      WxMaService wxService = getMaService(appid);
      WxMaJscode2SessionResult wxMaJscode2SessionResult = null;
try {
	wxMaJscode2SessionResult = wxService.getUserService().getSessionInfo(code);
} catch (WxErrorException e) {
	String msg = e.getMessage();
	throw new ResultException(ResultInfo.devCustomTypePrompt(msg));
}

return wxMaJscode2SessionResult;
  }
 
Example #24
Source File: WxMaUser.java    From yue-library with Apache License 2.0 5 votes vote down vote up
private WxMaService getMaService(String appid) {
    WxMaService wxService = maServices.get(appid);
    if (wxService == null) {
        throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置,请核实!", appid));
    }

    return wxService;
}
 
Example #25
Source File: WechatMiniAppConfiguration.java    From loc-framework with MIT License 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean
public WxMaService wxMaService(WxMaConfig maConfig) {
  WxMaService service = new WxMaServiceImpl();
  service.setWxMaConfig(maConfig);
  return service;
}
 
Example #26
Source File: WechatMiniAppConfiguration.java    From loc-framework with MIT License 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean
public WxMaService wxMaService(WxMaConfig maConfig) {
  WxMaService service = new WxMaServiceImpl();
  service.setWxMaConfig(maConfig);
  return service;
}
 
Example #27
Source File: WxMiniAppConfiguration.java    From xiaoyuanxianyu with Apache License 2.0 4 votes vote down vote up
@Bean
public WxMaService Service() {
    WxMaService service  = new WxMaServiceImpl();
    service.setWxMaConfig(WxConfig());
    return service;
}
 
Example #28
Source File: WxConfig.java    From litemall with MIT License 4 votes vote down vote up
@Bean
public WxMaService wxMaService(WxMaConfig maConfig) {
    WxMaService service = new WxMaServiceImpl();
    service.setWxMaConfig(maConfig);
    return service;
}
 
Example #29
Source File: WxMaCodeServiceImpl.java    From weixin-java-tools with Apache License 2.0 4 votes vote down vote up
public WxMaCodeServiceImpl(WxMaService wxMaService) {
  this.wxMaService = wxMaService;
}
 
Example #30
Source File: WxMaSettingServiceImpl.java    From weixin-java-tools with Apache License 2.0 4 votes vote down vote up
public WxMaSettingServiceImpl(WxMaService wxMaService) {
  this.wxMaService = wxMaService;
}