com.aliyuncs.http.MethodType Java Examples

The following examples show how to use com.aliyuncs.http.MethodType. 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: SmsClient.java    From aliyun-sms with Apache License 2.0 8 votes vote down vote up
/**
 * 发送短信.
 *
 * @param smsTemplate 短信模板
 */
public void send(final SmsTemplate smsTemplate) {
    Objects.requireNonNull(smsTemplate);
    checkSmsTemplate(smsTemplate);

    final CommonRequest request = new CommonRequest();
    request.setSysMethod(MethodType.POST);
    request.setSysDomain("dysmsapi.aliyuncs.com");
    request.setSysVersion("2017-05-25");
    request.setSysAction("SendSms");
    request.putQueryParameter("PhoneNumbers", String.join(",", smsTemplate.getPhoneNumbers()));
    request.putQueryParameter("SignName", smsTemplate.getSignName());
    request.putQueryParameter("TemplateCode", smsTemplate.getTemplateCode());
    request.putQueryParameter("TemplateParam", Utils.toJsonStr(smsTemplate.getTemplateParam()));
    try {
        final CommonResponse response = this.acsClient.getCommonResponse(request);
        checkSmsResponse(response);
    }
    catch (final ClientException e) {
        throw new SmsException(e);
    }
}
 
Example #2
Source File: SmsService.java    From pybbs with GNU Affero General Public License v3.0 7 votes vote down vote up
public boolean sendSms(String mobile, String code) {
    try {
        if (StringUtils.isEmpty(mobile)) return false;
        // 获取连接
        if (this.instance() == null) return false;
        // 构建请求体
        CommonRequest request = new CommonRequest();
        //request.setProtocol(ProtocolType.HTTPS);
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", regionId);
        request.putQueryParameter("PhoneNumbers", mobile);
        request.putQueryParameter("SignName", signName);
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam", String.format("{\"code\": \"%s\"}", code));
        CommonResponse response = client.getCommonResponse(request);
        //{"Message":"OK","RequestId":"93E35E66-B2B2-4D7A-8AC9-2BDD97F5FB18","BizId":"689615750980282428^0","Code":"OK"}
        Map responseMap = JsonUtil.jsonToObject(response.getData(), Map.class);
        if (responseMap.get("Code").equals("OK")) return true;
    } catch (ClientException e) {
        log.error(e.getMessage());
    }
    return false;
}
 
Example #3
Source File: SmsClient.java    From aliyun-sms with Apache License 2.0 6 votes vote down vote up
/**
 * 批量发送短信.
 *
 * <p>
 * 批量发送短信接口,支持在一次请求中分别向多个不同的手机号码发送不同签名的短信。
 * 手机号码,签名,模板参数字段个数相同,一一对应,短信服务根据字段的顺序判断发往指定手机号码的签名。
 *
 * <p>
 * 如果您需要往多个手机号码中发送同样签名的短信,请使用 {@link #send(SmsTemplate)}。
 *
 * @param batchSmsTemplate 批量发送短信模板
 */
public void send(final BatchSmsTemplate batchSmsTemplate) {
    Objects.requireNonNull(batchSmsTemplate);
    checkBatchSmsTemplate(batchSmsTemplate);

    final CommonRequest request = new CommonRequest();
    request.setSysMethod(MethodType.POST);
    request.setSysDomain("dysmsapi.aliyuncs.com");
    request.setSysVersion("2017-05-25");
    request.setSysAction("SendBatchSms");
    request.putQueryParameter("PhoneNumberJson", this.gson.toJson(batchSmsTemplate.getPhoneNumbers()));
    request.putQueryParameter("SignNameJson", this.gson.toJson(batchSmsTemplate.getSignNames()));
    request.putQueryParameter("TemplateCode", batchSmsTemplate.getTemplateCode());
    request.putQueryParameter("TemplateParamJson", this.gson.toJson(batchSmsTemplate.getTemplateParams()));
    try {
        final CommonResponse response = this.acsClient.getCommonResponse(request);
        checkSmsResponse(response);
    }
    catch (final ClientException e) {
        throw new SmsException(e);
    }
}
 
Example #4
Source File: SmsService.java    From microservice-recruit with Apache License 2.0 6 votes vote down vote up
private boolean sendSms(String phoneNumber, String randomCode) {
    SendSmsRequest request = new SendSmsRequest();
    request.setMethod(MethodType.POST);
    request.setPhoneNumbers(phoneNumber);
    request.setSignName("leader直聘");
    request.setTemplateCode("SMS_130924380");
    request.setTemplateParam("{\"code\":\"" + randomCode + "\"}");
    try {
        SendSmsResponse sendSmsResponse = getAcsClient().getAcsResponse(request);
        if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals(Constant.OK)) {
            log.info("发送短信成功");
            return true;
        }
        log.error(sendSmsResponse.getCode());
    } catch (ClientException e) {
        log.error("ClientException异常:" + e.getMessage());
        throw new MyException(ResultEnum.SEND_NOTE_ERROR);
    }
    log.error("发送短信失败");
    return false;
}
 
