Salesforce Schedule中调用接口案例

global class MessageTemplateStatusSchedule implements Schedulable 
{
	global void execute(SchedulableContext sc)
	{
		pushSMSTemplate();
	} 

	//接收返回json内部类
    public class PushSMSTemplateInner 
    { 
        public String statusCode;  //返回状态码 000000(成功)
        public String totalCount;
        public List TemplateSMS;
    }

    public class TemplateSMS
    {
        public String title;
        public String content;
        public String status;      //模板状态 0:待审核,1:通过审核,2:未通过审核,-1:已删除
        public String type;        //模板类型 0:验证码,1:通知,2:营销短信
        public String dateCreated;
        public String dateUpdated;
        public String id;          //模板Id
    }

    //发送请求
    public static HttpResponse Execute(string method,string url,string body,string authorization)
    {
        HttpRequest req = new HttpRequest();   
        req.setEndpoint(url);     
        req.setMethod(method);                      
        req.setTimeout(120000);
        req.setHeader('Content-Type','application/json;charset=utf-8');  
        req.setHeader('Accept','application/json');   
        req.setHeader('Authorization',authorization);
        if(body != null && body != '')
        {
            req.setBody(body);
        }
        HttpResponse response = new Http().send(req); 

        return response;
    }

    //发起Post方式请求
    public static HttpResponse HTTPPost(string url,string body,string authorization)
    {
        return Execute('POST',url,body,authorization);
    }

    @future(callout=true)
    public static void pushSMSTemplate() 
    {
        //查询Token信息
        SMSAccountNumber__c sms = new SMSAccountNumber__c();
        sms = [Select Id,
                      ACCOUNTSID__c,
                      APPID__c,
                      AUTHTOKEN__c,
                      RestURL__c,
                      SoftVersion__c
                      From SMSAccountNumber__c
                      limit 1
              ];

        //拼接请求SigParameter参数   账户Id + 账户授权令牌 + 时间戳(时间戳是当前系统时间,格式"yyyyMMddHHmmss")
        String sigParameter = sms.ACCOUNTSID__c + sms.AUTHTOKEN__c + String.valueOf(Datetime.now().format('yyyyMMddHHmmss'));

        //SigParameter参数 需要MD5加密
        Blob thehash = Crypto.generateDigest('MD5',Blob.valueOf(sigParameter));
        String SecretKey = EncodingUtil.convertToHex(thehash);

        //SigParameter参数需要大写
        String uppercasesig = SecretKey.touppercase();

        String url = sms.RestURL__c +'/'+ sms.SoftVersion__c +'/Accounts/' + sms.ACCOUNTSID__c + '/SMS/QuerySMSTemplate?sig=' + uppercasesig;

        //拼接请求SigParameter参数 需要base64加密   账户Id + 账户授权令牌 + 时间戳(时间戳是当前系统时间,格式"yyyyMMddHHmmss")
        String authorization = sms.ACCOUNTSID__c +':'+ String.valueOf(Datetime.now().format('yyyyMMddHHmmss'));
        Blob exampleIv = Blob.valueOf(authorization);
        String base64authorization = EncodingUtil.base64Encode(exampleIv);

        //请求包体
        String body = '{"appId":'+sms.APPID__c+'}';

        //发送请求
        Httpresponse res = HTTPPost(url,body,base64authorization);
        //反序列化Json串
        MessageTemplateStatusSchedule.PushSMSTemplateInner jsonApex = (MessageTemplateStatusSchedule.PushSMSTemplateInner)JSON.deserialize(EncodingUtil.urlDecode(res.getBody(),'utf_8'),MessageTemplateStatusSchedule.PushSMSTemplateInner.class);

        System.debug('===================res.getBody=================='+res.getBody());

        //查询所有短信模板
        List smslist = new List();
        smslist = [Select Id,ApprovalStatus__c,TemplateId__c From SMSTemplate__c Where IsPush__c = true];

        if(jsonApex.statusCode == '000000')
        {
	        for (MessageTemplateStatusSchedule.TemplateSMS ts : jsonApex.TemplateSMS) 
	        {
	    		for(SMSTemplate__c smst : smslist)
	    		{
	    			if(ts.id == smst.TemplateId__c)
	    			{
	    				//0:待审核,1:通过审核,2:未通过审核,-1:已删除
	    				if(ts.status == '0')
	    				{
	    					smst.ApprovalStatus__c = '审核中';
	    				}
	    				else if(ts.status == '1')
	    				{
	    					smst.ApprovalStatus__c = '审核通过';
	    				}
	    				else if(ts.status == '2')
	    				{
	    					smst.ApprovalStatus__c = '未通过审核';
	    				}
	    				else
	    				{
	    					smst.ApprovalStatus__c = '已删除';
	    				}
	    			}
	    		}
	        }
	    }
	    else
	    {
	    	//生成接口日志
	    	InterfaceLog__c lfl = new InterfaceLog__c();
            lfl.CreateTime__c = Datetime.now();
            lfl.ReceiveStatus__c = '失败';
            lfl.ErrorCode__c = jsonApex.statusCode;
            lfl.ErrorMessage__c = res.getBody();
            insert lfl;
	    }

        update smslist;
    }
}

你可能感兴趣的:(Schedule)