iOS 微信支付(服务端下单)

2017-03-15  本文已影响60人  lancely

一、注册登录微信开放平台账号

  1. 注册登录微信开放平台账号
  2. 添加一个用于支付/分享的移动应用,等待审核通过
  3. 前往管理中心-移动应用,为通过审核的移动应用申请支付功能,并等待审核通过
    申请支付功能

详细步骤参照微信支付官方文档 微信APP支付接入商户服务中心

二、集成微信SDK

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    // 注册(如果使用了友盟,则先注册友盟)
    [WXApi registerApp:@"wxd930ea5d5a258f4f"];
    
    return YES;
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    return [WXApi handleOpenURL:url delegate:self];
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    return [WXApi handleOpenURL:url delegate:self];
}

// 微信支付结果的回调
- (void)onResp:(BaseResp *)resp {
    //启动微信支付的response
    NSString *strMsg = [NSString stringWithFormat:@"errcode:%d", resp.errCode];
    BOOL paySuccess = false;
    if([resp isKindOfClass:[PayResp class]]){
        //支付返回结果,实际支付结果需要去微信服务器端查询
        switch (resp.errCode) {
            case 0:
                strMsg = @"支付结果:成功!";
                paySuccess = true;
                break;
            case -1:
                strMsg = @"支付结果:失败!";
                break;
            case -2:
                strMsg = @"用户已经退出支付!";
                break;
            default:
                strMsg = [NSString stringWithFormat:@"支付结果:失败!retcode = %d, retstr = %@", resp.errCode,resp.errStr];
                break;
        }
    }
    NSNotification *nofity = [[NSNotification alloc] initWithName:kNofificationWechatPayCallback object:nil userInfo:@{@"success":paySuccess ? @(YES) : @(NO) ,@"errMsg":paySuccess ? @"" : strMsg}];
    [[NSNotificationCenter defaultCenter] postNotification:nofity];
}
"appid": "wxb423c568326b71ee" // 微信开放平台审核通过的应用 APPID
"partnerId": "1326631501" // 微信支付分配的商户号,也就是 MCH_ID
"nonceStr": "EStCEnC8lVvIBV10" // 随机字符串
"prepayId": "wx20160601113412a39d0f4d700072397236" // 预支付交易会话标识
/** 微信支付 */
- (void)pay {
    // 向服务器发送请求,获取微信订单信息
    NSURLSession *session = [NSURLSession sharedSession];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://www.xxx.com/pay.php"]];
    request.HTTPMethod = @"POST";
    NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSDictionary *res = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
        if ([res[@"errCode"] intValue] == 0) {
            // 调起微信
            PayReq *req = [[PayReq alloc] init];
            req.partnerId = kWx_MchId;
            req.prepayId = res[@"prepayId"];
            req.nonceStr = res[@"nonce_str"];
            req.timeStamp = (UInt32)[[NSDate date] timeIntervalSince1970];
            req.package = @"Sign=WXPay";
            // 传入相关参数签名
            req.sign = [self getSign:@{
                                       @"appid": kWx_AppId,
                                       @"partnerid": req.partnerId,
                                       @"noncestr": req.nonceStr,
                                       @"package": req.package,
                                       @"timestamp": @(req.timeStamp).stringValue,
                                       @"prepayid": req.prepayId
                                       }];
            [WXApi sendReq:req];
        }
    }];
    [task resume];
}

 /**
 生成签名参数sign

 @param params 参数
 @return sign
 */
- (NSString *)getSign:(NSDictionary *)params {
    NSMutableString *contentString  =[NSMutableString string];
    NSArray *keys = [params allKeys];
    //按字母顺序排序
    NSArray *sortedArray = [keys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];
    //拼接字符串
    for (NSString *categoryId in sortedArray) {
        if (![[params objectForKey:categoryId] isEqualToString:@""]
            && ![categoryId isEqualToString:@"sign"]
            && ![categoryId isEqualToString:@"key"]
            ) {
            [contentString appendFormat:@"%@=%@&", categoryId, [params objectForKey:categoryId]];
        }
        
    }
    //添加key字段
    [contentString appendFormat:@"key=%@", kWx_PartnerKey];
    //得到MD5 sign签名
    NSString *sign = [self getMD5:contentString];
    return sign;
}

/**
 MD5加密

 @param sourceString 源字符串
 @return 加密后的字符串
 */
- (NSString *)getMD5:(NSString *)sourceString {
    NSData *data = [sourceString dataUsingEncoding:NSUTF8StringEncoding];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(data.bytes, (CC_LONG)data.length, result);
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}
上一篇下一篇

猜你喜欢

热点阅读