Example #5
Source File: AbstractAliSmsTemplate.java    From fast-family-master with Apache License 2.0 6 votes vote down vote up
@Override
public CommonRequest getAliSmsRequest(T t) {
    CommonRequest request = new CommonRequest();
    request.setAction("SendSms");
    request.setVersion("2017-05-25");
    request.setMethod(MethodType.POST);
    request.setDomain(aliSmsProperties.getDomain());
    request.setProduct(aliSmsProperties.getProduce());
    request.setEndpointType(aliSmsProperties.getEndPointName());
    request.putQueryParameter("PhoneNumbers", t.getMobile());
    request.putQueryParameter("TemplateCode", t.getTemplateCode());
    request.putQueryParameter("TemplateParam", JSONObject.toJSONString(t.getParams()));
    request.putQueryParameter("SignName", t.getSignName());
    request.putQueryParameter("OutId", t.getOutId());
    return request;
}
 
Example #6
Source File: AliSmsService.java    From faster-framework-project with Apache License 2.0 6 votes vote down vote up
@Override
public boolean send(SendSmsRequest request) {
    try {
        IAcsClient acsClient = new DefaultAcsClient(profile);
        request.setMethod(MethodType.POST);
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
        if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().
                equals("OK")) {
            return true;
        }
    } catch (ClientException e) {
        log.error(e.getMessage());
        return false;
    }
    return false;
}
 
Example #7
Source File: SmsHelper.java    From tools with MIT License 6 votes vote down vote up
/**
 * Query the record of sending the specified mobile phone number
 *
 * @param phone    Mobile phone number
 * @param sendDate Send date,Format for yyyy-MM-dd
 * @param page     Query page
 * @param row      No more than 50 pages per page
 * @return Query results
 */
public String findSendDetail(String phone, String sendDate, long page, long row) {
    if (row > 50) {
        throw new IllegalArgumentException("每页条数不能大于50");
    }
    CommonRequest request = new CommonRequest();
    request.setMethod(MethodType.POST);
    request.setDomain(DO_MAIN);
    request.setVersion(VERSION);
    request.setAction("QuerySendDetails");
    request.putQueryParameter("PhoneNumber", phone);
    request.putQueryParameter("SendDate", sendDate.replaceAll("-", ""));
    request.putQueryParameter("PageSize", String.valueOf(row));
    request.putQueryParameter("CurrentPage", String.valueOf(page));
    try {
        CommonResponse commonResponse = this.client.getCommonResponse(request);
        return commonResponse.getData();
    } catch (ClientException e) {
        throw new ToolsAliyunException(e.getMessage());
    }
}
 
Example #8
Source File: SmsHelper.java    From tools with MIT License 6 votes vote down vote up
/**
 * Send SMS
 *
 * @param phones       Mobile phone number, multiple with English commas separated, the maximum of 1000
 * @param templateCode SMS template code
 * @param signName     SMS sign name
 * @param param        The actual value of the SMS template variable
 * @return Send the receipt
 */
public String send(String phones, String templateCode, String signName, Map<String, ?> param) {
    CommonRequest request = new CommonRequest();
    request.setMethod(MethodType.POST);
    request.setDomain(DO_MAIN);
    request.setVersion(VERSION);
    request.setAction("sendSms");
    request.putQueryParameter("PhoneNumbers", phones);
    if (param != null) {
        request.putQueryParameter("TemplateParam", new Gson().toJson(param));
    }
    request.putQueryParameter("TemplateCode", templateCode);
    request.putQueryParameter("SignName", signName);
    try {
        CommonResponse response = this.client.getCommonResponse(request);
        return response.getData();
    } catch (ClientException e) {
        throw new ToolsAliyunException(e.getMessage());
    }
}
 
Example #9
Source File: PushUtil.java    From NutzSite with Apache License 2.0 6 votes vote down vote up
/**
 * 推送通知给iOS
 *
 * @param deviceIds
 * @param titale
 * @param body
 * @param parameters
 * @throws Exception
 */
public static void pushNoticeToIOS(String deviceIds, String titale, String body, Object parameters) throws Exception {
    PushNoticeToiOSRequest iOSRequest = new PushNoticeToiOSRequest();
    //安全性比较高的内容建议使用HTTPS
    iOSRequest.setProtocol(ProtocolType.HTTPS);
    //内容较大的请求,使用POST请求
    iOSRequest.setMethod(MethodType.POST);
    iOSRequest.setAppKey(BaseConfig.iosAppKey);
    // iOS的通知是通过APNS中心来发送的,需要填写对应的环境信息. DEV :表示开发环境, PRODUCT: 表示生产环境
    iOSRequest.setApnsEnv("DEV");
    iOSRequest.setTarget("DEVICE");
    iOSRequest.setTargetValue(deviceIds);
    iOSRequest.setTitle(titale);
    iOSRequest.setBody(body);
    iOSRequest.setExtParameters(JSON.toJSONString(parameters));
    PushNoticeToiOSResponse pushNoticeToiOSResponse = BaseConfig.client.getAcsResponse(iOSRequest);
    System.out.printf("RequestId: %s, MessageId: %s\n",
            pushNoticeToiOSResponse.getRequestId(), pushNoticeToiOSResponse.getMessageId());
}
 
Example #10
Source File: PushUtil.java    From NutzSite with Apache License 2.0 6 votes vote down vote up
/**
 * 推送消息给iOS
 *
 * @param deviceIds
 * @param titale
 * @param body
 * @throws Exception
 */
public static void pushMessageToIOS(String deviceIds, String titale, String body) throws Exception {
    PushMessageToiOSRequest iOSRequest = new PushMessageToiOSRequest();
    //安全性比较高的内容建议使用HTTPS
    iOSRequest.setProtocol(ProtocolType.HTTPS);
    //内容较大的请求,使用POST请求
    iOSRequest.setMethod(MethodType.POST);
    iOSRequest.setAppKey(BaseConfig.iosAppKey);
    iOSRequest.setTarget("DEVICE");
    iOSRequest.setTargetValue(deviceIds);
    iOSRequest.setTitle(titale);
    iOSRequest.setBody(body);
    PushMessageToiOSResponse pushMessageToiOSResponse = BaseConfig.client.getAcsResponse(iOSRequest);
    System.out.printf("RequestId: %s, MessageId: %s\n",
            pushMessageToiOSResponse.getRequestId(), pushMessageToiOSResponse.getMessageId());
}
 
Example #11
Source File: AliyunMsgMaker.java    From WePush with MIT License 6 votes vote down vote up
/**
 * 组织阿里云短信消息
 *
 * @param msgData 消息信息
 * @return SendSmsRequest
 */
@Override
public SendSmsRequest makeMsg(String[] msgData) {
    SendSmsRequest request = new SendSmsRequest();
    //使用post提交
    request.setSysMethod(MethodType.POST);
    //必填:短信签名-可在短信控制台中找到
    request.setSignName(App.config.getAliyunSign());

    // 模板参数
    Map<String, String> paramMap = new HashMap<>(10);
    VelocityContext velocityContext = getVelocityContext(msgData);

    for (TemplateData templateData : templateDataList) {
        paramMap.put(templateData.getName(), TemplateUtil.evaluate(templateData.getValue(), velocityContext));
    }

    request.setTemplateParam(JSONUtil.parseFromMap(paramMap).toJSONString(0));

    // 短信模板ID,传入的模板必须是在阿里阿里云短信中的可用模板。示例:SMS_585014
    request.setTemplateCode(templateId);

    return request;
}
 
Example #12
Source File: OSSUtil.java    From xnx3 with Apache License 2.0 6 votes vote down vote up
static AssumeRoleResponse assumeRole(String accessKeyId, String accessKeySecret,String roleArn, String roleSessionName, String policy,ProtocolType protocolType) throws ClientException {
	try {
		// 创建一个 Aliyun Acs Client, 用于发起 OpenAPI 请求
		IClientProfile profile = DefaultProfile.getProfile(region_cn_hangzhou, accessKeyId, accessKeySecret);
		DefaultAcsClient client = new DefaultAcsClient(profile);
		// 创建一个 AssumeRoleRequest 并设置请求参数
		final AssumeRoleRequest request = new AssumeRoleRequest();
		request.setVersion(sta_api_version);
		request.setMethod(MethodType.POST);
		request.setProtocol(protocolType);
		request.setRoleArn(roleArn);
		request.setRoleSessionName(roleSessionName);
		request.setPolicy(policy);
		// 发起请求,并得到response
		final AssumeRoleResponse response = client.getAcsResponse(request);
		return response;
	} catch (ClientException e) {
		throw e;
	}
}
 
Example #13
Source File: STSServiceImpl.java    From jframe with Apache License 2.0 6 votes vote down vote up
AssumeRoleResponse assumeRole(String id, String roleArn, String roleSessionName, String policy, ProtocolType protocolType)
        throws ServerException, com.aliyuncs.exceptions.ClientException {
    DefaultAcsClient client = clients.get(id);

    // 创建一个 AssumeRoleRequest 并设置请求参数
    final AssumeRoleRequest request = new AssumeRoleRequest();
    request.setVersion(_config.getConf(id, K_api_version));
    request.setMethod(MethodType.POST);
    request.setProtocol(protocolType);

    request.setRoleArn(roleArn);
    request.setRoleSessionName(roleSessionName);
    request.setPolicy(policy);

    request.setDurationSeconds(Long.parseLong(_config.getConf(id, K_durationSeconds, "3600"))); // 默认值为3600

    // 发起请求,并得到response
    final AssumeRoleResponse response = client.getAcsResponse(request);
    // client.shutdown();

    return response;
}
 
Example #14
Source File: SmsService.java    From microservice-recruit with Apache License 2.0 6 votes vote down vote up
private boolean sendSms(String phoneNumber, String randomCode) {
    SendSmsRequest request = new SendSmsRequest();
    request.setMethod(MethodType.POST);
    request.setPhoneNumbers(phoneNumber);
    request.setSignName("leader直聘");
    request.setTemplateCode("SMS_130924380");
    request.setTemplateParam("{\"code\":\"" + randomCode + "\"}");
    try {
        SendSmsResponse sendSmsResponse = getAcsClient().getAcsResponse(request);
        if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals(Constant.OK)) {
            log.info("发送短信成功");
            return true;
        }
        log.error(sendSmsResponse.getCode());
    } catch (ClientException e) {
        log.error("ClientException异常:" + e.getMessage());
        throw new MyException(ResultEnum.SEND_NOTE_ERROR);
    }
    log.error("发送短信失败");
    return false;
}
 
