# 微博SDK-鸿蒙接入文档

## 接入代码

### 初始化SDK

在页面创建前执行一些初始化工作（相当于Android的application）

``` arkts
export default class MyAbilityStage extends AbilityStage {
	private readonly APP_KEY = "在微博开发平台为应用申请的App Key";
	private readonly REDIRECT_URL = "在微博开放平台设置的授权回调页";
	//注意：scope为""，表示没有申请的高级权限，则走快捷授权流程
	private readonly SCOPE = "在微博开放平台为应用申请的高级权限";
	private readonly CALLBACK_ABILITY = "微博授权分享后的回呼abiltiy";//如‘EntryAbility'
	private readonly CALLBACK_MODULE = "微博授权分享后的回呼module";// 如不传入，默认是entry
		
	onCreate(): void {
		this.initSdk();
	}
		
	/**
	 * 初始化sdk。
	 * 理论上使用前只要初始化一次即可，具体分享及授权登录时将不需要再次初始化。
	 */
	private initSdk(): void {
		WeiboLogger.debug("testTag", "AbilityStage init sdk context: " + this.context);
		let authInfo = new AuthInfo(this.context, this.APP_KEY, this.REDIRECT_URL, this.SCOPE, this.CALLBACK_ABILITY, this.CALLBACK_MODULE);
		let listener: SdkListener = {
		  onInitSuccess: () => {
		    WeiboLogger.debug("testTag", "init sdk success " );
		  },
		  onInitFail: (error: Error) => {
		    WeiboLogger.debug("testTag", "init sdk failed errmsg: " + error.message);
		  }
		};
		WBAPI.getInstance(this.context).registerApp(authInfo, listener);
	}
}
```

### 微博授权回调

1. 在EntryAbility里添加微博授权回调
``` arkts
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
    Utils.logger.debug('testTag', 'Ability onCreate');
    //此处添加微博授权回调
    WBAPI.getInstance().doWBAsResult(want, this.context);
  }

  onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void {
    Utils.logger.debug('testTag', 'Ability onNewWant');
    //此处添加微博授权回调
    WBAPI.getInstance().doWBAsResult(want, this.context);
  }
```

### 使用微博授权

1. 在Ability或业务所在Page中调用授权API（请选择其中一种方式）

```arkts
//方式一，优先客户端授权，未安装时使用Web授权
private startAuth() {
	let listener: WbASListener = {
	  onComplete: (token: Oauth2AccessToken) => {
	    promptAction.showToast({
          message: '微博授权成功',
          duration: 2000
        });
	  },
	  onError: (error: UiError) => {
	    promptAction.showToast({
          message: '微博授权出错: ' + error.errorMessage,
          duration: 2000
        });
	  },
	  onCancel: () => {
	    promptAction.showToast({
          message: '微博授权取消',
          duration: 2000
        });
	  }
	};
	if (this.mWBAPI != null) {
	  this.mWBAPI.authorize(this.context, listener);
	}
}

//方式二，指定通过客户端授权操作
private startClientAuth() {
	let listener: WbASListener = {
	  onComplete: (token: Oauth2AccessToken) => {
	    promptAction.showToast({
          message: '微博授权成功',
          duration: 2000
        });
	  },
	  onError: (error: UiError) => {
	    promptAction.showToast({
          message: '微博授权出错: ' + error.errorMessage,
          duration: 2000
        });
	  },
	  onCancel: () => {
	    promptAction.showToast({
          message: '微博授权取消',
          duration: 2000
        });
	  }
	};
	if (this.mWBAPI != null) {
	  this.mWBAPI.authorizeClient(this.context, listener);
	}
}		
  
//方式三，指定通过网页（Web）授权操作
private startWebAuth() {
	let listener: WbASListener = {
	  onComplete: (token: Oauth2AccessToken) => {
	    promptAction.showToast({
	      message: '微博授权成功',
	      duration: 2000
	    });
	  },
	  onError: (error: UiError) => {
	    promptAction.showToast({
	      message: '微博授权出错: ' + error.errorMessage,
	      duration: 2000
	    });
	  },
	  onCancel: () => {
	    promptAction.showToast({
	      message: '微博授权取消',
	      duration: 2000
	    });
	  }
	};
	if (this.mWBAPI != null) {
	  this.mWBAPI.authorizeWeb(listener);
	}
}

```

