jpush.js 2.34 KB
import { updateJpush } from '@/api/jpush'
import { platform } from '@/config/index'

export function useJPush() {
  const jpushModule = uni.requireNativePlugin('JG-JPush')
  const isRegistrationPushed = ref(false)
  const registerID = ref(null)
  const startUploadJpush = () => {
    if (registerID.value) {
      updateJpush({ registrationId: registerID.value, platform: platform() })
        .then(() => {
          console.warn('推送注册成功')
          // tip.showToast(`推送注册成功${registerID.value}`)
          isRegistrationPushed.value = true
        })
        .catch((err) => {
          console.error('推送注册失败', err)
          // tip.showToast(`推送注册失败:${err}`)
        })
    }
  }

  const registerPush = () => {
    if (isRegistrationPushed.value) {
      return
    }
    if (registerID.value) {
      // 调用接口后台关联
      startUploadJpush()
      return
    }
    try {
      jpushModule.getRegistrationID((result) => {
        registerID.value = result.registerID
        console.warn('推送注册结果:', result)
        // tip.showToast(`推送注册结果:${registerID.value}`)
        startUploadJpush()
      })
    }
    catch (err) {
      console.error('推送注册异常', err)
      // tip.showToast(`推送注册异常 :${err}`)
    }
    // 可能registerPush异常失败,再重试一次
    setTimeout(() => {
      registerPush()
    }, 5000)
  }

  const checkNotificationAuthorization = () => {
    jpushModule.isNotificationEnabled((result) => {
      const code = result.code
      if (code !== 1) {
        uni.showToast({
          icon: 'none',
          title: '还没有通知权限,请在系统设置中开启',
          duration: 3000,
        })
        jpushModule.openSettingsForNotification((result) => {
          console.warn('打开通知设置结果:', result)
          if (result.code === 1) {
            // 用户已授权
            registerPush()
          }
          else {
            // 用户未授权
            uni.showToast({
              icon: 'none',
              title: '您还没有打开通知权限',
              duration: 3000,
            })
          }
        })
      }
    })
    jpushModule.requestPermission()
  }

  return {
    jpushModule,
    isRegistrationPushed,
    registerID,
    registerPush,
    checkNotificationAuthorization,
  }
}