Example #15
Source File: StsServiceSample.java    From jframe with Apache License 2.0 6 votes vote down vote up
static AssumeRoleResponse assumeRole(String accessKeyId, String accessKeySecret, String roleArn, String roleSessionName, String policy,
                                     ProtocolType protocolType) throws ClientException {
    try {
        // 创建一个 Aliyun Acs Client, 用于发起 OpenAPI 请求
        IClientProfile profile = DefaultProfile.getProfile(REGION_CN_HANGZHOU, accessKeyId, accessKeySecret);
        DefaultAcsClient client = new DefaultAcsClient(profile);

        // 创建一个 AssumeRoleRequest 并设置请求参数
        final AssumeRoleRequest request = new AssumeRoleRequest();
        request.setVersion(STS_API_VERSION);
        request.setMethod(MethodType.POST);
        request.setProtocol(protocolType);

        request.setRoleArn(roleArn);
        request.setRoleSessionName(roleSessionName);
        request.setPolicy(policy);

        // 发起请求,并得到response
        final AssumeRoleResponse response = client.getAcsResponse(request);

        return response;
    } catch (ClientException e) {
        throw e;
    }
}
 
Example #16
Source File: NoticeService.java    From ticket with GNU General Public License v3.0 5 votes vote down vote up
public void send(NoticeModel noticeModel) {

        try {
            Gson gson = new Gson();
            Map<String, String> map = new HashMap<>();
            map.put("name", noticeModel.getName());
            map.put("username", noticeModel.getUserName());
            map.put("password", noticeModel.getPassword());
            map.put("orderId", noticeModel.getOrderId());

            DefaultProfile profile = DefaultProfile.getProfile("default", noticeConfig.getAccessKeyId(), noticeConfig.getAccessSecret());
            IAcsClient client = new DefaultAcsClient(profile);

            CommonRequest request = new CommonRequest();
            request.setProtocol(ProtocolType.HTTPS);
            request.setMethod(MethodType.GET);
            request.setDomain(apiConfig.getNotice());
            request.setVersion("2017-05-25");
            request.setAction("SendSms");
            request.putQueryParameter("PhoneNumbers", noticeModel.getPhoneNumber());
            request.putQueryParameter("SignName", noticeConfig.getSignName());
            request.putQueryParameter("TemplateCode", noticeConfig.getTemplateCode());
            request.putQueryParameter("TemplateParam", gson.toJson(map));
            CommonResponse response = client.getCommonResponse(request);
            map = gson.fromJson(response.getData(), Map.class);
            if (map.get("Code").equals("OK")) {
                log.debug("短信通知通知完成{}!", noticeModel.getPhoneNumber());
            } else {
                log.error("短信通知失败:" + map);
            }
        } catch (Exception e) {
            log.error("短信通知失败:" + noticeModel, e);
        }

    }
 
Example #17
Source File: SimaplePhoneRegist.java    From danyuan-application with Apache License 2.0 5 votes vote down vote up
public void SendPhoneToCustom(String phone, String templateParam) throws ClientException {
		// 设置超时时间-可自行调整
		System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
		System.setProperty("sun.net.client.defaultReadTimeout", "10000");
		// 初始化ascClient需要的几个参数
		final String product = "Dysmsapi";// 短信API产品名称(短信产品名固定,无需修改)
		final String domain = "dysmsapi.aliyuncs.com";// 短信API产品域名(接口地址固定,无需修改)
		// 替换成你的AK
		// 初始化ascClient,暂时不支持多region(请勿修改)
		IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", PHONE_ACCESSKEYID, PHONE_ACCESSKEYSECRET);
		DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
		IAcsClient acsClient = new DefaultAcsClient(profile);
		// 组装请求对象
		SendSmsRequest request = new SendSmsRequest();
		// 使用post提交
		request.setMethod(MethodType.POST);
		// 必填:待发送手机号。支持以逗号分隔的形式进行批量调用,批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式;发送国际/港澳台消息时,接收号码格式为国际区号+号码,如“85200000000”
		request.setPhoneNumbers(phone);
		// 必填:短信签名-可在短信控制台中找到
		request.setSignName(PHONE_SIGNNAME);
		// 必填:短信模板-可在短信控制台中找到,发送国际/港澳台消息时,请使用国际/港澳台短信模版
		request.setTemplateCode(PHONE_TEMPLATECODE);
		// 可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
		// 友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
		request.setTemplateParam(templateParam);
		// 可选-上行短信扩展码(扩展码字段控制在7位或以下,无特殊需求用户请忽略此字段)
		// request.setSmsUpExtendCode("90997");
		// 可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
//		request.setOutId("yourOutId");
		// 请求失败这里会抛ClientException异常
		SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
		if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
			// 请求成功
		}
	}
 
