前两天又一次要搞微信支付,想想就难过。因为贵公司的文档真心无力吐槽。前面几个步骤还好,这里记录一下调起支付的相关代码。
集成 实例化 调用弄完后,翻到了“调起支付”这里。懵逼了很久。
下面三个方法记录一下
1.MD5加密算法
2.微信需要的签名算法(sign)
3.调起支付方法
// 传入订单信息(大部分支付的订单信息都是服务端返回的,客户端生成订单信息会存在安全问题)
- (void)weixinPayRequestWithOrderString:(NSString *)orderString
{
time_t now;
time(&now);
NSString *time_stamp = [NSString stringWithFormat:@"%ld",now];
NSString *nonce_str = [self md5:time_stamp];
NSString *package = @"Sign=WXPay";
NSMutableDictionary *signParams = [NSMutableDictionary dictionary];
[signParams setObject:APP_ID forKey:@"appid"];
[signParams setObject:nonce_str forKey:@"noncestr"];
[signParams setObject:package forKey:@"package"];
[signParams setObject:MCH_ID forKey:@"partnerid"];
[signParams setObject:time_stamp forKey:@"timestamp"];
[signParams setObject:orderString forKey:@"prepayid"];
NSString *sign = [self createMD5Sign:signParams];
PayReq *req = [[PayReq alloc] init];
req.openID = APP_ID; //APPID
req.partnerId = MCH_ID; //商户号
req.prepayId = orderString;
req.nonceStr = nonce_str;
req.timeStamp = time_stamp.intValue;
req.package = package;
req.sign = sign;
[WXApi sendReq:req];
}
// MD5加密方法
- (NSString *)md5:(NSString *)input
{
const char *cStr = [input UTF8String];
unsigned char digest[16];
CC_MD5(cStr,(CC_LONG)strlen(cStr), digest); // This is the md5 call
NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
[output appendFormat:@"%02x", digest[i]];
return output;
}
- (NSString *)createMD5Sign:(NSMutableDictionary *)dict
{
NSMutableString *contentString = [NSMutableString string];
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 (![[dict objectForKey:categoryId] isEqualToString:@""] && ![categoryId isEqualToString:@"sign"] && ![categoryId isEqualToString:@"key"]) {
[contentString appendFormat:@"%@=%@&", categoryId, [dict objectForKey:categoryId]];
}
}
//添加key字段
[contentString appendFormat:@"key=%@", PARTNER_ID];
//得到MD5 sign签名
NSString *md5Sign = [self md5:contentString];
return md5Sign;
}
网友评论