没什么话说,直接看步骤和代码。




1、准备

[Swift] 纯文本查看 复制代码
let app_id = "appid";
let mch_id = "商户号";
let api_key = "api_key";





2、配置



2.1、SDK

下载微信支付SDK,把下面三个文件拖进工程。

  • libWeChartSDK.a
  • WXAPi.h
  • WXApiObject.h




2.2、URL Types

Swift 微信支付 1 URL Types

手把手教你用Swift实现微信支付 - 敏捷大拇指 - Swift 微信支付 1 URL Types

URL Types



2.3、info.plist

[Swift] 纯文本查看 复制代码
LSApplicationQueriesSchemes
    weixin
    wechart

App Transport Security Settings
     Allow Arbitrary Loads


Swift 微信支付 2 info.plist

手把手教你用Swift实现微信支付 - 敏捷大拇指 - Swift 微信支付 2 info.plist

info.plist



2.4、添加支持库

[Swift] 纯文本查看 复制代码
libc++.tbd
libsqlite3.tbd
libz.tbd
CoreTelephony.framework
SystemConfiguration.framework




2.5、XML

下载解析XML的框架 ONOXMLDocument,地址:https://github.com/mattt/Ono

[Swift] 纯文本查看 复制代码
/**
 * 导入库 libxml2.tod     
 * Build Phases -> header search paths -> /usr/include/libxml2
 */


Ono.h 会提示错误,改成

[Swift] 纯文本查看 复制代码
#import "ONOXMLDocument.h"




2.6、混编

在混编的头文件里添加:

[Swift] 纯文本查看 复制代码
#import "WXApi.h"
#import "WXApiObject.h"

#import "Ono.h"

// 这个自己创建
#import "WXParameters.h”




2.7、WXParameters 复制


2.7.1、.H文件

[Swift] 纯文本查看 复制代码
#import <Foundation/Foundation.h>

@interface WXParameters : NSObject

+ (NSString *)IP;   //设备ip
+ (NSString *)md5:(NSString *)str;  //MD5
+ (NSString *)nonce_str;    //32位随机字符串
+ (NSString *)out_trade_no; //商户订单号
@end



2.7.2、.M文件

导入:

[Swift] 纯文本查看 复制代码
#import <ifaddrs.h>
#import <arpa/inet.h>
#import <CommonCrypto/CommonDigest.h>


static WXParameters *instance;

@implementation WXParameters

#pragma mark - 设备IP
+ (NSString *)IP {

    NSString *address = @"error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    // retrieve the current interfaces - returns 0 on success
    success = getifaddrs(&interfaces);

    if (success == 0) {
        // Loop through linked list of interfaces
        temp_addr = interfaces;
        while(temp_addr != NULL) {
            if (temp_addr->ifa_addr->sa_family == AF_INET) {
                // Check if interface is en0 which is the wifi connection on the iPhone
                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                    // Get NSString from C String
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                }
            }
            temp_addr = temp_addr->ifa_next;
        }
    }
    // Free memory
    freeifaddrs(interfaces);

    return address;
}


#pragma MD5加密算法
+ (NSString *)md5:(NSString *)str {
    const char *cStr = [str UTF8String];
    //加密规则,因为逗比微信没有出微信支付demo,这里加密规则是参照安卓demo来得
    unsigned char result[16]= "0123456789abcdef";
    CC_MD5(cStr, (CC_LONG)strlen(cStr), result);
    //这里的x是小写则产生的md5也是小写,x是大写则md5是大写,这里只能用大写,逗比微信的大小写验证很逗
    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]
            ];
}


#pragma mark - 随机字符串
+ (NSString *)nonce_str {

    char data[32];

    for (int x = 0; x < 32; data[x++] = (char)('A' + (arc4random_uniform(26))));

    return [[NSString alloc] initWithBytes:data length:32 encoding:NSUTF8StringEncoding];
}


#pragma mark - 商户订单号
+ (NSString *)out_trade_no {

    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];

    [dateFormat setDateFormat:@"yyyyMMddHHmmss"];

    return [dateFormat stringFromDate:[NSDate date]];
}