Example #18
Source File: FunctionComputeClientTest.java    From fc-java-sdk with MIT License 5 votes vote down vote up
private Credentials getAssumeRoleCredentials(String policy)
    throws com.aliyuncs.exceptions.ClientException {
    IClientProfile profile = DefaultProfile
        .getProfile(REGION, ACCESS_KEY, SECRET_KEY);
    //DefaultProfile.addEndpoint("sts.us-west-1.aliyuncs.com", "us-west-1", "Sts", "sts.us-west-1.aliyuncs.com");
    DefaultAcsClient client = new DefaultAcsClient(profile);

    AssumeRoleRequest request = new AssumeRoleRequest();
    request.setVersion(STS_API_VERSION);
    request.setMethod(MethodType.POST);
    request.setProtocol(ProtocolType.HTTPS);
    request.setRoleArn(STS_ROLE);
    request.setRoleSessionName("test-session");
    if (policy != null) {
        request.setPolicy(policy);
    }

    AssumeRoleResponse stsResponse;
    try {
        stsResponse = client.getAcsResponse(request);
    } catch (com.aliyuncs.exceptions.ClientException e) {
        throw new RuntimeException(e);
    }

    String accessKey = stsResponse.getCredentials().getAccessKeyId();
    String secretKey = stsResponse.getCredentials().getAccessKeySecret();
    String stsToken = stsResponse.getCredentials().getSecurityToken();

    assertNotNull(accessKey);
    assertNotNull(secretKey);
    assertNotNull(stsToken);

    return stsResponse.getCredentials();
}
 
Example #19
Source File: AliyunSmsMessageNotifier.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
@Override
public void send(GenericNotifyMessage msg) {
	try {
		isTrue(msg.getToObjects().size() < 1000, "Group numbers exceeds the limit (<1000)");

		SendSmsRequest req = new SendSmsRequest();
		req.setSysMethod(MethodType.POST);
		// 必填:待发送手机号。支持以逗号分隔的形式进行批量调用,批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
		req.setPhoneNumbers(StringUtils.join(msg.getToObjects(), ','));
		// 必填:短信签名-可在短信控制台中找到
		req.setSignName(config.getAliyun().getSignName());
		// 必填:短信模板-可在短信控制台中找到
		req.setTemplateCode(config.getAliyun().getTemplates().getProperty(msg.getTemplateKey()));
		// 可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
		// 友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
		req.setTemplateParam(toJSONString(msg.getParameters()));
		// 可选-上行短信扩展码(扩展码字段控制在7位或以下,无特殊需求用户请忽略此字段)
		// request.setSmsUpExtendCode("90997");
		// 可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
		req.setOutId(msg.getCallbackId());
		// 请求失败这里会抛ClientException异常
		SendSmsResponse resp = acsClient.getAcsResponse(req);
		if (!isNull(resp) && "OK".equalsIgnoreCase(resp.getCode())) {
			if (log.isDebugEnabled())
				log.debug("Successed response: {}, request: {}", toJSONString(resp), toJSONString(req));
			else
				log.info("Successed message: {}, numbers: {}", resp.getMessage(), msg.getToObjects());
		} else
			log.warn("Failed response: {}, request: {}", toJSONString(resp), toJSONString(req));
	} catch (Exception e) {
		throw new NotificationException(kind(), e.getMessage(), e);
	}

}
 
Example #20
Source File: SmsOtpAuthnAliyun.java    From MaxKey with Apache License 2.0 5 votes vote down vote up
@Override
public boolean produce(UserInfo userInfo) {
    // 手机号
    String mobile = userInfo.getMobile();
    if (mobile != null && !mobile.equals("")) {
        try {
            DefaultProfile profile = DefaultProfile.getProfile(
                                "cn-hangzhou", accessKeyId, accessSecret);
            IAcsClient client = new DefaultAcsClient(profile);

            String token = this.genToken(userInfo);
            CommonRequest request = new CommonRequest();
            request.setSysMethod(MethodType.POST);
            request.setSysDomain("dysmsapi.aliyuncs.com");
            request.setSysVersion("2017-05-25");
            request.setSysAction("SendSms");
            request.putQueryParameter("RegionId", "cn-hangzhou");
            request.putQueryParameter("PhoneNumbers", mobile);
            request.putQueryParameter("SignName", signName);
            request.putQueryParameter("TemplateCode", templateCode);
            request.putQueryParameter("TemplateParam", "{\"code\":\"" + token + "\"}");
            CommonResponse response = client.getCommonResponse(request);
            logger.debug("responseString " + response.getData());
            //成功返回
            if (response.getData().indexOf("OK") > -1) {
                this.optTokenStore.store(
                        userInfo, 
                        token, 
                        userInfo.getMobile(), 
                        OptTypes.SMS);
                return true;
            }
        } catch  (Exception e) {
            logger.error(" produce code error ", e);
        } 
    }
    return false;
}
 
