美文网首页一步步学习ios
iOS - 需求 - 将参数进行字典排序组成字符串(待签名字符

iOS - 需求 - 将参数进行字典排序组成字符串(待签名字符

作者: 彗星来的那一夜 | 来源:发表于2017-08-23 20:33 被阅读56次

    将所有POST参数(sign除外)进行字典排序,组成字符串:
    比如:(根据首字母排序,参数间用&相连,字典转成json格式)

    ap_id=20140723007148&biz_conte={"outTradeNo":201503201",toalAmount":
    "8.8",discountAmount":8.",unDiscountAmount":80",subject": 扫码支付",godsDetail": [{"godsI":
    "aple-01",godsName":ipad",godsCategory":78230",price":8.8",quantiy":1"}],"operatorId":
    "op01",storeId":pudong01",terminalId":t_01",timeExpire":
    "20150329101"}&charset=utf-8&method=alipay.trade.precate×tamp=2017-0724 03:750
    

    解决办法:
    1.首先传入的是参数字典.
    2.获取字典的所有key
    3.创建一个可变字符串
    4.将key和value对应用’=’相连起来
    5.其中value是字典的话,就转成json格式,再相连
    6.如果有空格,换行等等的格式字符,就将其替换掉

    示例:

    NSMutableString *contentString  =[NSMutableString string];
        NSDictionary* dict = [self convertToDict];
        NSArray *keys = [dict allKeys];
        //按字母顺序排序
        NSArray *sortedArray = [keys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
            return [obj1 compare:obj2 options:NSNumericSearch];
        }];
        //拼接字符串
        for (NSString *categoryId in sortedArray) {
            if (![categoryId isEqualToString:@"sign"] && ![categoryId isEqualToString:@"timestamp"]){
                if([categoryId isEqualToString:@"biz_content"]){
                    NSError *error = nil;
                    NSDictionary* bizDict = [dict objectForKey:@"biz_content"];
                    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:bizDict options:NSJSONWritingPrettyPrinted error: &error];
                    NSMutableData *tempJsonData = [NSMutableData dataWithData:jsonData];
                    NSString* jsonString1 = [[NSString alloc] initWithData:tempJsonData encoding:NSUTF8StringEncoding];
                    NSString *jsonString2 = [jsonString1 stringByReplacingOccurrencesOfString:@" : " withString:@":"];
                    [contentString appendFormat:@"biz_content=%@&",jsonString2];
                }else{
                    [contentString appendFormat:@"%@=%@&", categoryId, [dict valueForKey:categoryId]];
                }
    
    
            }
        }
        //添加key字段
        [contentString appendFormat:@"timestamp=%@", [dict objectForKey:@"timestamp"]];
        NSString *strUrl1 = [contentString stringByReplacingOccurrencesOfString:@"  " withString:@""];
    //    NSString *strUrl2 = [strUrl1 stringByReplacingOccurrencesOfString:@"\t" withString:@""];
        NSString *strUrl3 = [strUrl1 stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    

    上述代码中,timestamp是最后的一个key,是不用用&相连的,所以拿出来单独拼接.biz_content是一个字典,所以也单独进行判断,转成json格式进行拼接,这样就完成待签名字符串的整理了.

    相关文章

      网友评论

        本文标题: iOS - 需求 - 将参数进行字典排序组成字符串(待签名字符

        本文链接:https://www.haomeiwen.com/subject/nzujdxtx.html