com.aliyuncs.CommonRequest Java Examples

The following examples show how to use com.aliyuncs.CommonRequest. 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: 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 #4
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 #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: 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 #7
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 #8
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 #9
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 #10
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 #11
Source File: DefaultAliSmsTemplate.java    From fast-family-master with Apache License 2.0 5 votes vote down vote up
@Override
public void sendSms(AliSmsEntity aliSmsEntity) {
    final IAcsClient acsClient = this.getAcsClient();
    final CommonRequest request = this.getAliSmsRequest(aliSmsEntity);
    final CommonResponse response;
    try {
        response = acsClient.getCommonResponse(request);
        this.parseResponse(response);
    } catch (ClientException | IOException e) {
        throw new AliSmsException(e);
    } finally {
        acsClient.shutdown();
    }
}
 
Example #12
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 #13
Source File: AliYunSmsUtils.java    From pre with GNU General Public License v3.0 4 votes vote down vote up
public static SmsResponse sendSms(String phone, String signName, String templateCode) {
    SmsResponse smsResponse = new SmsResponse();
    //初始化ascClient
    DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", ACCESS_KEY_ID, ACCESS_KEY_SECRET);
    IAcsClient client = new DefaultAcsClient(profile);
    //组装请求对象
    CommonRequest request = new CommonRequest();
    /**
     * 使用post提交
     */
    request.setMethod(MethodType.POST);
    //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
    //request.setOutId("1454");
    request.setDomain("dysmsapi.aliyuncs.com");
    request.setVersion("2017-05-25");
    request.setAction("SendSms");
    request.putQueryParameter("RegionId", "cn-hangzhou");
    //待发送的手机号
    request.putQueryParameter("PhoneNumbers", phone);
    //短信签名
    request.putQueryParameter("SignName", signName);

    if ("登录".equals(templateCode)){
        templateCode = "SMS_172887387";
    } else if ("注册".equals(templateCode)){
        templateCode = "SMS_172887416";
    }
    //短信模板ID
    request.putQueryParameter("TemplateCode", templateCode);
    //验证码
    /**
     * 可选:模板中的变量替换JSON串,
     */
    String random = RandomStringUtils.random(6, false, true);
    request.putQueryParameter("TemplateParam", "{\"code\":\"" + random + "\"}");
    request.putQueryParameter("OutId", random);

    try {
        CommonResponse response = client.getCommonResponse(request);
        String responseData = response.getData();
        JSONObject jsonObject = JSONObject.parseObject(responseData);
        String code = (String) jsonObject.get("Code");
        if (StrUtil.isNotEmpty(code) && "OK".equals(code)) {
            //请求成功
            log.info(phone + ",发送短信成功");
            smsResponse.setSmsCode(random);
            smsResponse.setSmsPhone(phone);
            smsResponse.setSmsTime(System.nanoTime() + "");
            return smsResponse;
        } else {
            log.error(phone + ",发送短信失败:{}", jsonObject.get("Message"));
        }
    } catch (ClientException e) {
        log.error(phone + ",发送短信失败:{}", e.getMessage());
    }

    return null;
}
 
Example #14
Source File: AliSmsTemplate.java    From fast-family-master with Apache License 2.0 4 votes vote down vote up
default CommonRequest getAliSmsRequest(T t) {
    return null;
}
 
Example #15
Source File: AliyunVmsMessageNotifier.java    From super-cloudops with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void send(GenericNotifyMessage msg) {
	CommonRequest req = new CommonRequest();
	// 请求方法分为POST和GET,建议您选择POST方式
	req.setSysMethod(MethodType.POST);
	// Domain参数的默认值为dyvmsapi.aliyuncs.com
	req.setSysDomain("dyvmsapi.aliyuncs.com");
	req.setSysVersion("2017-05-25");
	// SingleCallByTts|SingleCallByVoice
	req.setSysAction(msg.getParameterAsString(KEY_VMS_ACTION, "SingleCallByTts"));
	// VoiceCode和TtsCode二选一即可,前者用于自定义语音文件通知,后者用于标准语音通知,
	// action都为SingleCallByTts,参考文档:
	// https://help.aliyun.com/document_detail/114036.html?spm=a2c4g.11186623.6.579.7bc95f33wpPjWM
	// https://help.aliyun.com/document_detail/114035.html?spm=a2c4g.11186623.6.581.56295ad5EBbcwv#
	String ttsCodeOrVoiceCode = config.getAliyun().getTemplates().getProperty(msg.getTemplateKey());
	// 自定义语音文件ID
	req.putQueryParameter("VoiceCode", ttsCodeOrVoiceCode);
	// 标准文本转语音模板ID
	req.putQueryParameter("TtsCode", ttsCodeOrVoiceCode);
	req.putQueryParameter("TtsParam", toJSONString(msg.getParameters()));
	req.putQueryParameter("CalledShowNumber", config.getAliyun().getCalledShowNumber());
	String calledNumber = msg.getToObjects().get(0);
	req.putQueryParameter("CalledNumber", calledNumber);
	req.putQueryParameter("PlayTimes", msg.getParameterAsString(KEY_VMS_PLAYTIMES, "2"));
	req.putQueryParameter("Volume", msg.getParameterAsString(KEY_VMS_VOLUME, "100"));
	req.putQueryParameter("Speed", msg.getParameterAsString(KEY_VMS_SPEED, "100"));
	req.putQueryParameter("OutId", msg.getCallbackId());

	try {
		log.debug("Aliyun vms request: {}", () -> toJSONString(req));
		CommonResponse resp = acsClient.getCommonResponse(req);
		if (!isNull(resp) && !isBlank(resp.getData())) {
			Properties body = parseJSON(resp.getData(), Properties.class);
			if (!isNull(body) && "OK".equalsIgnoreCase((String) body.get("Code"))) {
				if (log.isDebugEnabled())
					log.debug("Successed response: {}, request: {}", resp.getData(), toJSONString(req));
				else
					log.info("Successed calledNumer: {}, message: {}", calledNumber, msg.getParameters());
			} else
				log.warn("Failed response: {}, request: {}", resp.getData(), toJSONString(req));
		} else
			throw new NotificationException(kind(), format("Failed to vms request", toJSONString(req)));
	} catch (Exception e) {
		throw new NotificationException(kind(), e.getMessage(), e);
	}

}