Example #21
Source File: AliyunUtil.java    From roncoo-education with MIT License 5 votes vote down vote up
public static boolean sendMsg(String phone, String code, Aliyun aliyun) throws ClientException {
	System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
	System.setProperty("sun.net.client.defaultReadTimeout", "10000");
	// 初始化ascClient需要的几个参数
	// 初始化ascClient,暂时不支持多region(请勿修改)
	IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", aliyun.getAliyunAccessKeyId(), aliyun.getAliyunAccessKeySecret());
	DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", "Dysmsapi", "dysmsapi.aliyuncs.com");
	IAcsClient acsClient = new DefaultAcsClient(profile);
	// 组装请求对象
	SendSmsRequest request = new SendSmsRequest();
	// 使用post提交
	request.setMethod(MethodType.POST);
	// 必填:待发送手机号。支持以逗号分隔的形式进行批量调用,批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
	request.setPhoneNumbers(phone);
	// 必填:短信签名-可在短信控制台中找到
	request.setSignName(aliyun.getSignName());
	// 必填:短信模板-可在短信控制台中找到
	request.setTemplateCode(aliyun.getSmsCode());
	// 可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
	// 友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
	request.setTemplateParam("{\"code\":\"{code}\",\"product\":\"领课开源\"}".replace("{code}", code));
	// 可选-上行短信扩展码(扩展码字段控制在7位或以下,无特殊需求用户请忽略此字段)
	// request.setSmsUpExtendCode("90997");
	// 可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
	// request.setOutId("yourOutId");
	// 请求失败这里会抛ClientException异常
	SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
	if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
		// 请求成功
		log.debug(sendSmsResponse.getCode());
		return true;
	} else {
		log.error("发送失败,code={},message={}", sendSmsResponse.getCode(), sendSmsResponse.getMessage());
		return false;
	}
}
 
Example #22
Source File: PushUtil.java    From NutzSite with Apache License 2.0 5 votes vote down vote up
/**
 * 推送通知给android
 *
 * @param deviceIds
 * @param titale
 * @param body
 * @param parameters json数据
 * @throws Exception
 */
public static void pushNoticeToAndroid(String deviceIds, String titale, String body, Object parameters) throws Exception {
    PushRequest pushRequest = new PushRequest();
    //安全性比较高的内容建议使用HTTPS
    pushRequest.setProtocol(ProtocolType.HTTPS);
    //内容较大的请求,使用POST请求
    pushRequest.setMethod(MethodType.POST);
    // 推送目标
    pushRequest.setAppKey(BaseConfig.androidAppKey);
    pushRequest.setTarget("DEVICE");
    //推送目标: DEVICE:按设备推送 ALIAS : 按别名推送 ACCOUNT:按帐号推送  TAG:按标签推送; ALL: 广播推送
    pushRequest.setTargetValue(deviceIds);
    //根据Target来设定,如Target=DEVICE, 则对应的值为 设备id1,设备id2. 多个值使用逗号分隔.(帐号与设备有一次最多100个的限制)
    pushRequest.setAndroidExtParameters(JSON.toJSONString(parameters));
    pushRequest.setPushType("NOTICE");
    // 消息类型 MESSAGE NOTICE
    pushRequest.setDeviceType("ANDROID");
    // 设备类型 ANDROID iOS ALL.

    // 推送配置
    pushRequest.setTitle(titale); // 消息的标题
    pushRequest.setBody(body); // 消息的内容
    pushRequest.setAndroidNotificationChannel("1");
    // 推送配置: Android
    pushRequest.setAndroidNotifyType("NONE");
    //通知的提醒方式 "VIBRATE" : 震动 "SOUND" : 声音 "BOTH" : 声音和震动 NONE : 静音

    pushRequest.setAndroidRemind(true);

    String expireTime = ParameterHelper.getISO8601Time(new Date(System.currentTimeMillis() + 72 * 3600 * 1000));
    // 12小时后消息失效, 不会再发送
    pushRequest.setExpireTime(expireTime);
    pushRequest.setStoreOffline(true);
    // 离线消息是否保存,若保存, 在推送时候,用户即使不在线,下一次上线则会收到

    PushResponse pushResponse = BaseConfig.client.getAcsResponse(pushRequest);
    System.out.printf("RequestId: %s, MessageID: %s\n",
            pushResponse.getRequestId(), pushResponse.getMessageId());
}
 
Example #23
Source File: PushUtil.java    From NutzSite with Apache License 2.0 5 votes vote down vote up
/**
 * 推送消息给android
 *
 * @param deviceIds
 * @param titale
 * @param body
 * @throws Exception
 */
public static void pushMessageToAndroid(String deviceIds, String titale, String body) throws Exception {

    PushMessageToAndroidRequest androidRequest = new PushMessageToAndroidRequest();
    /**
     * 安全性比较高的内容建议使用HTTPS
     */
    androidRequest.setProtocol(ProtocolType.HTTPS);
    /**
     * 内容较大的请求,使用POST请求
     */
    androidRequest.setMethod(MethodType.POST);
    androidRequest.setAppKey(BaseConfig.androidAppKey);
    /**
     * 推送目标: DEVICE:按设备推送 ALIAS : 按别名推送 ACCOUNT:按帐号推送  TAG:按标签推送; ALL: 广播推送
     */
    androidRequest.setTarget("DEVICE");
    /**
     * 根据Target来设定,如Target=DEVICE, 则对应的值为 设备id1,设备id2. 多个值使用逗号分隔.(帐号与设备有一次最多100个的限制)
     */
    androidRequest.setTargetValue(deviceIds);
    androidRequest.setTitle(titale);
    androidRequest.setBody(body);
    PushMessageToAndroidResponse pushMessageToAndroidResponse = BaseConfig.client.getAcsResponse(androidRequest);
    System.out.printf("RequestId: %s, MessageId: %s\n",
            pushMessageToAndroidResponse.getRequestId(), pushMessageToAndroidResponse.getMessageId());

}
 
