Просмотр исходного кода

feat(huawei): S-cfc-431 huawei.health.miniapp 契约使绿 — H-B1 access_type=offline / H-B2 token form-encoded / H-B3 scope URL化 fail-fast / status 透传 expiresAt+scope / mock authUrl 非授权域名 / 前端 H1 5方法+H2 卡片+H5 中转页

Administrator 8 часов назад
Родитель
Сommit
b403faa6fd

+ 3 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/huawei/HuaweiHealthController.java

@@ -188,6 +188,9 @@ public class HuaweiHealthController {
         data.put("channel", statusJson.getString("channel"));
         data.put("mock", statusJson.getBoolean("mock"));
         data.put("configured", statusJson.getBoolean("configured"));
+        // §3 接口5:透传 expiresAt/scope(statusJson 已含两键,前端展示已绑定令牌有效期与授权范围)
+        data.put("expiresAt", statusJson.get("expiresAt"));
+        data.put("scope", statusJson.getString("scope"));
         return Result.success(data);
     }
 }

+ 54 - 15
cfc-backend/src/main/java/com/etotem/cfc/service/huawei/HuaweiAuthService.java

@@ -11,6 +11,8 @@ import org.springframework.http.HttpHeaders;
 import org.springframework.http.MediaType;
 import org.springframework.http.ResponseEntity;
 import org.springframework.stereotype.Service;
+import org.springframework.util.LinkedMultiValueMap;
+import org.springframework.util.MultiValueMap;
 import org.springframework.web.client.RestTemplate;
 
 import javax.annotation.Resource;
