阿里短信iOS端发送API 签名加密处理

阿里云短信发送API 公共参数签名示例有Java端代码,安卓开发方便,但iOS比较苦逼
阿里签名生成文档

需要使用到的加密库:

pod 'LBXDataHandler', '~> 1.0.3' #加密方式

iOS OC实现直接看代码

- (void)sendMsgWithcurLocation:(NSString *)curPositionCode {
    YYAcitveAreaModel *model = [YYAcitveAreaModel getActiveModel];
    if (model.isOpenArea == NO || model.contackPhone.length <= 0) {
        return;
    }
    
    NSString *url = [self creataliSendMsgUrl:curPositionCode activeModel:model];
    __weak typeof(model) weakModel = model;
    [self.network getAppendingString:url withPara:nil cookie:NO netType:NetTypeAliMsg result:^(id info, NSError *error) {
        if (info) {
            NSString *code = [info objectForKey:@"Code"];
            if ([code.uppercaseString isEqualToString:@"OK"]) {
                // 成功
                weakModel.sendMsgTime = [[NSDate date] timeIntervalSince1970];
                [weakModel saveOrUpdateActiveModel];
            }else {
                NSString *msg = [info objectForKey:@"Message"];
                NSLog(@"阿里短信发送失败:%@",msg);
            }
        }else{
            NSLog(@"阿里短信发送失败:%@",error.localizedDescription);
        }
    }];
}

- (NSString *)creataliSendMsgUrl:(NSString *)curPositionCode activeModel:(YYAcitveAreaModel *)model {
    
    NSString *accesskey = @"LTAI5tDsjxeEzpMc****";
    NSString *secret = @"2i8mFIzygdy6qyXuWJ2O****";
    NSString *templateCode = @"SMS_219752717"; // 模板Id
    
    CLLocationCoordinate2D coor = self.currentLocation.coordinate;
    NSString *latStr = [NSString stringWithFormat:@"%.6f",coor.latitude];
    NSString *longStr = [NSString stringWithFormat:@"%.6f",coor.longitude];
    
    NSDictionary *templateParam =  @{@"name":@"【慧心】",@"position":model.thoroughfare,@"direction":@(model.radius),@"lng":longStr,@"lat":latStr};
    NSString *templateParamJson = [self dictionaryToJson:templateParam];
    
    NSDateFormatter *formater = [[NSDateFormatter alloc] init];
    formater.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss'Z'";
    formater.locale = [NSLocale autoupdatingCurrentLocale];
    formater.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
    NSString *timeS = [formater stringFromDate:[NSDate date]];
    NSLog(@"%@",timeS);
    
    NSString *uuidString = [NSUUID UUID].UUIDString;
    NSDictionary *dict = @{@"AccessKeyId":accesskey,
                           @"SignatureVersion":@"1.0",
                           @"SignatureNonce":uuidString,
                           @"SignatureMethod":@"HMAC-SHA1",
                           @"RegionId":@"cn-hangzhou",
                           @"Action":@"SendSms",
                           @"Format":@"JSON",
                           @"Timestamp":timeS,
                           @"Version":@"2017-05-25",
    };
    NSMutableDictionary *signatureParam = [NSMutableDictionary dictionaryWithDictionary:dict];
    [signatureParam setObject:templateParamJson forKey:@"TemplateParam"];
    [signatureParam setObject:model.contackPhone forKey:@"PhoneNumbers"];
    [signatureParam setObject:templateCode forKey:@"TemplateCode"];
    [signatureParam setObject:@"123" forKey:@"OutId"];
    [signatureParam setObject:@"慧心" forKey:@"SignName"];
    
    if ([signatureParam.allKeys containsObject:@"Signature"]) {
        [signatureParam removeObjectForKey:@"Signature"];
    }
    
    //按字母顺序排序
    NSArray *keys = signatureParam.allKeys;
    keys = [keys sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];
    NSMutableDictionary *dictM = [NSMutableDictionary dictionary];
    NSMutableString *argumentStr = [NSMutableString string];
    for (NSString *key in keys) {
        [dictM setObject:[signatureParam objectForKey:key] forKey:key];
        [argumentStr appendFormat:@"&%@=%@",[self specialUrlEncode:key],[self specialUrlEncode:[signatureParam objectForKey:key]]];
    }
    signatureParam = dictM;
    [argumentStr deleteCharactersInRange:NSMakeRange(0, 1)];
    NSMutableString *stringToSign = [NSMutableString string];
    [stringToSign appendFormat:@"GET&"];
    [stringToSign appendString:[self specialUrlEncode:@"/"]];
    [stringToSign appendString:@"&"];
    [stringToSign appendString:[self specialUrlEncode:argumentStr]];
    // cpNO3Oe4DoiEML50AVXAjQDrNxU=
    NSString *sign = [self signWithSecret:[NSString stringWithFormat:@"%@&",secret] stringToSign:stringToSign];
    //NSLog(@"签名:%@",sign);
    
    NSString *lastUrl = [NSString stringWithFormat:@"http://dysmsapi.aliyuncs.com/?Signature=%@&%@", [self specialUrlEncode:sign],argumentStr];
    NSLog(@"lasturl:%@",lastUrl);
    
    return lastUrl;
}

