当前位置: 移动技术网 > IT编程>移动开发>IOS > iOS应用内支付(IAP)详解

iOS应用内支付(IAP)详解

2018年09月18日  | 移动技术网IT编程  | 我要评论

郑球洋,总市值,陆柏权

在ios开发中如果涉及到虚拟物品的购买,就需要使用iap服务,我们今天来看看如何实现。

在实现代码之前我们先做一些准备工作,一步步来看。


1、iap流程

iap流程分为两种,一种是直接使用apple的服务器进行购买和验证,另一种就是自己假设服务器进行验证。由于国内网络连接apple服务器验证非常慢,而且也为了防止伪造购买凭证,通用做法是自己架设服务器进行验证。

下面我们通过图来看看两种方式的差别:

1.1、使用apple服务器

1.2、自己架设服务器

简单说下第二中情况的流程:

用户进入购买虚拟物品页面,app从后台服务器获取产品列表然后显示给用户用户点击购买购买某一个虚拟物品,app就发送该虚拟物品的productionidentifier到apple服务器apple服务器根据app发送过来的productionidentifier返回相应的物品的信息(描述,价格等)用户点击确认键购买该物品,购买请求发送到apple服务器apple服务器完成购买后,返回用户一个完成购买的凭证app发送这个凭证到后台服务器验证后台服务器把这个凭证发送到apple验证,apple返回一个字段给后台服务器表明该凭证是否有效后台服务器把验证结果在发送到app,app根据验证结果做相应的处理

2、itunes connet操作

搞清楚了自己架设服务器是如何完成iap购买的流程了之后,我们下一步就是登录到itunes connet创建应用和指定虚拟物品价格表

2.1、创建自己的app

如下图所示,我们需要创建一个自己的app,要注意的是这里的bundle id一定要跟你的项目中的info.plist中的bundle id保证一致。也就是图中红框部分。

2.2、创建虚拟物品价格表

2.2.1、虚拟物品分为如下几种:

消耗品(consumable products):比如游戏内金币等。

不可消耗品(non-consumable products):简单来说就是一次购买,终身可用(用户可随时从app store restore)。

自动更新订阅品(auto-renewable subscriptions):和不可消耗品的不同点是有失效时间。比如一整年的付费周刊。在这种模式下,开发者定期投递内容,用户在订阅期内随时可以访问这些内容。订阅快要过期时,将自动更新订阅(如果用户同意)。

非自动更新订阅品(non-renewable subscriptions):一般使用场景是从用户从iap购买后,购买信息存放在自己的开发者服务器上。失效日期/可用是由开发者服务器自行控制的,而非由app store控制,这一点与自动更新订阅品有差异。

免费订阅品(free subscriptions):在newsstand中放置免费订阅的一种方式。免费订阅永不过期。只能用于newsstand-enabled apps。

类型2、3、5都是以apple id为粒度的。比如小张有三个ipad,有一个apple id购买了不可消耗品,则三个ipad上都可以使用。

类型1、4一般来说则是现买现用。如果开发者自己想做更多控制,一般选4

2.2.2、创建成功后如下所示:

其中产品id是字母或者数字,或者两者的组合,用于唯一表示该虚拟物品,app也是通过请求产品id来从apple服务器获取虚拟物品信息的。

2.3、设置税务和银行卡信息

这一步必须设置,不然是无法从apple获取虚拟产品信息。

设置成功后如下所示:


3、ios端具体代码实现

完成了上面的准备工作,我们就可以开始着手iap的代码实现了。

我们假设你已经完成了从后台服务器获取虚拟物品列表这一步操作了,这一步后台服务器还会返回每个虚拟物品所对应的productionidentifier,假设你也获取到了,并保存在属性self.productident中。

需要在工程中引入 storekit.framework。

我们来看看后续如何实现iap

3.1、确认用户是否允许iap

//移除监听
-(void)dealloc
{
    [[skpaymentqueue defaultqueue] removetransactionobserver:self];
}

//添加监听
- (void)viewdidload{
    [super viewdidload];
    [self.tableview.mj_header beginrefreshing];
    [[skpaymentqueue defaultqueue] addtransactionobserver:self];
}

- (void)buyprodution:(uibutton *)sender{    
    if ([skpaymentqueue canmakepayments]) {
        [self getproductinfo:self.productident];
    } else {
        [self showmessage:@"用户禁止应用内付费购买"];
    }
}

3.2、发起购买操作