Example #24
Source File: AliyunSmsSenderImpl.java    From open-cloud with MIT License 5 votes vote down vote up
@Override
public Boolean send(SmsMessage parameter) {
    boolean result = false;
    try {
        // 地域ID
        DefaultProfile profile = DefaultProfile.getProfile(
                "cn-hangzhou",
                accessKeyId,
                accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", parameter.getPhoneNum());
        request.putQueryParameter("SignName", parameter.getSignName());
        request.putQueryParameter("TemplateCode", parameter.getTplCode());
        request.putQueryParameter("TemplateParam", parameter.getTplParams());
        CommonResponse response = client.getCommonResponse(request);
        System.out.println(response.toString());
        JSONObject json = JSONObject.parseObject(response.getData());
        result = OK.equalsIgnoreCase(json.getString(CODE));
        log.info("result:{}", response.getData());
    } catch (Exception e) {
        log.error("发送短信失败:{}", e.getMessage(), e);
    }
    return result;
}
 
Example #25
Source File: SmsService.java    From spring-microservice-exam with MIT License 5 votes vote down vote up
/**
 * 发送短信
 *
 * @param smsDto smsDto
 * @return SmsResponse
 * @author tangyi
 * @date 2019/06/22 13:28
 */
public SmsResponse sendSms(SmsDto smsDto) {
    DefaultProfile profile = DefaultProfile.getProfile(smsProperties.getRegionId(), smsProperties.getAppKey(), smsProperties.getAppSecret());
    IAcsClient client = new DefaultAcsClient(profile);
    CommonRequest request = new CommonRequest();
    request.setMethod(MethodType.POST);
    request.setDomain(smsProperties.getDomain());
    request.putQueryParameter("RegionId", smsProperties.getRegionId());
    request.putQueryParameter("PhoneNumbers", smsDto.getReceiver());
    request.putQueryParameter("SignName", smsProperties.getSignName());
    request.putQueryParameter("TemplateCode", smsProperties.getTemplateCode());
    request.putQueryParameter("TemplateParam", smsDto.getContent());
    request.setVersion(smsProperties.getVersion());
    request.setAction(smsProperties.getAction());
    try {
        CommonResponse response = client.getCommonResponse(request);
        log.info("response: {}", response.getData());
        if (response.getHttpStatus() != 200)
            throw new CommonException(response.getData());
        SmsResponse smsResponse = JsonMapper.getInstance().fromJson(response.getData(), SmsResponse.class);
        if (smsResponse == null)
            throw new CommonException("Parse response error");
        if (!"OK".equals(smsResponse.getCode()))
            throw new CommonException(smsResponse.getMessage());
        return smsResponse;
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new CommonException("Send message failed: " + e.getMessage());
    }
}
 
Example #26
Source File: AliyunVoiceNotifier.java    From jetlinks-community with Apache License 2.0 5 votes vote down vote up
@Override
@Nonnull
public Mono<Void> send(@Nonnull AliyunVoiceTemplate template, @Nonnull Values context) {

    return Mono.<Void>defer(() -> {
        try {
            CommonRequest request = new CommonRequest();
            request.setMethod(MethodType.POST);
            request.setDomain(domain);
            request.setVersion("2017-05-25");
            request.setAction("SingleCallByTts");
            request.setConnectTimeout(connectTimeout);
            request.setReadTimeout(readTimeout);
            request.putQueryParameter("RegionId", regionId);
            request.putQueryParameter("CalledShowNumber", template.getCalledShowNumbers());
            request.putQueryParameter("CalledNumber", template.getCalledNumber());
            request.putQueryParameter("TtsCode", template.getTtsCode());
            request.putQueryParameter("PlayTimes", String.valueOf(template.getPlayTimes()));
            request.putQueryParameter("TtsParam", template.createTtsParam(context.getAllValues()));

            CommonResponse response = client.getCommonResponse(request);

            log.info("发起语音通知完成 {}:{}", response.getHttpResponse().getStatus(), response.getData());

            JSONObject json = JSON.parseObject(response.getData());
            if (!"ok".equalsIgnoreCase(json.getString("Code"))) {
                return Mono.error(new BusinessException(json.getString("Message"), json.getString("Code")));
            }
        } catch (Exception e) {
            return Mono.error(e);
        }
        return Mono.empty();
    }).doOnEach(ReactiveLogger.onError(err -> {
        log.info("发起语音通知失败", err);
    }));
}
 
Example #27
Source File: SmsServiceImpl.java    From cloud-service with MIT License 5 votes vote down vote up
/**
 * 异步发送阿里云短信
 *
 * @param sms
 * @return
 */
@Async
@Override
public SendSmsResponse sendSmsMsg(Sms sms) {
	if (sms.getSignName() == null) {
		sms.setSignName(this.signName);
	}

	if (sms.getTemplateCode() == null) {
		sms.setTemplateCode(this.templateCode);
	}

	// 阿里云短信官网demo代码
	SendSmsRequest request = new SendSmsRequest();
	request.setMethod(MethodType.POST);
	request.setPhoneNumbers(sms.getPhone());
	request.setSignName(sms.getSignName());
	request.setTemplateCode(sms.getTemplateCode());
	request.setTemplateParam(sms.getParams());
	request.setOutId(sms.getId().toString());

	SendSmsResponse response = null;
	try {
		response = acsClient.getAcsResponse(request);
		if (response != null) {
			log.info("发送短信结果:code:{},message:{},requestId:{},bizId:{}", response.getCode(), response.getMessage(),
					response.getRequestId(), response.getBizId());

			sms.setCode(response.getCode());
			sms.setMessage(response.getMessage());
			sms.setBizId(response.getBizId());
		}
	} catch (ClientException e) {
		e.printStackTrace();
	}

	update(sms);

	return response;
}
 
Example #28
Source File: SmsUtils.java    From leyou with Apache License 2.0 5 votes vote down vote up
public SendSmsResponse sendSms(String phone, String code, String signName, String template) throws ClientException {

        // 可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        // 初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou",
                prop.getAccessKeyId(), prop.getAccessKeySecret());
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);

        // 组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();
        request.setMethod(MethodType.POST);
        // 必填:待发送手机号
        request.setPhoneNumbers(phone);
        // 必填:短信签名-可在短信控制台中找到
        request.setSignName(signName);
        // 必填:短信模板-可在短信控制台中找到
        request.setTemplateCode(template);
        // 可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
        request.setTemplateParam("{\"code\":\"" + code + "\"}");

        // 选填-上行短信扩展码(无特殊需求用户请忽略此字段)
        //request.setSmsUpExtendCode("90997");

        // 可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
        request.setOutId("123456");

        // hint 此处可能会抛出异常,注意catch
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);

        logger.info("发送短信状态:{}", sendSmsResponse.getCode());
        logger.info("发送短信消息:{}", sendSmsResponse.getMessage());

        return sendSmsResponse;
    }
 