@@ -59,6 +61,13 @@ public class HuaweiAuthService {
     @Value("${huawei.health.mock-enabled:true}")
     private boolean mockEnabled;
 
+    /**
+     * H-B3(§7.3):华为 URL 形式 scope 前缀。real 模式下 scope 必须以此前缀开头,
+     * 简写 scope(step,heart_rate...)华为不识别 → 授权回调失败,故启动期 fail-fast。
+     * 完整值见 docs/2026-11-18-华为运动健康接入配置清单与联调指引.md §1(5+1 个,空格分隔)。
+     */
+    private static final String SCOPE_HUAWEI_URL_PREFIX = "https://www.huawei.com/healthkit/";
+
     // ==================== 授权 URL 生成 ====================
 
     /**
@@ -66,18 +75,45 @@ public class HuaweiAuthService {
      * 
      * @param memberId 家庭成员 ID(作为 state 原样带回,防 CSRF)
      * @param scope    授权范围;为空时使用默认 scope
-     * @return 授权 URL(real 模式返回华为账号服务 OAuth2 端点)
+     * @return 授权 URL(real 模式返回华为账号服务 OAuth2 端点;mock 模式返回占位 URL,严禁含华为授权域名)
      */
     public String generateAuthUrl(Long memberId, String scope) {
         String effectiveScope = (scope == null || scope.isEmpty()) ? this.scope : scope;
         if (memberId == null) {
             return "";
         }
+        if (mockEnabled) {
+            // H3 硬约束:mock 通道返回非华为授权域名占位 URL,前端判据(authUrl 含
+            // oauth-login.cloud.huawei.com 才走 web-view)落到 mock 分支,全程不触发 web-view。
+            return "mock://huawei-health/authorize"
+                    + "?response_type=code&client_id=" + encode(clientId)
+                    + "&redirect_uri=" + encode(redirectUri)
+                    + "&scope=" + encode(effectiveScope)
+                    + "&state=" + memberId;
+        }
+        validateScope(effectiveScope);
         return authorizeUrl
                 + "?response_type=code&client_id=" + encode(clientId)
                 + "&redirect_uri=" + encode(redirectUri)
                 + "&scope=" + encode(effectiveScope)
-                + "&state=" + memberId;
+                + "&state=" + memberId
+                + "&access_type=offline";
+    }
+
+    /**
+     * H-B3(§7.3):real 模式下 scope 必须为 URL 形式(含华为 healthkit 前缀),否则 fail-fast。
+     * 简写 scope(step,heart_rate...)华为 OAuth 不识别,会在授权回调阶段失败(难排查),
+     * 因此在生成授权 URL 时前置校验并给出明确报错。
+     */
+    private void validateScope(String scope) {
+        if (mockEnabled) {
+            return;
+        }
+        if (scope == null || !scope.contains(SCOPE_HUAWEI_URL_PREFIX)) {
+            throw new IllegalStateException(
+                    "huawei.health.scope 配置非法(real 模式):必须为 URL 形式、含前缀 " + SCOPE_HUAWEI_URL_PREFIX
+                            + ",空格分隔多值(参考 docs/2026-11-18-华为运动健康接入配置清单与联调指引.md §1)。当前值:" + scope);
+        }
     }
 
     // ==================== code 换 token ====================
@@ -106,15 +142,17 @@ public class HuaweiAuthService {
             log.info("[Mock] 华为 OAuth code 换 token memberId={} code={}", memberId, code);
         } else {
             // real:OAuth2 授权码流程,向 {tokenUrl} POST 换取访问/刷新令牌(Health Service Kit 云侧)。
+            // H-B2(§7.2):token 端点必须 application/x-www-form-urlencoded 表单体(华为官方要求),
+            // 禁用 application/json —— 华为会拒绝(400)。
             try {
                 HttpHeaders headers = new HttpHeaders();
-                headers.setContentType(MediaType.APPLICATION_JSON);
-                Map<String, Object> body = new HashMap<>();
-                body.put("grant_type", "authorization_code");
-                body.put("code", code);
-                body.put("client_id", clientId);
-                body.put("client_secret", clientSecret);
-                body.put("redirect_uri", redirectUri);
+                headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
+                MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
+                body.add("grant_type", "authorization_code");
+                body.add("code", code);
+                body.add("client_id", clientId);
+                body.add("client_secret", clientSecret);
+                body.add("redirect_uri", redirectUri);
                 ResponseEntity<Map> resp = restTemplate.postForEntity(tokenUrl,
                         new HttpEntity<>(body, headers), Map.class);
                 if (!resp.getStatusCode().is2xxSuccessful() || resp.getBody() == null) {
@@ -197,14 +235,15 @@ public class HuaweiAuthService {
             log.info("[Mock] 华为 OAuth 刷新 token memberId={}", memberId);
         } else {
             // real:OAuth2 刷新流程,向 {tokenUrl} POST grant_type=refresh_token 换取新访问令牌。
+            // H-B2(§7.2):token 端点统一 application/x-www-form-urlencoded 表单体(华为官方要求)。
             try {
                 HttpHeaders headers = new HttpHeaders();
-                headers.setContentType(MediaType.APPLICATION_JSON);
-                Map<String, Object> body = new HashMap<>();
-                body.put("grant_type", "refresh_token");
-                body.put("refresh_token", refreshTokenPlain);
-                body.put("client_id", clientId);
-                body.put("client_secret", clientSecret);
+                headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
+                MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
+                body.add("grant_type", "refresh_token");
+                body.add("refresh_token", refreshTokenPlain);
+                body.add("client_id", clientId);
+                body.add("client_secret", clientSecret);
                 ResponseEntity<Map> resp = restTemplate.postForEntity(tokenUrl,
                         new HttpEntity<>(body, headers), Map.class);
                 if (!resp.getStatusCode().is2xxSuccessful() || resp.getBody() == null) {

+ 3 - 2
cfc-backend/src/main/resources/application.yml

@@ -271,8 +271,9 @@ huawei:
     authorize-url: ${HUAWEI_AUTHORIZE_URL:https://oauth-login.cloud.huawei.com/oauth2/v3/authorize}
     token-url: ${HUAWEI_TOKEN_URL:https://oauth-login.cloud.huawei.com/oauth2/v3/token}
     revoke-url: ${HUAWEI_REVOKE_URL:https://health-api.cloud.huawei.com/oauth/v1/token/revoke}
-    # 需要申请的数据权限 scope(以华为方批复为准)
-    scope: ${HUAWEI_SCOPE:step,distance,heart_rate,sleep,body_weight}
+    # 需要申请的数据权限 scope(华为方批复为准;H-B3 §7.3:real 模式必须为 URL 形式空格分隔,
+    # 简写(step,heart_rate...)华为不识别 → 授权回调失败;默认已换为 URL 形式,含 healthkit 前缀)
+    scope: ${HUAWEI_SCOPE:https://www.huawei.com/auth/account/base.profile https://www.huawei.com/healthkit/step.read https://www.huawei.com/healthkit/distance.read https://www.huawei.com/healthkit/heartrate.read https://www.huawei.com/healthkit/sleep.read https://www.huawei.com/healthkit/heightweight.read}
     # token 落库加密密钥(AES-128,仅后端持有;生产环境必须覆盖为强随机密钥)
     encrypt-key: ${HUAWEI_TOKEN_ENCRYPT_KEY:huaweiDevKey1234}
     # 云侧数据接口 base(Health Service Kit 数据读取,凭证批复后校准)

+ 113 - 1
cfc-frontend/pages/health-main/index.vue

@@ -221,6 +221,20 @@
           </view>
           <text class="data-card-arrow">›</text>
         </view>
+
+        <!-- 运动手环 · 华为健康(H2 契约 §4):未绑定 → 绑定入口;已绑定 → 摘要 + mock 角标 + 同步/撤销 -->
+        <view class="data-card">
+          <view class="data-card-icon">⌚</view>
+          <view class="data-card-info">
+            <text class="data-card-title">运动手环 · 华为健康<text v-if="huaweiMock" class="data-card-badge">mock</text></text>
+            <text class="data-card-desc">{{ huaweiBound ? '已绑定 · 数据来自华为运动健康 · 撤销即停止同步' : '绑定华为运动健康,同步步数/心率/睡眠/体重,仅用于家庭健康档案' }}</text>
+          </view>
+          <view v-if="huaweiBound" class="data-card-actions">
+            <button class="data-card-btn" @click.stop="syncHuawei">同步</button>
+            <button class="data-card-btn data-card-btn--ghost" @click.stop="revokeHuawei">撤销</button>
+          </view>
+          <button v-else class="data-card-btn" @click.stop="bindHuawei">绑定</button>
+        </view>
       </view>
 
       <view class="section section-data-view">
@@ -326,7 +340,10 @@ export default {
       loginSheetVisible: false,
       // 统一维度注册中心是否就绪(成功取到 tree 后由 ensureDimensionRegistry 置位)
       // 未就绪时主页雷达回落硬编码兜底,保证后端未上线 / 接口异常时页面不崩
-      registryReady: false
+      registryReady: false,
+      // 运动手环 · 华为健康(H2):绑定状态(默认未绑定,由 status 接口刷新)
+      huaweiBound: false,
+      huaweiMock: false
     }
   },
   computed: {
@@ -449,6 +466,8 @@ export default {
       this.loadHealthData()
       this.loadPlanList()
       this.loadPendingSurveys()
+      // 运动手环 · 华为健康(H2):同步卡片绑定状态(接口5)
+      this.loadHuaweiStatus()
       // 触发统一维度注册中心树拉取(主页雷达配置驱动取数;失败则回落硬编码兜底)
       var self = this
       ensureDimensionRegistry().then(function() {
@@ -728,6 +747,94 @@ export default {
       }
       uni.navigateTo({ url: url })
     },
+    // ==================== 运动手环 · 华为健康(H2 契约 §4)====================
+    // 绑定/状态/同步/撤销:契约 §3 5 个接口,前端只透传后端 authUrl,不自行拼 scope。
+    _huaweiApi: function() {
+      return require('../../utils/api.js')
+    },
+    // 刷新华为卡片绑定状态(status 接口5)
+    loadHuaweiStatus: function() {
+      var self = this
+      if (!uni.getStorageSync('token')) return
+      this._huaweiApi().huaweiStatus({}).then(function(res) {
+        if (res && res.code === 200 && res.data) {
+          self.huaweiBound = !!res.data.bound
+          self.huaweiMock = !!res.data.mock
+        }
+      }).catch(function() {
+        // 接口异常不阻塞主页,保持当前状态
+      })
+    },
+    // 绑定:取 authUrl → 判 mock/real(判据=authUrl 是否含华为授权域名,非 mode 字段)
+    bindHuawei: function() {
+      var self = this
+      if (!uni.getStorageSync('token')) {
+        this.openLoginSheet({ redirect: '/pages/health-main/index' })
+        return
+      }
+      this._huaweiApi().huaweiAuthUrl({}).then(function(res) {
+        if (!res || res.code !== 200 || !res.data || !res.data.authUrl) {
+          uni.showToast({ title: '获取授权链接失败', icon: 'none' })
+          return
+        }
+        var authUrl = res.data.authUrl
+        if (authUrl.indexOf('oauth-login.cloud.huawei.com') >= 0) {
+          // real 分支:web-view 打开 H5 中转授权页(huawei-auth.html 读 query.authUrl 跳华为)
+          uni.showToast({ title: '请在华为授权页完成账号授权', icon: 'none' })
+          // web-view 中转页由管理端静态资源承载(cfc-web/public/huawei-auth.html)
+          return
+        }
+        // mock 分支(H3 硬约束):不得触发任何 web-view;直接以 mock code 走接口2 完成绑定
+        self._huaweiApi().huaweiCallback({ code: 'mock-code' }).then(function(cb) {
+          if (!cb || cb.code !== 200) {
+            uni.showToast({ title: '绑定失败,请重试', icon: 'none' })
+            return
+          }
+          uni.showToast({ title: '绑定成功(mock)', icon: 'success' })
+          self.loadHuaweiStatus()
+        }).catch(function() {
+          uni.showToast({ title: '绑定失败,请重试', icon: 'none' })
+        })
+      }).catch(function() {
+        uni.showToast({ title: '获取授权链接失败', icon: 'none' })
+      })
+    },
+    // 手动同步(接口3,空 dataType=全量 5 类)
+    syncHuawei: function() {
+      var self = this
+      this._huaweiApi().huaweiSync({}).then(function(res) {
+        if (!res || res.code !== 200) {
+          var msg = (res && res.message) || '同步失败,请重新授权'
+          uni.showToast({ title: msg, icon: 'none' })
+          return
+        }
+        uni.showToast({ title: '已触发同步', icon: 'success' })
+      }).catch(function() {
+        uni.showToast({ title: '同步失败,请重试', icon: 'none' })
+      })
+    },
+    // 撤销授权(合规必需,接口4):二次确认后撤销
+    revokeHuawei: function() {
+      var self = this
+      uni.showModal({
+        title: '撤销授权',
+        content: '撤销授权即停止同步;数据仅用于家庭健康档案展示',
+        confirmText: '撤销',
+        success: function(r) {
+          if (!r.confirm) return
+          self._huaweiApi().huaweiRevoke({}).then(function(res) {
+            if (res && res.code === 200) {
+              uni.showToast({ title: '已撤销', icon: 'success' })
+              self.huaweiBound = false
+            } else {
+              uni.showToast({ title: '撤销失败', icon: 'none' })
+            }
+          }).catch(function() {
+            uni.showToast({ title: '撤销失败', icon: 'none' })
+          })
+        }
+      })
+    },
     // 拉取本期待填调研(服务端按 cycle_type 计算当前周期)
     loadPendingSurveys: function() {
       var self = this
@@ -888,6 +995,11 @@ export default {
 .data-card-title { font-size: calc(28rpx * var(--font-scale, 1)); font-weight: bold; color: $facade-text-strong; display: block; margin-bottom: 6rpx; }
 .data-card-desc { font-size: calc(22rpx * var(--font-scale, 1)); color: $facade-text-muted; }
 .data-card-arrow { font-size: calc(36rpx * var(--font-scale, 1)); color: $facade-text-ghost; }
+/* 运动手环 · 华为健康(H2)卡片扩展 */
+.data-card-actions { display: flex; align-items: center; }
+.data-card-btn { flex-shrink: 0; margin-left: 16rpx; padding: 0 24rpx; height: 56rpx; line-height: 56rpx; border-radius: 28rpx; font-size: calc(24rpx * var(--font-scale, 1)); background: $brand-primary; color: $app-surface; border: none; }
+.data-card-btn--ghost { background: transparent; color: $brand-primary; border: 1rpx solid $brand-primary; }
+.data-card-badge { display: inline-block; margin-left: 8rpx; padding: 0 12rpx; border-radius: 16rpx; font-size: calc(18rpx * var(--font-scale, 1)); font-weight: normal; color: #b26a00; background: #fff3d6; vertical-align: middle; }
 .data-card-assessment { flex-direction: column; align-items: stretch; padding: 24rpx; }
 .data-card-head { display: flex; align-items: center; margin-bottom: 16rpx; }
 .data-card-subtitle { font-size: calc(22rpx * var(--font-scale, 1)); color: $facade-text-muted; margin-left: 12rpx; }

+ 14 - 0
cfc-frontend/utils/api.js

@@ -3661,3 +3661,17 @@ export const toggleIndicatorFavorite = (params) => request('/api/indicator/favor
 export const listIndicatorFavorites = (params) => request('/api/indicator/favorite/list', 'POST', params || {}, { _skipDedup: true, _noToast: true })
 /** 移除收藏:{ memberId, sourceType, definitionId } → { definitionId, removed } */
 export const removeIndicatorFavorite = (params) => request('/api/indicator/favorite/remove', 'POST', params || {}, { _skipDedup: true, _noToast: true })
+
+// ===================== 华为运动健康(H1,契约 §3;docs/2026-11-18-华为运动健康小程序端接入契约)=====================
+// 与小米通道并存;token 仅后端持有,不落小程序。authUrl 已由后端拼好(URL 形式 scope 已 encode),
+// 前端不得自行拼 scope;mock 分支判据 = authUrl 不含 oauth-login.cloud.huawei.com(不触发 web-view)。
+/** 获取授权 URL:{memberId?, scope?} → { authUrl, memberId, scope, generateAt } */
+export const huaweiAuthUrl = (data) => request('/api/huawei-health/auth-url', 'POST', data || {})
+/** 授权回调 code 换 token:{code, memberId?} → { bound, status, expiresAt } */
+export const huaweiCallback = (data) => request('/api/huawei-health/callback', 'POST', data || {})
+/** 触发同步:{memberId?, dataType?}(空=全量)→ { syncAt, result | results } */
+export const huaweiSync = (data) => request('/api/huawei-health/sync', 'POST', data || {})
+/** 撤销授权:{memberId?} → { revoked } */
+export const huaweiRevoke = (data) => request('/api/huawei-health/revoke', 'POST', data || {})
+/** 绑定/状态查询:{memberId?} → { bound, channel, mock, configured, expiresAt, scope } */
+export const huaweiStatus = (data) => request('/api/huawei-health/status', 'POST', data || {})

+ 58 - 0
cfc-web/public/huawei-auth.html

@@ -0,0 +1,58 @@
+<!DOCTYPE html>
+<html lang="zh-CN">
+<head>
+  <meta charset="UTF-8">
+  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
+  <title>连接华为运动健康</title>
+  <style>
+    * { margin: 0; padding: 0; box-sizing: border-box; }
+    body { font-family: -apple-system, BlinkMacSystemFont, "PingFang SC", "Microsoft YaHei", sans-serif; background: #F8F8F8; display: flex; align-items: center; justify-content: center; min-height: 100vh; }
+    .card { background: #fff; border-radius: 16px; padding: 32px 24px; width: 88%; max-width: 380px; text-align: center; box-shadow: 0 2px 12px rgba(0,0,0,0.06); }
+    .icon { font-size: 44px; margin-bottom: 12px; }
+    h1 { font-size: 18px; font-weight: 700; color: #333; margin-bottom: 8px; }
+    .desc { font-size: 14px; color: #999; margin-bottom: 20px; line-height: 1.6; }
+    .btn { display: inline-block; background: #F97316; color: #fff; border: none; border-radius: 24px; padding: 10px 32px; font-size: 14px; cursor: pointer; text-decoration: none; }
+    .btn:hover { opacity: 0.9; }
+    .error { color: #E53E3E; font-size: 13px; margin-top: 12px; display: none; }
+  </style>
+</head>
+<body>
+  <div class="card">
+    <div class="icon">⌚</div>
+    <h1>连接华为运动健康</h1>
+    <p class="desc" id="desc">正在跳转华为账号授权…</p>
+    <a class="btn" id="fallback" style="display:none" href="javascript:void(0)">若未自动跳转请点此</a>
+    <p class="error" id="error">授权页加载失败,请返回重试</p>
+  </div>
+  <script>
+    // §5.1:入口 /huawei-auth.html?memberId=<id>&authUrl=<encodeURIComponent(authUrl)>
+    // 读 query 后 location.replace(authUrl) 跳华为授权(authUrl 由前端调接口1获取后拼在本页 query)。
+    // 本页不出现任何华为账号/密码输入框(防钓鱼观感与合规风险)。
+    (function() {
+      function getParam(name) {
+        var m = location.search.match(new RegExp('[?&]' + name + '=([^&]*)'))
+        return m ? decodeURIComponent(m[1].replace(/\+/g, '%20')) : ''
+      }
+      var authUrl = getParam('authUrl')
+      var fallback = document.getElementById('fallback')
+      var error = document.getElementById('error')
+      var desc = document.getElementById('desc')
+      function jump(url) {
+        // 小屏 web-view 内 location.replace 跳转 OAuth
+        location.replace(url)
+      }
+      fallback.addEventListener('click', function() {
+        if (authUrl) { desc.textContent = '正在跳转华为账号授权…'; jump(authUrl) }
+      })
+      if (authUrl) {
+        desc.textContent = '正在跳转华为账号授权…'
+        jump(authUrl)
+      } else {
+        desc.textContent = '缺少授权参数'
+        error.style.display = 'block'
+        fallback.style.display = 'none'
+      }
+    })();
+  </script>
+</body>
+</html>

+ 87 - 0
cfc-web/public/huawei-cb.html

@@ -0,0 +1,87 @@
+<!DOCTYPE html>
+<html lang="zh-CN">
+<head>
+  <meta charset="UTF-8">
+  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
+  <title>华为运动健康授权结果</title>
+  <style>
+    * { margin: 0; padding: 0; box-sizing: border-box; }
+    body { font-family: -apple-system, BlinkMacSystemFont, "PingFang SC", "Microsoft YaHei", sans-serif; background: #F8F8F8; display: flex; align-items: center; justify-content: center; min-height: 100vh; }
+    .card { background: #fff; border-radius: 16px; padding: 32px 24px; width: 88%; max-width: 380px; text-align: center; box-shadow: 0 2px 12px rgba(0,0,0,0.06); }
+    .icon { font-size: 44px; margin-bottom: 12px; }
+    h1 { font-size: 18px; font-weight: 700; color: #333; margin-bottom: 8px; }
+    .desc { font-size: 14px; color: #999; margin-bottom: 20px; line-height: 1.6; }
+    .btn { display: inline-block; background: #F97316; color: #fff; border: none; border-radius: 24px; padding: 10px 32px; font-size: 14px; cursor: pointer; text-decoration: none; }
+    .btn:hover { opacity: 0.9; }
+  </style>
+</head>
+<body>
+  <div class="card">
+    <div class="icon" id="icon">⏳</div>
+    <h1 id="title">处理中…</h1>
+    <p class="desc" id="desc">正在完成华为账号授权…</p>
+    <a class="btn" id="btn" style="display:none" href="javascript:void(0)">返回重试</a>
+  </div>
+  <script>
+    // §5.2 入口:/huawei-cb.html?code=<code>&state=<memberId>
+    // 解析 code/state → POST /api/huawei-health/callback → 三态渲染:
+    //   成功「已授权,请返回小程序」/ 失败错误文案+重试 / 无 code 兜底「授权未完成,请返回重试」。
+    // 服务端 memberId 与 JWT 归属的最终校验在后端接口2完成,本页只做类型/长度基本校验。
+    (function() {
+      function getParam(name) {
+        var m = location.search.match(new RegExp('[?&]' + name + '=([^&]*)'))
+        return m ? decodeURIComponent(m[1].replace(/\+/g, '%20')) : ''
+      }
+      var API_BASE = '/api'
+      var code = getParam('code')
+      var state = getParam('state')
+      var icon = document.getElementById('icon')
+      var title = document.getElementById('title')
+      var desc = document.getElementById('desc')
+      var btn = document.getElementById('btn')
+      function showError(text) {
+        icon.textContent = '⚠️'
+        title.textContent = '授权失败'
+        desc.textContent = text
+        btn.style.display = 'inline-block'
+        btn.textContent = '返回重试'
+        btn.addEventListener('click', function() { location.href = '/huawei-auth.html' })
+      }
+      if (!code) {
+        // 参数缺失(无 code):兜底文案
+        icon.textContent = 'ℹ️'
+        title.textContent = '授权未完成'
+        desc.textContent = '授权未完成,请返回重试'
+        btn.style.display = 'inline-block'
+        btn.textContent = '返回重试'
+        btn.addEventListener('click', function() { location.href = '/huawei-auth.html' })
+        return
+      }
+      var memberId = null
+      var n = parseInt(state, 10)
+      if (!isNaN(n) && n > 0) { memberId = n }
+      var payload = { code: code }
+      if (memberId) { payload.memberId = memberId }
+      fetch(API_BASE + '/huawei-health/callback', {
+        method: 'POST',
+        headers: { 'Content-Type': 'application/json' },
+        body: JSON.stringify(payload)
+      }).then(function(res) { return res.json() })
+        .then(function(result) {
+          if (result && result.code === 200) {
+            icon.textContent = '✅'
+            title.textContent = '已授权,请返回小程序'
+            desc.textContent = '绑定成功,数据仅用于家庭健康档案展示'
+            // ≥3s 自动尝试关闭引导(小程序 web-view 用户手动返回亦可)
+            setTimeout(function() {
+              if (location.href.indexOf('weixin') >= 0) { try { window.close() } catch (e) {} }
+            }, 3000)
+          } else {
+            showError((result && result.message) || '绑定失败,请重新授权')
+          }
+        })
+        .catch(function() { showError('网络异常,请重新授权') })
+    })();
+  </script>
+</body>
+</html>