如果用户允许iap,那么就可以发起购买操作了

//从apple查询用户点击购买的产品的信息
- (void)getproductinfo:(nsstring *)productidentifier {
    nsarray *product = [[nsarray alloc] initwithobjects:productidentifier, nil];
    nsset *set = [nsset setwitharray:product];
    skproductsrequest * request = [[skproductsrequest alloc] initwithproductidentifiers:set];
    request.delegate = self;
    [request start];
    [self showmessagemanualhide:@"正在购买,请稍后"];
}

// 查询成功后的回调
- (void)productsrequest:(skproductsrequest *)request didreceiveresponse:(skproductsresponse *)response {
    [self hidehud];
    nsarray *myproduct = response.products;
    if (myproduct.count == 0) {
        [self showmessage:@"无法获取产品信息,请重试"];
        return;
    }
    skpayment * payment = [skpayment paymentwithproduct:myproduct[0]];
    [[skpaymentqueue defaultqueue] addpayment:payment];
}

//查询失败后的回调
- (void)request:(skrequest *)request didfailwitherror:(nserror *)error {
    [self hidehud];
    [self showmessage:[error localizeddescription]];
}

3.3、购买操作后的回调

//购买操作后的回调
- (void)paymentqueue:(skpaymentqueue *)queue updatedtransactions:(nsarray *)transactions {
    [self hidehud];
    for (skpaymenttransaction *transaction in transactions)
    {
        switch (transaction.transactionstate)
        {
            case skpaymenttransactionstatepurchased://交易完成
                self.receipt = [gtmbase64 stringbyencodingdata:[nsdata datawithcontentsofurl:[[nsbundle mainbundle] appstorereceipturl]]];
                [self checkreceiptisvalid];//把self.receipt发送到服务器验证是否有效
                [self completetransaction:transaction];
                break;

            case skpaymenttransactionstatefailed://交易失败
                [self failedtransaction:transaction];
                break;

            case skpaymenttransactionstaterestored://已经购买过该商品
                [self showmessage:@"恢复购买成功"];
                [self restoretransaction:transaction];
                break;

            case skpaymenttransactionstatepurchasing://商品添加进列表
                [self showmessage:@"正在请求付费信息,请稍后"];
                break;

            default:
                break;
        }
    }

}



- (void)completetransaction:(skpaymenttransaction *)transaction {
    [[skpaymentqueue defaultqueue] finishtransaction: transaction];
}


- (void)failedtransaction:(skpaymenttransaction *)transaction {
    if(transaction.error.code != skerrorpaymentcancelled) {
        uialertview *alertview = [[uialertview alloc] initwithtitle:nil message:@"购买失败,请重试"delegate:self cancelbuttontitle:@"取消" otherbuttontitles:@"重试", nil];
        [alertview show];
    } else {
        [self showmessage:@"用户取消交易"];
    }

    [[skpaymentqueue defaultqueue] finishtransaction: transaction];
}


- (void)restoretransaction:(skpaymenttransaction *)transaction {
    [[skpaymentqueue defaultqueue] finishtransaction: transaction];
}

3.4、向服务器端验证购买凭证的有效性

在这一步我们需要向服务器验证apple服务器返回的购买凭证的有效性,然后把验证结果通知用户

- (void)checkreceiptisvalid{

    afhttpsessionmanager manager]get:@"后台服务器地址"  parameters::@"发送的参数(必须包括购买凭证)"
    success:^(nsurlsessiondatatask * _nonnull task, id  _nonnull responseobject) {
        if(凭证有效){
          你要做的事
        }else{//凭证无效
          你要做的事
        }

    } failure:^(nsurlsessiondatatask * _nullable task, nserror * _nonnull error) {
                uialertview *alertview = [[uialertview alloc] initwithtitle:nil message:@"购买失败,请重试"delegate:self cancelbuttontitle:@"取消" otherbuttontitles:@"重试", nil];
            [alertview show];
    }

}

3.5、发送凭证失败的处理

如果出现网络问题,导致无法验证。我们需要持久化保存购买凭证,在用户下次启动app的时候在后台向服务器再一次发起验证,直到成功然后移除该凭证。
保证如下define可在全局访问:

#define appstoreinfolocalfilepath [nsstring stringwithformat:@"%@/%@/", [nssearchpathfordirectoriesindomains(nsdocumentdirectory, nsuserdomainmask, yes) lastobject],@"eacef35fe363a75a"]
-(void)alertview:(uialertview *)alertview clickedbuttonatindex:(nsinteger)buttonindex
{
    if (buttonindex == 0)
    {
        [self savereceipt];
    }
    else
    {
        [self checkreceiptisvalid];
    }
}

