Catalog
java realizes the function of sending short messages
Preface
Nowadays, the function of sending short messages has become the standard of Internet companies. This article will implement java sending short messages step by step.
Many of the three parties that provide short message service have been investigated. Almost all of them need enterprise certification to be used, which is very inconvenient for personal learning. After many comparisons, Tencent Cloud (not advertising here) was chosen for two reasons:
- Support for Wechat Public Number Certification (Low Threshold)
- Give away 100 free short messages every month (suitable for personal learning) (this point should be ignored by the children of the miners themselves)
development environment
Please refer to: Building sub-module project based on SpringBook
Tencent Cloud - SMS
-
Find Short Message Service
-
After opening, click Add Application
-
Set up short message signature (take public number as an example), choose public number or small program for signature type, and fill in the rest as required.
-
When the signature is complete, create the SMS template
-
After waiting for the above information review to be completed, you can start to use Tencent SMS service needs SDK AppID and AppKey. Here:
Code
-
pom.xml introduces dependencies
<properties> <java.version>1.8</java.version> <!-- Your other dependencies... --> <tencent.qcloudsms.version>1.0.6</tencent.qcloudsms.version> </properties> <dependencies> <!-- Your other dependencies... --> <!-- Tencent Short Message --> <dependency> <groupId>com.github.qcloudsms</groupId> <artifactId>qcloudsms</artifactId> <version>${tencent.qcloudsms.version}</version> </dependency> </dependencies>
-
Sending SMS Tool Class
package com.wayne.common.utils; import com.github.qcloudsms.*; import com.github.qcloudsms.httpclient.HTTPException; import com.wayne.common.entity.CmsMessageConfig; import com.wayne.common.exception.CustomException; import com.wayne.common.form.MessageForm; import org.json.JSONException; import java.io.IOException; /** * Sending SMS Tool Class * @author Wayne * @date 2019/6/26 */ public class MessageUtils { /** * Sending SMS by Template Supports Single and Group Sending * @param isSingle Whether single true: single, false: group * @param form Short Message Content and Receiver's Mobile Phone Number * @param config Short Message Configuration * @throws CustomException Abnormal information captured when sending failure */ public static void sendMessage(Boolean isSingle, MessageForm form, CmsMessageConfig config) throws CustomException { validateMessage(form, config); String regex = ";"; String[] params = {form.getCaptcha()}; String[] phoneNumbers = form.getMobiles().split(regex); SmsResultBase result; try { // Is it single? if (isSingle) { SmsSingleSender ssender = new SmsSingleSender(config.getAppId(), config.getAppKey()); result = ssender.sendWithParam("86", phoneNumbers[0], config.getTemplateId(), params, config.getSmsSign(), "", ""); } else { SmsMultiSender msender = new SmsMultiSender(config.getAppId(), config.getAppKey()); result = msender.sendWithParam("86", phoneNumbers, config.getTemplateId(), params, config.getSmsSign(), "", ""); } System.out.println(result); } catch (HTTPException e) { e.printStackTrace(); throw new CustomException("HTTP Response Code Error"); } catch (JSONException e) { e.printStackTrace(); throw new CustomException("json Parsing error"); } catch (IOException e) { e.printStackTrace(); throw new CustomException("network IO error"); } } /** * Calibration parameters */ private static void validateMessage(MessageForm messageForm, CmsMessageConfig messageConfig) throws CustomException { ValidatorUtils.validateEntity(messageForm); if (null == messageConfig) { throw new CustomException("System parameter anomaly"); } } }
-
CmsMessageConfig configuration class
package com.wayne.common.entity; import lombok.Data; import javax.persistence.*; @Data @Table(name = "cms_message_config") public class CmsMessageConfig { /** * Primary key */ @Id @Column(name = "ID") private Integer id; /** * AppID */ @Column(name = "APP_ID") private Integer appId; /** * AppKey */ @Column(name = "APP_KEY") private String appKey; /** * Short Message Template ID */ @Column(name = "TEMPLATE_ID") private Integer templateId; /** * Signature content */ @Column(name = "SMS_SIGN") private String smsSign; /** * Whether to delete, 0:No, 1:Yes */ @Column(name = "IS_DELETE") private String isDelete; /** * State, 0: Use, 1: Not use (at most one data should be in use at the same time) */ @Column(name = "IS_USE") private String isUse; /** * Creator ID */ @Column(name = "CREATE_ADMIN_ID") private Integer createAdminId; @Column(name = "EXTEND1") private String extend1; @Column(name = "EXTEND2") private String extend2; @Column(name = "EXTEND3") private String extend3; @Column(name = "EXTEND4") private String extend4; @Column(name = "EXTEND5") private String extend5; @Column(name = "EXTEND6") private String extend6; }
-
Service
@Override public ResponseBean sendMessage(MessageForm messageForm) { ValidatorUtils.validateEntity(messageForm); // Get the SMS configuration in use: here to query from the database CmsMessageConfig messageConfig = getCurrUseMessageConfig(); try { // Send short messages MessageUtils.sendMessage(Boolean.FALSE, messageForm, messageConfig); } catch (CustomException e) { e.printStackTrace(); return ResponseBean.createInstance(Boolean.FALSE, 401, e.getMessage()); } return ResponseBean.createInstance(); }
-
Controller
@PostMapping("/message/sendMessage") public ResponseBean sendMessage(MessageForm messageForm) { return messageService.sendMessage(messageForm); }
Effect
No.1 SMS Template
-
No.2 Short Message Template
-
Setting Short Message Configuration Information
Concluding remarks
Finally, I have opened the public number. Welcome to the irrigation.