Nexmo API(现为Vonage API的一部分)是一组通信API,允许开发者通过短信、语音、验证等功能集成通信能力到应用中。Google Apps Script (GAS)是Google提供的基于JavaScript的云脚本语言,用于扩展Google Workspace应用功能。
function sendSMS() {
var apiKey = 'YOUR_NEXMO_API_KEY';
var apiSecret = 'YOUR_NEXMO_API_SECRET';
var fromNumber = 'NEXMO_VIRTUAL_NUMBER';
var toNumber = 'RECIPIENT_NUMBER';
var messageText = 'Hello from Google Apps Script!';
var url = 'https://rest.nexmo.com/sms/json?' +
'api_key=' + encodeURIComponent(apiKey) +
'&api_secret=' + encodeURIComponent(apiSecret) +
'&from=' + encodeURIComponent(fromNumber) +
'&to=' + encodeURIComponent(toNumber) +
'&text=' + encodeURIComponent(messageText);
var response = UrlFetchApp.fetch(url, {
method: 'GET',
muteHttpExceptions: true
});
var result = JSON.parse(response.getContentText());
Logger.log(result);
if (result.messages[0].status === '0') {
Logger.log('Message sent successfully');
} else {
Logger.log('Message failed with error: ' + result.messages[0]['error-text']);
}
}
function startVerification() {
var apiKey = 'YOUR_NEXMO_API_KEY';
var apiSecret = 'YOUR_NEXMO_API_SECRET';
var phoneNumber = 'USER_PHONE_NUMBER';
var brandName = 'YOUR_APP_NAME';
var url = 'https://api.nexmo.com/verify/json?' +
'api_key=' + encodeURIComponent(apiKey) +
'&api_secret=' + encodeURIComponent(apiSecret) +
'&number=' + encodeURIComponent(phoneNumber) +
'&brand=' + encodeURIComponent(brandName);
var response = UrlFetchApp.fetch(url, {
method: 'GET',
muteHttpExceptions: true
});
var result = JSON.parse(response.getContentText());
if (result.status === '0') {
Logger.log('Verification request sent, request_id: ' + result.request_id);
return result.request_id;
} else {
Logger.log('Error: ' + result.error_text);
return null;
}
}
function checkVerification(requestId, code) {
var apiKey = 'YOUR_NEXMO_API_KEY';
var apiSecret = 'YOUR_NEXMO_API_SECRET';
var url = 'https://api.nexmo.com/verify/check/json?' +
'api_key=' + encodeURIComponent(apiKey) +
'&api_secret=' + encodeURIComponent(apiSecret) +
'&request_id=' + encodeURIComponent(requestId) +
'&code=' + encodeURIComponent(code);
var response = UrlFetchApp.fetch(url, {
method: 'GET',
muteHttpExceptions: true
});
var result = JSON.parse(response.getContentText());
if (result.status === '0') {
Logger.log('Verification successful');
return true;
} else {
Logger.log('Verification failed: ' + result.error_text);
return false;
}
}
原因:
解决:
原因:
解决:
muteHttpExceptions
设置try {
var response = UrlFetchApp.fetch(url, {
method: 'GET',
muteHttpExceptions: true
});
var result = JSON.parse(response.getContentText());
} catch (e) {
Logger.log('Error parsing response: ' + e);
}
原因:
解决:
原因:
解决:
通过以上方法和示例,您可以在Google Apps Script中有效地集成Nexmo API,实现各种通信功能。