//apputils 类的方法,每次调用该方法都生成一个新的uuid
+ (nsstring *)getuuidstring
{
    cfuuidref uuidref = cfuuidcreate(kcfallocatordefault);
    cfstringref strref = cfuuidcreatestring(kcfallocatordefault , uuidref);
    nsstring *uuidstring = [(__bridge nsstring*)strref stringbyreplacingoccurrencesofstring:@"-" withstring:@""];
    cfrelease(strref);
    cfrelease(uuidref);
    return uuidstring;
}

//持久化存储用户购买凭证(这里最好还要存储当前日期,用户id等信息,用于区分不同的凭证)
-(void)savereceipt{
    nsstring *filename = [apputils getuuidstring];
    nsstring *savedpath = [nsstring stringwithformat:@"%@%@.plist", appstoreinfolocalfilepath, filename];

    nsdictionary *dic =[ nsdictionary dictionarywithobjectsandkeys:
                        self.receipt,                           request_transactionreceipt,
                        self.date                               date                        
                        self.userid                             userid
                        nil];

    [dic writetofile:savedpath atomically:yes];
}

3.6、app启动后再次发送持久化存储的购买凭证到后台服务器

- (bool)application:(uiapplication *)application didfinishlaunchingwithoptions:(nsdictionary *)launchoptions{    
    nsfilemanager *filemanager = [nsfilemanager defaultmanager];

    //从服务器验证receipt失败之后,在程序再次启动的时候,使用保存的receipt再次到服务器验证
    if (![filemanager fileexistsatpath:appstoreinfolocalfilepath]) {//如果在改路下不存在文件,说明就没有保存验证失败后的购买凭证,也就是说发送凭证成功。
        [filemanager createdirectoryatpath:appstoreinfolocalfilepath//创建目录
               withintermediatedirectories:yes
                                attributes:nil
                                     error:nil];
    }
    else//存在购买凭证,说明发送凭证失败,再次发起验证
    {
        [self sendfailediapfiles];
    }
}

//验证receipt失败,app启动后再次验证
- (void)sendfailediapfiles{
    nsfilemanager *filemanager = [nsfilemanager defaultmanager];
    nserror *error = nil;

    //搜索该目录下的所有文件和目录
    nsarray *cachefilenamearray = [filemanager contentsofdirectoryatpath:appstoreinfolocalfilepath error:&error];

    if (error == nil)
    {
        for (nsstring *name in cachefilenamearray)
        {
            if ([name hassuffix:@".plist"])//如果有plist后缀的文件,说明就是存储的购买凭证
            {
                nsstring *filepath = [nsstring stringwithformat:@"%@/%@", appstoreinfolocalfilepath, name];
                [self sendappstorerequestbuyplist:filepath];

            }
        }
    }
    else
    {
        debuglog(@"appstoreinfolocalfilepath error:%@", [error domain]);
    }
}

-(void)sendappstorerequestbuyplist:(nsstring *)plistpath
{
    nsdictionary *dic = [nsdictionary dictionarywithcontentsoffile:plistpath];

    //这里的参数请根据自己公司后台服务器接口定制,但是必须发送的是持久化保存购买凭证
    nsmutabledictionary *params = [nsmutabledictionary dictionarywithobjectsandkeys:
              [dic objectforkey:userid],                           userid,                    
              [dic objectforkey:date],                             date,  
              [dic objectforkey:receipt],                              receipt,                                                                             
              nil];


         afhttpsessionmanager manager]get:@"后台服务器地址"  parameters:params    success:^(nsurlsessiondatatask * _nonnull task, id  _nonnull responseobject) {
        if(凭证有效){
         [self removereceipt]
        }else{//凭证无效
          你要做的事
        }

    } failure:^(nsurlsessiondatatask * _nullable task, nserror * _nonnull error) {

    }

 }

//验证成功就从plist中移除凭证
-(void)sendappstorerequestsucceededwithdata
{
    nsfilemanager *filemanager = [nsfilemanager defaultmanager];
    if ([filemanager fileexistsatpath:appstoreinfolocalfilepath])
    {
        [filemanager removeitematpath:appstoreinfolocalfilepath error:nil];
    }
}

至此,整个流程结束,有任何疑问欢迎大家留言

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网