com.jfinal.weixin.sdk.api.ApiConfigKit Java Examples

The following examples show how to use com.jfinal.weixin.sdk.api.ApiConfigKit. 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: WechatApiConfigInterceptor.java    From jboot with Apache License 2.0 6 votes vote down vote up
@Override
public void intercept(Invocation inv) {
    try {
        JbootWechatController controller = (JbootWechatController) inv.getController();
        ApiConfig config = controller.getApiConfig();

        if (config == null) {
            inv.getController().renderText("error : cannot get apiconfig,please config jboot.properties");
            return;
        }

        ApiConfigKit.setThreadLocalAppId(config.getAppId());
        inv.invoke();
    } finally {
        ApiConfigKit.removeThreadLocalAppId();
    }
}
 
Example #2
Source File: MsgController.java    From jfinal-weixin with Apache License 2.0 6 votes vote down vote up
/**
 * 在接收到微信服务器的 InMsg 消息后后响应 OutMsg 消息
 */
public void render(OutMsg outMsg) {
    String outMsgXml = OutMsgXmlBuilder.build(outMsg);
    // 开发模式向控制台输出即将发送的 OutMsg 消息的 xml 内容
    if (ApiConfigKit.isDevMode()) {
        System.out.println("发送消息:");
        System.out.println(outMsgXml);
        System.out.println("--------------------------------------------------------------------------------\n");
    }

    // 是否需要加密消息
    if (ApiConfigKit.getApiConfig().isEncryptMessage()) {
        outMsgXml = MsgEncryptKit.encrypt(outMsgXml, getPara("timestamp"), getPara("nonce"));
    }

    renderText(outMsgXml, "text/xml");
}
 
Example #3
Source File: JfinalConfigListener.java    From jboot-admin with Apache License 2.0 5 votes vote down vote up
@Override
public void onJFinalStarted() {
    JbootWechatConfig wechatConfig = Jboot.config(JbootWechatConfig.class);
    ApiConfig apiConfig = new ApiConfig();
    apiConfig.setAppId(wechatConfig.getAppId());
    apiConfig.setAppSecret(wechatConfig.getAppSecret());
    apiConfig.setToken(wechatConfig.getToken());
    ApiConfigKit.putApiConfig(apiConfig);
}
 
Example #4
Source File: OptionInitializer.java    From jpress with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 设置微信的相关配置
 */
private void initWechatOption() {

    String appId = JPressOptions.get(JPressConsts.OPTION_WECHAT_APPID);
    String appSecret = JPressOptions.get(JPressConsts.OPTION_WECHAT_APPSECRET);
    String token = JPressOptions.get(JPressConsts.OPTION_WECHAT_TOKEN);

    if (StrUtil.areNotEmpty(appId, appSecret, token)) {
        // 配置微信 API 相关参数
        ApiConfig ac = new ApiConfig();
        ac.setAppId(appId);
        ac.setAppSecret(appSecret);
        ac.setToken(token);
        ac.setEncryptMessage(false); //采用明文模式,同时也支持混合模式

        //重新设置后,需要清空之前的配置。
        try {
            Field mapField =  ApiConfigKit.class.getDeclaredField("CFG_MAP");
            mapField.setAccessible(true);
            Map map = (Map) mapField.get(null);
            map.clear();
        } catch (Exception e) {}

        ApiConfigKit.putApiConfig(ac);
    }

    WechatInterceptor.init();

}
 
Example #5
Source File: WechatMiniProgramApiController.java    From jpress with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 1、小程序端调用 wx.login() 之后,会得到code ,
 * 详情:https://developers.weixin.qq.com/miniprogram/dev/api/open-api/login/wx.login.html
 * <p>
 * 2、小程序端得到code之后,需调用此接口那code来换session_key,同时服务器存储session_key
 * 3、为什么要存储session_key呢?目的是为了获取用户信息
 * 4、小程序调用 wx.login() 之后,接下来会调用 wx.getUserInfo() ,
 * 此时要注意:wx.getUserInfo()得到的信息是加密的,需要解密才能获取文本信息
 * <p>
 * 5、解密就用到刚才的 session_key 了,session_key 其实就是解密的钥匙 (密钥)
 */
