All Products
Search
Document Center

Access Account authorization in iOS mini program

Last Updated: Mar 24, 2021

The Account authorization component is designed to enable the Alipay internal Mini Program to redirect to the Alipay authorization page through the scheme protocol to obtain the Alipay login state and then use various functions normally when the Mini Program is running in the client app. Here, the client app is an app developed by using the mPaaS framework. For example, the 1688 Mini Program obtains the Alipay login state through the Account authorization component in the client app. Then, the Mini Program can perform business operations such as purchases.

During the redirection, the following handling process may be triggered based on whether the Alipay app is installed on the user’s mobile phone.

  • If the Alipay app is also installed on the mobile phone of the user who uses the client app:
    1. When the client app needs the Alipay login state, it redirects to the Alipay authorization application page through the scheme protocol.
    2. After successful authorization, the user can normally proceed after returning to the client app.
  • If Alipay is not installed on the mobile phone of the user who uses the client app, the user needs to register or enter the account password in the Mini Program to log in.

Prerequisites

You have accessed the Mini Program framework based on the mini program access document, and have verified that all functions are working properly.

Note: Currently, Account authorization supports obtaining Alipay authorization for login in the Mini Program. When you access the mPaaS plugin in Account authorization, do not access the quick payment component, otherwise symbol conflicts may occur.

Common access configuration

Add the SDK

If you have used the mPaaS plugin to integrate the quick payment SDK, complete the following steps:

  1. Click Cancel for the quick payment SDK.
  2. Click Start editing.
  3. Click Add for Mini Program - Account authorization to integrate the SDK.

If you do not cancel quick payment before adding the Mini Program - Account authorization, symbol conflicts may occur.

The CocoaPods access method

  1. Construct the mPaaS CocoaPods environment by referring to Access by Using CocoaPods Based on the Native Framework.
  2. Modify Podfile based on the following example to introduce Account authorization.
    1. # mPaaS Pods Begin
    2. plugin "cocoapods-mPaaS", :show_all_specs => true
    3. source "https://code.aliyun.com/mpaas-public/podspecs_test.git"
    4. #use_pod_for_mPaaS!
    5. mPaaS_baseline '10.1.60'# Replace x.x.x with the actual baseline version.
    6. # mPaaS Pods End
    7. platform :ios, '9.0'
    8. target 'MPTinyAppDemo_pod' do
    9. // The Mini Program.
    10. mPaaS_pod "mPaaS_TinyApp"
    11. // Account authorization.
    12. mPaaS_pod "mPaaS_AliAccount"
    13. end

Configure redirection based on the scheme protocol

  1. Configure the scheme redirection whitelist by adding alipay and alipays to ensure that the app can be redirected to Alipay.
    alipays
  2. Check the URLTypes of the app, such as mpaasinsidedemo.
    URLTypes
  3. Configure other items related to the scheme protocol.
    • Configure the scheme of mPaaS containers:
      container
      Note: All scheme values mentioned below must be consistent with this scheme value.
    • Configure the scheme system callback:
      • For the non-frame hosting access method, configure in the system callback of the used AppDelegate.
         AppDelegate
      • For the framework hosting access method, configure in the callback provided by the mPaaS framework.
         host
  4. Configure other Account authorization items.
    • Submit a ticket or contact after-sales personnel to generate a new ANX_ALIPAY_INSIDE_CONFIG and overwrite the original configuration in InsideDataConfig.bundle.
    • Use the mPaaS WSG image generation tool to generate a new WSG image and replace the original one. Be sure to select Account authorization for Type and perform regression testing on functions related to Account authorization and the gateway after using the new WSG image. The test objects include the service gateway, publishing, and offline packages.
  5. Configure the opening method of the Mini Program that requires Account authorization.

    • When the Mini Program to be opened requires Account authorization capabilities, do not use the original Mini Program to open the API, but use the following special Mini Program - Account authorization to open the API:

      1. #import <NBInsideAccountAdaptor/NBIAuthService.h>
      2. #import <InsideAccountOpenAuth/ANXAccountOpenAuthModel.h>
      3. #import <InsideService/ANXInsideService.h>
      4. [NBIAuthService shareInstance].delegate = self;
      5. [[NBIAuthService shareInstance] startTinyApp:item[0] uId:nil params:nil];
    • Implement NBIAuthDelegate additionally:```
    • (void)authModelForMode:(NBIAuthMode)mode extendParams:(NSDictionary )extendParams callback:(NBIAuthCallback)callback {// NeedRefreshToken == YES;// The Account authorization is used to guarantee the serial type, if it is always NeedRefreshToken, then it is necessary to continuously jump authorization// TODO: Here, the redirection to Alipay for authorization, the obtaining of accessToken, and the local persistent obtaining of accessToken are for examples only. In actual use, the accessing party needs to customize the following code:if (YES == [[extendParams objectForKey:@”NeedRefreshToken”] boolValue]) {[self getOnlineTokenWithMode:mode callback:callback];} else {NBIAuthModel model = [self getLocalTokenModelWithMode:mode];if (nil == model) {[self getOnlineTokenWithMode:mode callback:callback];return;}if(mode == NBIAuthModePlatformOnly) {callback(model);}}}```.

Obtain the data model

