Skip to content

Instantly share code, notes, and snippets.

@SalathielGenese
Last active August 13, 2019 15:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SalathielGenese/c13df9f7c1d4b4f3d6ffc644f7950ac5 to your computer and use it in GitHub Desktop.
Save SalathielGenese/c13df9f7c1d4b4f3d6ffc644f7950ac5 to your computer and use it in GitHub Desktop.
Use Orange API for SMS in Cameroun
const { default: axios } = require( 'axios' );
/**
*
* Send SMS
*
* @param {string} source The phone number sending the SMS, in the format '237698765432' (no '+' nor '00' prefix nor white spaces)
* @param {string} target The phone number to receive the SMS, in the format '237698765432' (no '+' nor '00' prefix nor white spaces)
* @param {string} message The content/body of the message. Default to empty message.
*
* @returns {Promise<SMSResponse>}
*
* @typedef {{ success: { outboundSMSMessageRequest:{ senderAddress:string, senderName:string, outboundSMSTextMessage:{ message:string }, resourceURL:string } } }} SMSResponse
*
*/
async function sendSMS( source, target, message = '' ) {
const { access_token: token } = await getToken();
const endpoint = `https://api.orange.com/smsmessaging/v1/outbound/tel:+${ source }/requests`;
return axios.post( endpoint, {
outboundSMSMessageRequest: {
outboundSMSTextMessage: {
message,
},
address: `tel:+${ target }`,
senderAddress: `tel:+${ source }`,
},
}, {
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${ token }`,
},
}).then( ({ data }) => data )
}
/**
*
* Get authentication token to interact with SMS API
*
* @type {() => Promise<TokenResponse>}
* @typedef {{ token_type:'Bearer', access_token:string, expires_in:number }} TokenResponse
*
*/
const getToken = ( ( response, next = Date.now() ) =>
async () => {
if ( next < Date.now() ) {
return response;
}
const Authorization = 'Basic [···]'; // Change with your Orange {{authorization_header}}
const endpoint = 'https://api.orange.com/oauth/v2/token';
const body = 'grant_type=client_credentials';
response = await axios.post( endpoint, body, {
headers: { Authorization },
}).then( ({ data }) => data );
// Stay valid until 10mins before expiration
// i.e 10 mins before the 90 days (per docs)
next = Date.now() + response.expires_in * 1E3 - 6E5;
return response;
})();
/**
*
* Main function here, self executed
*
*/
( () => {
const DESTINATION = '237690000000'; // Change accordingly
const ORIGIN = '237690000000'; // Change accordingly
const MESSAGE = 'Echo SMS (second time)';
sendSMS( ORIGIN, DESTINATION, MESSAGE )
.then( success => console.log({ success }) )
.catch( ({ response }) => console.error( response ) );
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment