前兩天又一次要搞微信支付腌零,想想就難過。因為貴公司的文檔真心無力吐槽续誉。前面幾個步驟還好莱没,這里記錄一下調(diào)起支付的相關代碼初肉。
集成 實例化 調(diào)用弄完后酷鸦,翻到了“調(diào)起支付”這里。懵逼了很久牙咏。
下面三個方法記錄一下
1.MD5加密算法
2.微信需要的簽名算法(sign)
3.調(diào)起支付方法
// 傳入訂單信息(大部分支付的訂單信息都是服務端返回的臼隔,客戶端生成訂單信息會存在安全問題)
- (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;
}