从Angular App向手机下发短信可以通过以下步骤实现:
下面是一个示例代码,展示了如何在Angular App中使用腾讯云短信服务发送短信:
import { HttpClient } from '@angular/common/http';
@Injectable()
export class SmsService {
private apiUrl = 'https://sms.tencentcloudapi.com/';
constructor(private http: HttpClient) {}
sendSms(phoneNumber: string, message: string): Observable<any> {
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const body = {
PhoneNumberSet: [phoneNumber],
TemplateID: 'YOUR_TEMPLATE_ID',
SmsSdkAppid: 'YOUR_SDK_APPID',
Sign: 'YOUR_SIGN',
TemplateParamSet: [message],
};
const headers = {
'Content-Type': 'application/json',
'X-TC-Action': 'SendSms',
'X-TC-Version': '2019-07-11',
'X-TC-Region': 'ap-guangzhou',
'Authorization': this.generateAuthorization(apiKey, secretKey),
};
return this.http.post(this.apiUrl, body, { headers });
}
private generateAuthorization(apiKey: string, secretKey: string): string {
const timestamp = Math.floor(Date.now() / 1000);
const signStr = `x-tc-key=${apiKey}&x-tc-timestamp=${timestamp}`;
const signature = CryptoJS.HmacSHA1(signStr, secretKey).toString(CryptoJS.enc.Base64);
return `TC3-HMAC-SHA256 Credential=${apiKey}/${this.getDateString(timestamp)}/sms/tc3_request, SignedHeaders=content-type;host, Signature=${signature}`;
}
private getDateString(timestamp: number): string {
const date = new Date(timestamp * 1000);
return date.toISOString().substr(0, 10);
}
}
请注意,上述代码中的YOUR_API_KEY
、YOUR_SECRET_KEY
、YOUR_TEMPLATE_ID
、YOUR_SDK_APPID
和YOUR_SIGN
需要替换为你在腾讯云短信服务中创建的相应信息。
这是一个基本的示例,你可以根据自己的需求进行修改和扩展。同时,腾讯云还提供了更多功能和服务,如短信模板管理、短信发送状态查询等,你可以根据具体需求选择适合的产品和功能。
更多关于腾讯云短信服务的信息和产品介绍,你可以访问腾讯云官方网站:腾讯云短信服务。
领取专属 10元无门槛券
手把手带您无忧上云