@end





3、使用



3.1、AppDelegate

遵循 WXApiDelegate 协议

[Swift] 纯文本查看 复制代码
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    WXApi.registerApp("wx22223"/*改成你自己的*/, withDescription: "MNLWXPay")

    return true
}

func application(application: UIApplication, handleOpenURL url: NSURL) -> Bool {
    return WXApi.handleOpenURL(url, delegate: self)
}

// MARK: - WXApiDelegate 支付结果
func onResp(resp: BaseResp!) {

    if resp.isKindOfClass(PayResp.classForCoder()) {

        //支付返回结果,实际支付结果需要去微信服务器端查询
        let strMsg: String?, strTitle = "支付结果"

        switch resp.errCode {
        case 0:
            strMsg = "支付结果:成功!";
            print("支付成功-PaySuccess,retcode = \(resp.errCode)")
        default:
            strMsg = "支付结果:失败!retcode = \(resp.errCode), retstr = \(resp.errCode)"
            print("错误,retcode = \(resp.errCode), retstr = \(resp.errStr)")
        }
    }
}




3.2、ViewController

[Swift] 纯文本查看 复制代码
@IBAction func wxPayClick(sender: UIButton) {

    wxPar("1", body: "支付说明")
}

func wxPar(totoal_fee: String, body: String) {

    if !WXApi.isWXAppInstalled() {
        print("没有安装微信"); return
    }else if !WXApi.isWXAppSupportApi() {
        print("当前版本不支持微信支付"); return
    }

    var parameters = [String: AnyObject]()
    parameters["appid"] = app_id
    parameters["mch_id"] = mch_id
    parameters["nonce_str"] = WXParameters.nonce_str()
    parameters["body"] = body
    parameters["out_trade_no"] = WXParameters.out_trade_no()
    parameters["total_fee"] = totoal_fee
    parameters["spbill_create_ip"] = WXParameters.IP()
    parameters["notify_url"] = "http://wxpay.weixin.qq.com/pub_v2/pay/notify.v2.php"
    parameters["trade_type"] = "APP"

    // MARK: - Sign & XML

    var stringA = String(), XMLString = "\n<xml>";

    for key in parameters.keys.sort() {
        stringA.appendContentsOf("\(key)=\(parameters[key]!)&")
        XMLString.appendContentsOf("\n\t<\(key)>\(parameters[key]!)</\(key)>")
    }
    stringA.removeAtIndex(stringA.endIndex.predecessor())

    let sign = WXParameters.md5("\(stringA)&key=\(api_key)").uppercaseString
    XMLString.appendContentsOf("\n\t<sign>\(sign)</sign>\n</xml>")

    // MARK: - END

    Alamofire.upload(.POST, "https://api.mch.weixin.qq.com/pay/unifiedorder", data: XMLString.dataUsingEncoding(NSUTF8StringEncoding)!).responseData { (response) in

        switch response.result {
        case .Success(let data):

            let prepay_id = try! ONOXMLDocument.init(data: data).rootElement.firstChildWithTag("prepay_id").stringValue()

            let request = PayReq.init()
            request.nonceStr = WXParameters.nonce_str()
            request.package = "Sign=WXPay"
            request.partnerId = self.mch_id
            request.prepayId = prepay_id
            request.timeStamp = UInt32(NSDate.init().timeIntervalSince1970)

            let stringA = "appid=\(self.app_id)&noncestr=\(request.nonceStr)&package=Sign=WXPay&partnerid=\(self.mch_id)&prepayid=\(prepay_id)×tamp=\(request.timeStamp)"

            request.sign = WXParameters.md5("\(stringA)&key=\(self.api_key)").uppercaseString

            WXApi.sendReq(request)

        case .Failure(let error):
            print("统一下单失败!\(error)")
        }
    }
}





也可以参考Swifthumb上的:

10分钟搞定支付宝和微信支付的各种填坑,7个问题解决办法

说说第三方支付接口开发及开发中遇到的坑爹问题 源码下载




作者:兔小七