When the Mini Program needs to obtain the Alipay login state, it calls back the aforementioned delegate function. This function obtains the corresponding data model and returns it to the mini program container through the callback. The container will then use this data model to obtain the Alipay login state.

  • The data model consists of three components:
    • uid (The Alipay user ID)
    • accessToken (The Alipay authorization token)
    • mcUid (The app user ID)
  • The process of obtaining the data model is as follows:
    1. Redirect to Alipay through AuthURL for authorization.
    2. Obtain authCode after successful authorization.
    3. Pass the authCode to the API of the accessing party to obtain the model, and then call the callback in the delegate to pass the data to the mini program container to obtain the Alipay login state.
  • Generally, accessToken has a validity period. In order to avoid redirecting to Alipay for authorization every time you open the Mini Program, take the following general practice. After you obtain Alipay authorization for the first time and obtain the data model, the model is cached. When the model is not expired, return it to the mini program container.
  • To determine whether the model is expired, check NeedRefreshToken in the extendParams parameter carried by the delegate callback. NeedRefreshToken indicates that accessToken is expired, and you need to redirect to Alipay again for authorization. In this case, you can repeat the process of obtaining the data model.
    An example is as follows:

    1. - (void)getOnlineTokenWithMode:(NBIAuthMode)mode callback:(NBIAuthCallback)callback
    2. {
    3. ANXAccountOpenAuthModel *model = [[ANXAccountOpenAuthModel alloc] init];
    4. model.scheme = PortalScheme;
    5. model.thirdAuth = YES;
    6. // TODO: The accessing party provides AuthURL.
    7. model.authURL = @"xxx";
    8. model.phoneNum = nil;
    9. [[ANXInsideService sharedService] startServiceWithModel:model completion:^(NSDictionary<ANXCallbackKey *,id> *result, NSError *error) {
    10. if ([result[ANXProductConfigResultCodeKey] isEqualToString:@"account_open_auth_9000"]) {
    11. // The authorization is successful, and authcode and app_id can be obtained.
    12. NSString *authcode = result[ANXProductConfigResultKey][@"auth_code"];
    13. NSDictionary *userInfo = @{@"behaviorCode" : @"AccountOpenAuth",
    14. @"params1" : result[ANXProductConfigResultKey]
    15. };
    16. [[NSNotificationCenter defaultCenter] postNotificationName:@"ANX_Login_log" object:nil userInfo:userInfo];
    17. NBIAuthModel *model = [[NBIAuthModel alloc] init];
    18. model.uid = @"xxx";
    19. model.token = @"xxx";
    20. model.extraInfo = @{@"mcUid": @"xxx"};
    21. if(mode == NBIAuthModePlatformOnly) {
    22. callback(model);
    23. }
    24. }
    25. }];
    26. }
Note: Both the AuthURL and the API for obtaining uid, accessToken, and mcUid based on authCode are provided by the accessing party.

Access payment

When the Mini Program requires Alipay’s quick payment capabilities, you must configure the scheme system callback.

  • For the non-mPaaS framework hosting method, add the following code:
    1. #import <AlipaySDK/AlipaySDK.h>
    2. - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
    3. {
    4. if ([url.host containsString:@"safepay"])
    5. {
    6. [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:nil];
    7. }
    8. // TODO: Other redirection logic.
    9. return YES;
    10. }
  • For the mPaaS framework hosting method, add the following code in the Category of the framework class:
    1. #import <AlipaySDK/AlipaySDK.h>
    2. - (DTFrameworkCallbackResult)application:(UIApplication *)application openURL:(NSURL *)url newURL:(NSURL **)newURL sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
    3. {
    4. if ([url.host containsString:@"safepay"])
    5. {
    6. [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:nil];
    7. }
    8. // TODO: Other redirection logic.
    9. return YES;
    10. }
Note: The callback of the AlipaySDK calls in the preceding two code segments must be nil, so that the AlipaySDK used when the Mini Program calls tradePay jsapi can obtain the callback result after the payment is completed.

Log out of the client or switch the user

When the accessing party logs out or switches the user, the Alipay login state of the client must be cleared. Otherwise, the Mini Program will continue to use the Alipay login information of the previous user.The accessing party needs to call the following methods when logging out or switching the user, and be sure to clear the persistence or cache of authcode and accesstoken when using Account authorization functions.

  1. // When a merchant account logs out or switches the account, it must call the account logout function to notify Account authorization of the account logout, and then authorize and bind again when accessing Account authorization again.
  2. ANXMCAccountStatusChangeModel *model = [ANXMCAccountStatusChangeModel new];
  3. model.status = MCAccountLogout;// The account logs out.
  4. //model.status = MCAccountUnbind; // The account unbinds Alipay.
  5. [[ANXInsideService sharedService] startServiceWithModel:model completion:nil];
  6. // TODO: When you are using Account authorization functions, be sure to clear the persistence and cache of authcode and accesstoken.

Payment configuration

If the accessing party has payment configuration requirements, submit a ticket to obtain the campaign ID and service scenario ID. After you obtain the IDs, configure in info.plist on the client as follows:

  1. <key>MPAuthIdentity</key>
  2. <dict>
  3. <key>instBizSceneCode</key>
  4. <string>The service scenario ID (replace it with the actual one.)</string>
  5. <key>instCampaignIds</key>
  6. <string>The campaign ID (replace it with the actual one.)</string>
  7. </dict>

Notes

When the user is performing Alipay authorization, that is, when redirecting from the app to Alipay for authorization, if the user returns to the app without performing anything on the Alipay page, the authorization will time out and fail in several minutes. Since the current authorization mechanism is waiting for Alipay until completion, this issue always exists.