2. 错误码定位：[OAuth2.0 错误码](http://t.cn/8kWBkoj)

### 分享内容到微博

1. 实现回调接口，代码示例如下

```arkts
let listener: WbASListener = {
    onComplete: () => {
      promptAction.showToast({
        message: '分享成功',
        duration: 2000
      });
    },
    onError: (error: UiError) => {
      promptAction.showToast({
        message: '分享出错: ' + error.errorMessage,
        duration: 2000
      });
    },
    onCancel: () => {
      promptAction.showToast({
        message: '分享取消',
        duration: 2000
      });
    }
  };
```
2. 在自己的应用的EntryAbility中处理分享结果, 代码示例如下
```arkts
export default class EntryAbility extends UIAbility {
  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
    WeiboLogger.debug('testTag', 'Ability onCreate');
    WBAPI.getInstance().doWBAsResult(want, this.context);
  }

  onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void {
    WeiboLogger.debug('testTag', 'Ability onNewWant');
    //调用
    WBAPI.getInstance().doWBAsResult(want, this.context);
  }

  onDestroy(): void {
    WeiboLogger.debug('testTag', 'Ability onDestroy');
  }

  onWindowStageCreate(windowStage: window.WindowStage): void {
    // Main window is created, set main page for this ability
    WeiboLogger.debug('testTag', 'Ability onWindowStageCreate');

    windowStage.loadContent('pages/Index', (err, data) => {
      if (err.code) {
        WeiboLogger.debug('testTag', 'Failed to load the content. Cause: ' + JSON.stringify(err) ?? '');
        return;
      }
      WeiboLogger.debug('testTag', 'Succeeded in loading the content. Data: ' + JSON.stringify(data) ?? '');
    });
  }

  onWindowStageDestroy(): void {
    // Main window is destroyed, release UI related resources
    WeiboLogger.debug('testTag', 'Ability onWindowStageDestroy');
  }

  onForeground(): void {
    // Ability has brought to foreground
    WeiboLogger.debug('testTag', 'Ability onForeground');
  }

  onBackground(): void {
    // Ability has back to background
    WeiboLogger.debug('testTag', 'Ability onBackground');
  }

}
```
   > 注：这里是设置处理分享结果，如果调用doShareResult，将收不到分享结果。

3. 微博分享示例代码如下

```arkts
    //客户端分享目前支持文字、图片和视频，web分享仅支持文字
    private async doWeiboShare() {
    //创建分享的数据对象
    let message: WeiboMultiMessage = new WeiboMultiMessage();
    let textObject = new TextObject();
    let text = "我正在使用微博客户端发博器分享文字。";
    //设置分享文字
    if(this.shareText) {
      text = "这里设置您要分享的内容！";
      textObject.text = text;
      message.textObject = textObject;
    }
    //图片分享，通过图片uri进行分享
    if(this.shareMultiImage) {
      //创建分享图片对象
      let multiImage = new MultiImageObject();
      try {
        let uris = new ArrayList<string>();
        uris.add(fileUri.getUriFromPath(Utils.getCacheFile(getContext()) + "/aaa.png"));
        uris.add(fileUri.getUriFromPath(Utils.getCacheFile(getContext()) + "/bbb.png"));
        uris.add(fileUri.getUriFromPath(Utils.getCacheFile(getContext()) + "/ccc.png"));
        uris.add(fileUri.getUriFromPath(Utils.getCacheFile(getContext()) + "/ddd.png"));
        uris.add(fileUri.getUriFromPath(Utils.getCacheFile(getContext()) + "/eee.png"));
        uris.add(fileUri.getUriFromPath(Utils.getCacheFile(getContext()) + "/fff.png"));
        uris.add(fileUri.getUriFromPath(Utils.getCacheFile(getContext()) + "/ggg.png"));
        uris.add(fileUri.getUriFromPath(Utils.getCacheFile(getContext()) + "/hhhh.png"));
        uris.add(fileUri.getUriFromPath(Utils.getCacheFile(getContext()) + "/kkk.png"));
        //设置需要分享图片的uri数组
        multiImage.uriStrs = uris.convertToArray();
      } catch (e) {
        let err = e as BusinessError
        WeiboLogger.error("zhaojun8", "multi image file operation failed, error msg = " + err.message);
      }
      message.multiImageObject = multiImage;
    }
    
    // 视频分享 需提供视频和视频封面的uri
    if(this.shareVideo) {
      let videoObj = new VideoSourceObject();
      try {
        let videoFilePath = Utils.getVideoCacheFile(getContext()) + '/eeee.mp4';
        let videoUri = fileUri.getUriFromPath(videoFilePath);
        let coverUri = fileUri.getUriFromPath(Utils.getImageCacheFile(getContext()) + '/cover.png');
        videoObj.videoPath = videoUri;
        videoObj.coverPath = coverUri;
      } catch (e) {
        let err = e as BusinessError;
        WeiboLogger.error("zhaojun8", "video file operation failed, error msg = " + err.message + ", e: " + e);
      }
      message.videoSourceObject = videoObj;
    }
    
    if(this.mWBAPI != null) {
    //分享回调
      let listener: WbASListener = {
        onComplete: () => {
          promptAction.showToast({
            message: '分享成功',
            duration: 2000
          });
        },
        onError: (error: UiError) => {
          promptAction.showToast({
            message: '分享出错: ' + error.errorMessage,
            duration: 2000
          });
        },
        onCancel: () => {
          promptAction.showToast({
            message: '分享取消',
            duration: 2000
          });
        }
      };
      this.mWBAPI.shareMessage(this.context, message, listener);
    }
  }
```