Example #29
Source File: SmsServiceImpl.java    From open-capacity-platform with Apache License 2.0 5 votes vote down vote up
@Override
	public SendSmsResponse sendSmsMsg(Sms sms) {
		if (sms.getSignName() == null) {
			sms.setSignName(this.signName);
		}

		if (sms.getTemplateCode() == null) {
			sms.setTemplateCode(this.templateCode);
		}

		// 阿里云短信官网demo代码
		SendSmsRequest request = new SendSmsRequest();
		request.setMethod(MethodType.POST);
		request.setPhoneNumbers(sms.getPhone());
		request.setSignName(sms.getSignName());
		request.setTemplateCode(sms.getTemplateCode());
		request.setTemplateParam(sms.getParams());
		request.setOutId(sms.getId().toString());

		SendSmsResponse response = null;
//		测试时不需要开此 add by someday begin
//		try {
//			response = acsClient.getAcsResponse(request);
//			if (response != null) {
//				log.info("发送短信结果:code:{},message:{},requestId:{},bizId:{}", response.getCode(), response.getMessage(),
//						response.getRequestId(), response.getBizId());
//
//				sms.setCode(response.getCode());
//				sms.setMessage(response.getMessage());
//				sms.setBizId(response.getBizId());
//			}
//		} catch (ClientException e) {
//			e.printStackTrace();
//		}
//		测试时不需要开此 add by someday end
		update(sms);

		return response;
	}
 
Example #30
Source File: DySmsHelper.java    From jeewx-boot with Apache License 2.0 5 votes vote down vote up
/**
 * 发短信接口(固定:登录验证码模板)
 * @param phone
 * @param json
 * @return
 * @throws ClientException
 */
public static boolean sendSms(String phone,JSONObject json) throws ClientException {

    //可自助调整超时时间
    System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
    System.setProperty("sun.net.client.defaultReadTimeout", "10000");

    //初始化acsClient,暂不支持region化
    IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
    DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
    IAcsClient acsClient = new DefaultAcsClient(profile);

    //组装请求对象-具体描述见控制台-文档部分内容
    SendSmsRequest request = new SendSmsRequest();
    //必填:待发送手机号
    request.setPhoneNumbers(phone);
    //必填:短信签名-可在短信控制台中找到
    request.setSignName(msgSignName);
    //必填:短信模板-可在短信控制台中找到
    request.setTemplateCode(templateCode);
    //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
    request.setTemplateParam(json.toString());
    request.setMethod(MethodType.POST);
    //选填-上行短信扩展码(无特殊需求用户请忽略此字段)
    //request.setSmsUpExtendCode("90997");

    //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
    //request.setOutId("yourOutId");

    boolean result = false;

    //hint 此处可能会抛出异常,注意catch
    SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
    logger.info("短信接口返回的数据----------------");
    logger.info("{Code:" + sendSmsResponse.getCode()+",Message:" + sendSmsResponse.getMessage()+",RequestId:"+ sendSmsResponse.getRequestId()+",BizId:"+sendSmsResponse.getBizId()+"}");
    if ("OK".equals(sendSmsResponse.getCode())) {
        result = true;
    }
    return result;
}