- (NSString *)specialUrlEncode:(NSString *)value {
    NSString *str = [[value encodeURLString] unicodeToUtf8];
    [str stringByReplacingOccurrencesOfString:@"+" withString:@"%20"];
    [str stringByReplacingOccurrencesOfString:@"*" withString:@"%2A"];
    [str stringByReplacingOccurrencesOfString:@"~" withString:@"%7E"];
    return str;
}

- (NSString *)signWithSecret:(NSString *)secret stringToSign:(NSString *)stringToSign {
    NSData *data = [[stringToSign utf8Data] hmacWithKey:[secret utf8Data] algorithm:(LBXHmacAlgSHA1)];
    NSString *sign = [data encodeBase64WithOptions:0];
    return  sign;
}
- (NSString*)dictionaryToJson:(id)dic {
    if (dic) {
        NSError *parseError = nil;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:0 error:&parseError];
        return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }else {
        return nil;
    }
}

结果对比

// 阿里的
 //    GET&%2F&AccessKeyId%3DtestId%26
 //    Action%3DSendSms%26
 //    Format%3DXML%26
 //    OutId%3D123%26
 //    PhoneNumbers%3D15300000001%26
 //    RegionId%3Dcn-hangzhou%26
 //   SignName%3D%25E9%2598%25BF%25E9%2587%258C%25E4%25BA%2591%25E7%259F%25AD%25E4%25BF%25A1%25E6%25B5%258B%25E8%25AF%2595%25E4%25B8%2593%25E7%2594%25A8%26
 //    SignatureMethod%3DHMAC-SHA1%26
 //    SignatureNonce%3D45e25e9b-0a6f-4070-8c85-2956eda1b466%26
 //    SignatureVersion%3D1.0%26
 //    TemplateCode%3DSMS_71390007%26
 //    TemplateParam%3D%257B%2522customer%2522%253A%2522test%2522%257D%26
 //    Timestamp%3D2017-07-12T02%253A42%253A19Z%26
 //    Version%3D2017-05-25
     
 // 自己的
 GET&%2F&AccessKeyId%3DLTAI5tDsjxeEzpMc9WUkWpwz%26
 Action%3DSendSms%26
 Format%3DJSON%26
 OutId%3D123%26
 PhoneNumbers%3D185****5206%26
 RegionId%3Dcn-hangzhou%26
 SignName%3D%25E6%2585%25A7%25E5%25BF%2583%26
 SignatureMethod%3DHMAC-SHA1%26
 SignatureNonce%3D500A7C8F-6D5B-472D-8A23-4FFCD77E3EE8%26
 SignatureVersion%3D1.0%26
 TemplateCode%3DSMS_218547214%26
 TemplateParam%3D%257B%2522curPositionCode%2522%253A%2522%25E5%2588%259B%25E4%25B8%259A%25E4%25BA%258C%25E8%25B7%25AF377-379%25E8%25B7%25AF%2522%252C%2522name%2522%253A%2522%25E3%2580%2590%25E6%2585%25A7%25E5%25BF%2583%25E3%2580%2591%2522%252C%2522position%2522%253A%2522%25E5%2588%259B%25E4%25B8%259A%25E4%25BA%258C%25E8%25B7%25AF377-379%25E8%25B7%25AF%2522%252C%2522direction%2522%253A5%257D%26
 Timestamp%3D2021-07-16T10%253A23%253A16Z%26
 Version%3D2017-05-25
 

 
 // 阿里文档
 http://dysmsapi.aliyuncs.com/?Signature=zJDF%2BLrzhj%2FThnlvIToysFRq6t4%3D&
 AccessKeyId=testId&
 Action=SendSms&
 Format=XML&
 OutId=123&
 PhoneNumbers=15300000001&
 RegionId=cn-hangzhou&
 SignName=%E9%98%BF%E9%87%8C%E4%BA%91%E7%9F%AD%E4%BF%A1%E6%B5%8B%E8%AF%95%E4%B8%93%E7%94%A8&
 SignatureMethod=HMAC-SHA1&
 SignatureNonce=45e25e9b-0a6f-4070-8c85-2956eda1b466&
 SignatureVersion=1.0&
 TemplateCode=SMS_71390007&
 TemplateParam=%7B%22customer%22%3A%22test%22%7D&
 Timestamp=2017-07-12T02%3A42%3A19Z&
 Version=2017-05-25

 // iOS端
 http://dysmsapi.aliyuncs.com/?Signature=hQPvO8bGI7bWZhyChfEuh13ZWUs%3DAccessKeyId=LTAI5tDsjxeEzpMc9WUkWpwz&Action=SendSms&Format=XML&OutId=123&PhoneNumbers=185****5206&RegionId=cn-hangzhou&SignName=%E6%85%A7%E5%BF%83&SignatureMethod=HMAC-SHA1&SignatureNonce=1CF52A07-875C-44A6-945B-D458C2D4E2EC&SignatureVersion=1.0&TemplateCode=SMS_218547214&TemplateParam=%7B%22curPositionCode%22%3A%22%E5%88%9B%E4%B8%9A%E4%BA%8C%E8%B7%AF377-379%E8%B7%AF%22%2C%22name%22%3A%22%E3%80%90%E6%85%A7%E5%BF%83%E3%80%91%22%2C%22position%22%3A%22%E5%88%9B%E4%B8%9A%E4%BA%8C%E8%B7%AF377-379%E8%B7%AF%22%2C%22direction%22%3A5%7D&Timestamp=2021-07-16T10%3A35%3A46Z&Version=2017-05-25

你可能感兴趣的:(阿里短信iOS端发送API 签名加密处理)