public void code2session() {

    String code = getPara("code");
    if (StrUtil.isBlank(code)) {
        renderFailJson(105, "code is blank");
        return;
    }


    // 获取SessionKey 和 openId
    // 返回{"session_key":"nzoqhc3OnwHzeTxJs+inbQ==","expires_in":2592000,"openid":"oVBkZ0aYgDMDIywRdgPW8-joxXc4"}
    ApiResult apiResult = wxaUserApi.getSessionKey(code);
    if (!apiResult.isSucceed()) {
        renderFailJson(apiResult.getErrorCode(), apiResult.getErrorMsg());
        return;
    }


    String sessionKey = apiResult.getStr("session_key");
    String sessionId = StrUtil.uuid();

    //把sessionKey存储起来,接下来用户解密要用到这个sessionKey
    IAccessTokenCache accessTokenCache = ApiConfigKit.getAccessTokenCache();
    accessTokenCache.set("wxa:session:" + sessionId, sessionKey);


    //把sessionId传给客户端,客户端解密数据的时候,必须把这个sessionId传入进来,才能获取sessionKey
    renderJson(Ret.ok().set("sessionId", sessionId));

}
 
Example #6
Source File: WeixinConfig.java    From jfinal-weixin with Apache License 2.0 5 votes vote down vote up
public void configConstant(Constants me) {
	loadProp("a_little_config_pro.txt", "a_little_config.txt");
	me.setDevMode(PropKit.getBoolean("devMode", false));
	
	// ApiConfigKit 设为开发模式可以在开发阶段输出请求交互的 xml 与 json 数据
	ApiConfigKit.setDevMode(me.getDevMode());
}
 
Example #7
Source File: MsgEncryptKit.java    From jfinal-weixin with Apache License 2.0 5 votes vote down vote up
public static String encrypt(String msg, String timestamp, String nonce) {
	try {
		ApiConfig ac = ApiConfigKit.getApiConfig();
		WXBizMsgCrypt pc = new WXBizMsgCrypt(ac.getToken(), ac.getEncodingAesKey(), ac.getAppId());
		return pc.encryptMsg(msg, timestamp, nonce);
	}
	catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example #8
Source File: MsgEncryptKit.java    From jfinal-weixin with Apache License 2.0 5 votes vote down vote up
public static String decrypt(String encryptedMsg, String timestamp, String nonce, String msgSignature) {
	try {
		ApiConfig ac = ApiConfigKit.getApiConfig();
		
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = dbf.newDocumentBuilder();
		StringReader sr = new StringReader(encryptedMsg);
		InputSource is = new InputSource(sr);
		Document document = db.parse(is);
		
		Element root = document.getDocumentElement();
		NodeList nodelist1 = root.getElementsByTagName("Encrypt");
		// NodeList nodelist2 = root.getElementsByTagName("MsgSignature");
		
		String encrypt = nodelist1.item(0).getTextContent();
		// String msgSignature = nodelist2.item(0).getTextContent();
		
		String fromXML = String.format(format, encrypt);
		
		String encodingAesKey = ac.getEncodingAesKey();
		if (encodingAesKey == null)
			throw new IllegalStateException("encodingAesKey can not be null, config encodingAesKey first.");
		
		WXBizMsgCrypt pc = new WXBizMsgCrypt(ac.getToken(), encodingAesKey, ac.getAppId());
		return pc.decryptMsg(msgSignature, timestamp, nonce, fromXML);	// 此处 timestamp 如果与加密前的不同则报签名不正确的异常
	}
	catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example #9
Source File: ApiInterceptor.java    From jfinal-weixin with Apache License 2.0 5 votes vote down vote up
public void intercept(Invocation inv) {
	Controller controller = inv.getController();
	if (controller instanceof ApiController == false)
		throw new RuntimeException("控制器需要继承 ApiController");
	
	try {
		ApiConfigKit.setThreadLocalApiConfig(((ApiController)controller).getApiConfig());
		inv.invoke();
	}
	finally {
		ApiConfigKit.removeThreadLocalApiConfig();
	}
}
 
Example #10
Source File: MsgController.java    From jfinal-weixin with Apache License 2.0 5 votes vote down vote up
@Before(NotAction.class)
public String getInMsgXml() {
    if (inMsgXml == null) {
        inMsgXml = HttpKit.readIncommingRequestData(getRequest());

        // 是否需要解密消息
        if (ApiConfigKit.getApiConfig().isEncryptMessage()) {
            inMsgXml = MsgEncryptKit.decrypt(inMsgXml, getPara("timestamp"), getPara("nonce"), getPara("msg_signature"));
        }
    }
    return inMsgXml;
}
 
Example #11
Source File: MsgInterceptor.java    From jfinal-weixin with Apache License 2.0 5 votes vote down vote up
public void intercept(Invocation inv) {
	Controller controller = inv.getController();
	if (controller instanceof MsgController == false)
		throw new RuntimeException("控制器需要继承 MsgController");
	
	try {
		// 将 ApiConfig 对象与当前线程绑定,以便在后续操作中方便获取该对象: ApiConfigKit.getApiConfig();
		ApiConfigKit.setThreadLocalApiConfig(((MsgController)controller).getApiConfig());
		
		// 如果是服务器配置请求,则配置服务器并返回
		if (isConfigServerRequest(controller)) {
			configServer(controller);
			return ;
		}
		
		// 对开发测试更加友好
		if (ApiConfigKit.isDevMode()) {
			inv.invoke();
		} else {
			// 如果是服务器配置请求,则配置服务器并返回
			if (isConfigServerRequest(controller)) {
				configServer(controller);
				return ;
			}
			
			// 签名检测
			if (checkSignature(controller)) {
				inv.invoke();
			}
			else {
				controller.renderText("签名验证失败,请确定是微信服务器在发送消息过来");
			}
		}

	}
	finally {
		ApiConfigKit.removeThreadLocalApiConfig();
	}
}
 
Example #12
Source File: JbootWechatController.java    From jboot with Apache License 2.0 4 votes vote down vote up
public ApiConfig getApiConfig() {
    return ApiConfigKit.getApiConfig();
}
 
Example #13
Source File: WechatMiniProgramApiController.java    From jpress with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * 小程序端调用 wx.getUserInfo() 后,得到的是加密的用户数据
 * 需要调用此接口,才能获取到具体的数据
 * 解密用户数据,小程序的相关接口 https://developers.weixin.qq.com/miniprogram/dev/api/open-api/user-info/wx.getUserInfo.html
 */
public void decryptUserInfo() {


    String postData = getRawData();
    if (StrUtil.isBlank(postData)) {
        renderFailJson(107, "can not get data");
        return;
    }

    JSONObject json = JSON.parseObject(postData);

    //小程序端调用 /api/wechat/mp/code2session之后得到的sessionId
    String sessionId = json.getString("sessionId");

    IAccessTokenCache accessTokenCache = ApiConfigKit.getAccessTokenCache();
    String sessionKey = accessTokenCache.get("wxa:session:" + sessionId);
    if (StrUtil.isBlank(sessionKey)) {
        renderFailJson(107, "session id is error.");
        return;
    }


    //不包括敏感信息的原始数据字符串,用于计算签名
    String rawData = json.getString("rawData");

    //签名:使用 sha1( rawData + sessionkey ) 得到字符串,用于校验用户信息
    String signature = json.getString("signature");

    //包括敏感数据在内的完整用户信息的加密数据
    //具体加密方法在:https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/signature.html#%E5%8A%A0%E5%AF%86%E6%95%B0%E6%8D%AE%E8%A7%A3%E5%AF%86%E7%AE%97%E6%B3%95
    String encryptedData = json.getString("encryptedData");

    //加密算法的初始向量
    String iv = json.getString("iv");


    // 用户信息校验
    boolean check = wxaUserApi.checkUserInfo(sessionKey, rawData, signature);
    if (check == false) {
        renderFailJson(500, "userInfo check fail");
        return;
    }

    // 服务端解密用户信息,得到原始的用户信息
    ApiResult apiResult = wxaUserApi.getUserInfo(sessionKey, encryptedData, iv);
    if (!apiResult.isSucceed()) {
        renderFailJson(apiResult.getErrorCode(), apiResult.getErrorMsg());
        return;
    }

    Long userId = doGetOrCreateUser(apiResult);
    if (userId == null) {
        //这种情况非常严重,一般情况下只有链接不上数据库了
        //或者是在 RPC 下,无法调用到 provider 了
        renderFailJson(501, "can not query user or save user to database");
        return;
    }


    setJwtAttr(JPressConsts.JWT_USERID, userId);

    //设置 jwt Token 给客户端
    //以后客户端通过此token定位用户信息
    renderJson(Ret.ok().set("token", createJwtToken()));
}
 
Example #14
Source File: MsgController.java    From jfinal-weixin with Apache License 2.0 4 votes vote down vote up
/**
 * weixin 公众号服务器调用唯一入口,即在开发者中心输入的 URL 必须要指向此 action
 */
@Before(MsgInterceptor.class)
public void index() {
    // 开发模式输出微信服务发送过来的  xml 消息
    if (ApiConfigKit.isDevMode()) {
        System.out.println("接收消息:");
        System.out.println(getInMsgXml());
    }

    // 解析消息并根据消息类型分发到相应的处理方法
    InMsg msg = getInMsg();
    if (msg instanceof InTextMsg)
        processInTextMsg((InTextMsg) msg);
    else if (msg instanceof InImageMsg)
        processInImageMsg((InImageMsg) msg);
    else if (msg instanceof InVoiceMsg)
        processInVoiceMsg((InVoiceMsg) msg);
    else if (msg instanceof InVideoMsg)
        processInVideoMsg((InVideoMsg) msg);
    else if (msg instanceof InShortVideoMsg)   //支持小视频
        processInShortVideoMsg((InShortVideoMsg) msg);
    else if (msg instanceof InLocationMsg)
        processInLocationMsg((InLocationMsg) msg);
    else if (msg instanceof InLinkMsg)
        processInLinkMsg((InLinkMsg) msg);
    else if (msg instanceof InCustomEvent)
        processInCustomEvent((InCustomEvent) msg);
    else if (msg instanceof InFollowEvent)
        processInFollowEvent((InFollowEvent) msg);
    else if (msg instanceof InQrCodeEvent)
        processInQrCodeEvent((InQrCodeEvent) msg);
    else if (msg instanceof InLocationEvent)
        processInLocationEvent((InLocationEvent) msg);
    else if (msg instanceof InMassEvent)
        processInMassEvent((InMassEvent) msg);
    else if (msg instanceof InMenuEvent)
        processInMenuEvent((InMenuEvent) msg);
    else if (msg instanceof InSpeechRecognitionResults)
        processInSpeechRecognitionResults((InSpeechRecognitionResults) msg);
    else if (msg instanceof InTemplateMsgEvent)
        processInTemplateMsgEvent((InTemplateMsgEvent) msg);
    else if (msg instanceof InShakearoundUserShakeEvent)
        processInShakearoundUserShakeEvent((InShakearoundUserShakeEvent) msg);
    else
        logger.error("未能识别的消息类型。 消息 xml 内容为:\n" + getInMsgXml());
}
 
Example #15
Source File: SignatureCheckKit.java    From jfinal-weixin with Apache License 2.0 3 votes vote down vote up
/**
 * php 示例
 *  $signature = $_GET["signature"];
       $timestamp = $_GET["timestamp"];
       $nonce = $_GET["nonce"];	
       		
	$token = TOKEN;
	$tmpArr = array($token, $timestamp, $nonce);
	sort($tmpArr, SORT_STRING);
	$tmpStr = implode( $tmpArr );
	$tmpStr = sha1( $tmpStr );
	
	if( $tmpStr == $signature ){
		return true;
	}else{
		return false;
	}
 * @return
 */
public boolean checkSignature(String signature, String timestamp, String nonce) {
	String TOKEN = ApiConfigKit.getApiConfig().getToken();
	String array[] = {TOKEN, timestamp, nonce};
	Arrays.sort(array);
	String tempStr = new StringBuilder().append(array[0] + array[1] + array[2]).toString();
	tempStr = HashKit.sha1(tempStr);
	return tempStr.equalsIgnoreCase(signature);
}