Преглед изворни кода

feat(huawei.health.miniapp) S-cfc-431: 华为运动健康小程序端接入契约后端小修

- HuaweiAuthService: +validateScope() fail-fast; generateAuthUrl mock/real 双分支
  (mock 返回非华为授权域名占位、real 追加 access_type=offline);
  exchangeCode/refreshToken real 分支改 form-urlencoded; @Value scope 默认 URL 化
- HuaweiHealthController.status(): 透传 expiresAt/scope(H3 mock 判据)
- application.yml: huawei.health.scope 默认改为 6 项 URL 形式
- 小程序 health-main: 华为绑定/同步卡片(H2)+ loadHuaweiStatus/bindHuawei/syncHuawei
- utils/api.js: +huaweiAuthUrl/callback/sync/revoke/status 5 方法(H1)
- cfc-web/public: 新增 huawei-auth.html / huawei-cb.html H5 中转页(H5-1/H5-2)

单测 HuaweiHealthMiniappContractTest: 10 失败 -> 19/19 全绿
E2E Test Bot пре 3 часа
родитељ
комит
34db2effbd

+ 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("channel", statusJson.getString("channel"));
         data.put("mock", statusJson.getBoolean("mock"));
         data.put("mock", statusJson.getBoolean("mock"));
         data.put("configured", statusJson.getBoolean("configured"));
         data.put("configured", statusJson.getBoolean("configured"));
+        // §3 接口 5:补透传 expiresAt / scope(statusJson 已含两键),供前端卡片与 mock 分支判据展示
+        data.put("expiresAt", statusJson.get("expiresAt"));
+        data.put("scope", statusJson.getString("scope"));
         return Result.success(data);
         return Result.success(data);
     }
     }
 }
 }

+ 61 - 17
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.MediaType;
 import org.springframework.http.ResponseEntity;
 import org.springframework.http.ResponseEntity;
 import org.springframework.stereotype.Service;
 import org.springframework.stereotype.Service;
+import org.springframework.util.LinkedMultiValueMap;
+import org.springframework.util.MultiValueMap;
 import org.springframework.web.client.RestTemplate;
 import org.springframework.web.client.RestTemplate;
 
 
 import javax.annotation.Resource;
 import javax.annotation.Resource;
@@ -26,6 +28,14 @@ public class HuaweiAuthService {
 
 
     private static final Logger log = LoggerFactory.getLogger(HuaweiAuthService.class);
     private static final Logger log = LoggerFactory.getLogger(HuaweiAuthService.class);
 
 
+    /**
+     * 华为 Health Service Kit 云侧 URL 形式 scope 前缀(H-B3 fail-fast 锚点)。
+     *
+     * <p>华为 OAuth scope 是 URL 形式(如 {@code https://www.huawei.com/healthkit/step.read}),
+     * 简写 scope(step,heart_rate...)华为不识别 → 授权回调失败。real 模式启动前校验缺失则 fail-fast。</p>
+     */
+    public static final String SCOPE_HUAWEI_URL_PREFIX = "https://www.huawei.com/healthkit/";
+
     @Resource
     @Resource
     private HuaweiHealthTokenMapper tokenMapper;
     private HuaweiHealthTokenMapper tokenMapper;
 
 
@@ -53,7 +63,7 @@ public class HuaweiAuthService {
     @Value("${huawei.health.revoke-url:https://health-api.cloud.huawei.com/oauth/v1/token/revoke}")
     @Value("${huawei.health.revoke-url:https://health-api.cloud.huawei.com/oauth/v1/token/revoke}")
     private String revokeUrl;
     private String revokeUrl;
 
 
-    @Value("${huawei.health.scope:step,distance,heart_rate,sleep,body_weight}")
+    @Value("${huawei.health.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}")
     private String scope;
     private String scope;
 
 
     @Value("${huawei.health.mock-enabled:true}")
     @Value("${huawei.health.mock-enabled:true}")
@@ -66,18 +76,50 @@ public class HuaweiAuthService {
      * 
      * 
      * @param memberId 家庭成员 ID(作为 state 原样带回,防 CSRF)
      * @param memberId 家庭成员 ID(作为 state 原样带回,防 CSRF)
      * @param scope    授权范围;为空时使用默认 scope
      * @param scope    授权范围;为空时使用默认 scope
-     * @return 授权 URL(real 模式返回华为账号服务 OAuth2 端点)
+     * @return 授权 URL(real 模式返回华为账号服务 OAuth2 端点,带 access_type=offline;
+     *         mock 模式返回非华为授权域名占位 URL,保证前端判为 mock 分支、不触发 web-view)
      */
      */
     public String generateAuthUrl(Long memberId, String scope) {
     public String generateAuthUrl(Long memberId, String scope) {
-        String effectiveScope = (scope == null || scope.isEmpty()) ? this.scope : scope;
         if (memberId == null) {
         if (memberId == null) {
             return "";
             return "";
         }
         }
+        String effectiveScope = (scope == null || scope.isEmpty()) ? this.scope : scope;
+        // H3 硬约束:mock 通道返回非 oauth-login.cloud.huawei.com 域名占位 URL(前端判据为授权域名,
+        // mock 分支不得触发 web-view 白屏)
+        if (mockEnabled) {
+            return "https://mock.healthkit.etotem.com/oauth/authorize"
+                    + "?response_type=code&client_id=" + encode(clientId)
+                    + "&redirect_uri=" + encode(redirectUri)
+                    + "&scope=" + encode(effectiveScope)
+                    + "&state=" + memberId
+                    + "&access_type=offline";
+        }
+        // H-B3:real 模式 scope 必须为 URL 形式(fail-fast,缺失立即报错)
+        validateScope(effectiveScope);
+        // H-B1:追加 access_type=offline(换取 refresh_token 必需,否则 2h 后无法续期)
         return authorizeUrl
         return authorizeUrl
                 + "?response_type=code&client_id=" + encode(clientId)
                 + "?response_type=code&client_id=" + encode(clientId)
                 + "&redirect_uri=" + encode(redirectUri)
                 + "&redirect_uri=" + encode(redirectUri)
                 + "&scope=" + encode(effectiveScope)
                 + "&scope=" + encode(effectiveScope)
-                + "&state=" + memberId;
+                + "&state=" + memberId
+                + "&access_type=offline";
+    }
+
+    /**
+     * real 模式 scope 前置校验(H-B3 fail-fast)。
+     *
+     * <p>华为 OAuth scope 必须是 URL 形式(含 {@link #SCOPE_HUAWEI_URL_PREFIX} 前缀,空格分隔多值),
+     * 简写 scope(step,heart_rate...)华为不识别 → 授权回调失败。</p>
+     *
+     * @param scopeValue 待校验的 scope 字符串
+     * @throws IllegalStateException scope 不含 URL 前缀时立即抛出(fail-fast 并给出明确报错)
+     */
+    public void validateScope(String scopeValue) {
+        if (!mockEnabled && (scopeValue == null || !scopeValue.contains(SCOPE_HUAWEI_URL_PREFIX))) {
+            throw new IllegalStateException("华为 real 模式 scope 必须为 URL 形式(含 " + SCOPE_HUAWEI_URL_PREFIX
+                    + " 前缀,空格分隔多值),当前取到:" + scopeValue
+                    + "。请用环境变量 HUAWEI_SCOPE 注入 URL 形式 scope 后重启。");
+        }
     }
     }
 
 
     // ==================== code 换 token ====================
     // ==================== code 换 token ====================
@@ -106,15 +148,16 @@ public class HuaweiAuthService {
             log.info("[Mock] 华为 OAuth code 换 token memberId={} code={}", memberId, code);
             log.info("[Mock] 华为 OAuth code 换 token memberId={} code={}", memberId, code);
         } else {
         } else {
             // real:OAuth2 授权码流程,向 {tokenUrl} POST 换取访问/刷新令牌(Health Service Kit 云侧)。
             // real:OAuth2 授权码流程,向 {tokenUrl} POST 换取访问/刷新令牌(Health Service Kit 云侧)。
+            // H-B2:华为 token 端点要求 application/x-www-form-urlencoded 表单体(JSON body 被拒 400)。
             try {
             try {
                 HttpHeaders headers = new HttpHeaders();
                 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,
                 ResponseEntity<Map> resp = restTemplate.postForEntity(tokenUrl,
                         new HttpEntity<>(body, headers), Map.class);
                         new HttpEntity<>(body, headers), Map.class);
                 if (!resp.getStatusCode().is2xxSuccessful() || resp.getBody() == null) {
                 if (!resp.getStatusCode().is2xxSuccessful() || resp.getBody() == null) {
@@ -197,14 +240,15 @@ public class HuaweiAuthService {
             log.info("[Mock] 华为 OAuth 刷新 token memberId={}", memberId);
             log.info("[Mock] 华为 OAuth 刷新 token memberId={}", memberId);
         } else {
         } else {
             // real:OAuth2 刷新流程,向 {tokenUrl} POST grant_type=refresh_token 换取新访问令牌。
             // real:OAuth2 刷新流程,向 {tokenUrl} POST grant_type=refresh_token 换取新访问令牌。
+            // H-B2:token 端点要求 application/x-www-form-urlencoded 表单体。
             try {
             try {
                 HttpHeaders headers = new HttpHeaders();
                 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,
                 ResponseEntity<Map> resp = restTemplate.postForEntity(tokenUrl,
                         new HttpEntity<>(body, headers), Map.class);
                         new HttpEntity<>(body, headers), Map.class);
                 if (!resp.getStatusCode().is2xxSuccessful() || resp.getBody() == null) {
                 if (!resp.getStatusCode().is2xxSuccessful() || resp.getBody() == null) {

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

@@ -271,8 +271,8 @@ huawei:
     authorize-url: ${HUAWEI_AUTHORIZE_URL:https://oauth-login.cloud.huawei.com/oauth2/v3/authorize}
     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}
     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}
     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(URL 形式空格分隔;real 模式必须为 URL 形式,简写华为不识别)
+    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,仅后端持有;生产环境必须覆盖为强随机密钥)
     # token 落库加密密钥(AES-128,仅后端持有;生产环境必须覆盖为强随机密钥)
     encrypt-key: ${HUAWEI_TOKEN_ENCRYPT_KEY:huaweiDevKey1234}
     encrypt-key: ${HUAWEI_TOKEN_ENCRYPT_KEY:huaweiDevKey1234}
     # 云侧数据接口 base(Health Service Kit 数据读取,凭证批复后校准)
     # 云侧数据接口 base(Health Service Kit 数据读取,凭证批复后校准)

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

@@ -221,6 +221,26 @@
           </view>
           </view>
           <text class="data-card-arrow">›</text>
           <text class="data-card-arrow">›</text>
         </view>
         </view>
+
+        <!-- 运动手环 · 华为健康(H2 契约卡片):
+             未绑定=绑定按钮+用途说明;已绑定=摘要+mock 角标+手动同步按钮+合规常驻文案。
+             数据源 POST /api/huawei-health/status(huaweiStatus);mock/real 分支由 authUrl 域名判据驱动,
+             前端不自行拼 scope(§6-2)。 -->
+        <view class="data-card data-card-huawei">
+          <view class="data-card-head">
+            <text class="data-card-title">运动手环 · 华为健康</text>
+            <text class="data-card-subtitle" v-if="huaweiStatus.mock">模拟模式</text>
+          </view>
+          <view v-if="!huaweiStatus.bound">
+            <text class="data-card-desc">读取步数/距离/心率/睡眠/体重/身高,仅用于家庭健康档案与趋势分析。</text>
+            <button v-if="huaweiBusy" class="quiz-btn" disabled>绑定中…</button>
+            <button v-else class="quiz-btn" @click="bindHuawei">绑定华为运动健康</button>
+          </view>
+          <view v-else>
+            <text class="data-card-desc">数据来自华为运动健康{{ huaweiStatus.mock ? '(mock 端)' : '' }} · 撤销授权即停止同步。</text>
+            <button class="quiz-btn" @click="syncHuawei">手动同步</button>
+          </view>
+        </view>
       </view>
       </view>
 
 
       <view class="section section-data-view">
       <view class="section section-data-view">
@@ -326,7 +346,10 @@ export default {
       loginSheetVisible: false,
       loginSheetVisible: false,
       // 统一维度注册中心是否就绪(成功取到 tree 后由 ensureDimensionRegistry 置位)
       // 统一维度注册中心是否就绪(成功取到 tree 后由 ensureDimensionRegistry 置位)
       // 未就绪时主页雷达回落硬编码兜底,保证后端未上线 / 接口异常时页面不崩
       // 未就绪时主页雷达回落硬编码兜底,保证后端未上线 / 接口异常时页面不崩
-      registryReady: false
+      registryReady: false,
+      // 华为运动健康卡(H2):绑定/通道状态 + mock 角标 + 绑定中标志
+      huaweiStatus: { bound: false, mock: false, expiresAt: '', scope: '' },
+      huaweiBusy: false
     }
     }
   },
   },
   computed: {
   computed: {
@@ -449,6 +472,7 @@ export default {
       this.loadHealthData()
       this.loadHealthData()
       this.loadPlanList()
       this.loadPlanList()
       this.loadPendingSurveys()
       this.loadPendingSurveys()
+      this.loadHuaweiStatus()
       // 触发统一维度注册中心树拉取(主页雷达配置驱动取数;失败则回落硬编码兜底)
       // 触发统一维度注册中心树拉取(主页雷达配置驱动取数;失败则回落硬编码兜底)
       var self = this
       var self = this
       ensureDimensionRegistry().then(function() {
       ensureDimensionRegistry().then(function() {
@@ -745,6 +769,76 @@ export default {
       var map = { weekly: '每周调研', biweekly: '双周调研', monthly: '每月调研' }
       var map = { weekly: '每周调研', biweekly: '双周调研', monthly: '每月调研' }
       return map[cycleType] || '定期调研'
       return map[cycleType] || '定期调研'
     },
     },
+    // 华为运动健康卡(H2):拉取绑定/通道状态(含 expiresAt/scope,mock 角标数据源)
+    loadHuaweiStatus: function() {
+      var self = this
+      var api = require('../../utils/api.js')
+      var memberId = uni.getStorageSync('currentChildId') || uni.getStorageSync('currentMemberId') || ''
+      api.huaweiStatus(memberId || '').then(function(res) {
+        if (res && res.code === 200 && res.data) {
+          var d = res.data
+          self.huaweiStatus = {
+            bound: !!d.bound,
+            mock: !!d.mock,
+            expiresAt: d.expiresAt || '',
+            scope: d.scope || ''
+          }
+        }
+      }).catch(function() {
+        self.huaweiStatus = { bound: false, mock: false, expiresAt: '', scope: '' }
+      })
+    },
+    // 绑定华为运动健康(H3):取 authUrl → 域名判据分流 mock/real。
+    // mock:authUrl 非华为授权域名 → 直接 code=mock-code 走回调换 token(全程不触发 web-view);
+    // real:authUrl 含 oauth-login.cloud.huawei.com → 需在 web-view 业务域名下打开 H5 中转授权页
+    //(huawei-auth.html,随 huawei-auth/cb 两页一并部署,联调前由前端页面承接 web-view 宿主)。
+    bindHuawei: function() {
+      var self = this
+      var api = require('../../utils/api.js')
+      var memberId = uni.getStorageSync('currentChildId') || uni.getStorageSync('currentMemberId') || ''
+      if (self.huaweiBusy) return
+      self.huaweiBusy = true
+      api.huaweiAuthUrl(memberId || '', '').then(function(res) {
+        self.huaweiBusy = false
+        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) {
+          uni.showToast({ title: '请完成华为授权后返回刷新', icon: 'none' })
+          return
+        }
+        // mock 分支硬约束:不得打开 web-view
+        api.huaweiCallback('mock-code', memberId || '').then(function(cb) {
+          if (cb && cb.code === 200 && cb.data && cb.data.bound) {
+            uni.showToast({ title: '华为健康已绑定', icon: 'success' })
+            self.loadHuaweiStatus()
+          } else {
+            uni.showToast({ title: '绑定失败,请重试', icon: 'none' })
+          }
+        }).catch(function() {
+          uni.showToast({ title: '绑定失败,请重试', icon: 'none' })
+        })
+      }).catch(function() {
+        self.huaweiBusy = false
+        uni.showToast({ title: '获取授权链接失败', icon: 'none' })
+      })
+    },
+    // 手动同步(H4):POST /api/huawei-health/sync,全量 5 类
+    syncHuawei: function() {
+      var api = require('../../utils/api.js')
+      var memberId = uni.getStorageSync('currentChildId') || uni.getStorageSync('currentMemberId') || ''
+      api.huaweiSync(memberId || '', '').then(function(res) {
+        if (res && res.code === 200) {
+          uni.showToast({ title: '同步完成', icon: 'success' })
+        } else {
+          uni.showToast({ title: (res && res.message) || '同步失败', icon: 'none' })
+        }
+      }).catch(function() {
+        uni.showToast({ title: '同步失败', icon: 'none' })
+      })
+    },
     goSurveyFill: function(item) {
     goSurveyFill: function(item) {
       if (!item || !item.templateId) return
       if (!item || !item.templateId) return
       var url = '/pages/health/survey-questionnaire?templateId=' + item.templateId +
       var url = '/pages/health/survey-questionnaire?templateId=' + item.templateId +

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

@@ -3137,6 +3137,28 @@ export const getHealthStatus = (memberId) => request('/api/health-status/get', '
 export const saveHealthStatus = (data) => request('/api/health-status/save', 'POST', data)
 export const saveHealthStatus = (data) => request('/api/health-status/save', 'POST', data)
 export const saveHealthSignature = (memberId, signature) => request('/api/health-status/signature', 'POST', { memberId: memberId, signature: signature })
 export const saveHealthSignature = (memberId, signature) => request('/api/health-status/signature', 'POST', { memberId: memberId, signature: signature })
 
 
+// ===== 华为运动健康(OAuth 授权 + 数据同步,能力键 huawei.health.miniapp)=====
+// 契约见 docs/2026-11-18-华为运动健康小程序端接入契约-H1-H4.md §3(全部 @PostMapping / JWT 拦截)
+// ⚠️ §6-2:scope 须由后端拼好(URL 形式已 encode),前端不得自行拼接或改写 scope 参数
+export const huaweiAuthUrl = (memberId, scope) => request('/api/huawei-health/auth-url', 'POST', {
+  memberId: memberId || undefined,
+  scope: scope || undefined
+})
+export const huaweiCallback = (code, memberId) => request('/api/huawei-health/callback', 'POST', {
+  code: code,
+  memberId: memberId || undefined
+})
+export const huaweiSync = (memberId, dataType) => request('/api/huawei-health/sync', 'POST', {
+  memberId: memberId || undefined,
+  dataType: dataType || undefined
+})
+export const huaweiRevoke = (memberId) => request('/api/huawei-health/revoke', 'POST', {
+  memberId: memberId || undefined
+})
+export const huaweiStatus = (memberId) => request('/api/huawei-health/status', 'POST', {
+  memberId: memberId || undefined
+})
+
 // ===== 饮食模块 =====
 // ===== 饮食模块 =====
 export const getDietPreferences = (data) => request('/api/diet/preferences/current-member', 'POST', data || {})
 export const getDietPreferences = (data) => request('/api/diet/preferences/current-member', 'POST', data || {})
 export const saveDietPreferences = (data) => request('/api/diet/preferences/save', 'POST', data)
 export const saveDietPreferences = (data) => request('/api/diet/preferences/save', 'POST', data)

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

@@ -0,0 +1,61 @@
+<!DOCTYPE html>
+<html lang="zh-CN">
+<head>
+<meta charset="UTF-8">
+<meta name="viewport" content="width=device-width, initial-scale=1.0">
+<title>连接华为运动健康</title>
+<style>
+  * { margin: 0; padding: 0; box-sizing: border-box; }
+  body { font-family: -apple-system, "PingFang SC", "Microsoft YaHei", sans-serif; background: #f7f8fa; display: flex; align-items: center; justify-content: center; min-height: 100vh; }
+  .wrap { background: #fff; border-radius: 16px; padding: 40px 32px; width: 88%; max-width: 420px; text-align: center; box-shadow: 0 2px 12px rgba(0,0,0,.06); }
+  h1 { font-size: 20px; color: #1f2329; margin-bottom: 12px; }
+  .sub { font-size: 14px; color: #8a919f; margin-bottom: 28px; line-height: 1.6; }
+  .loading { color: #5f6b7a; font-size: 15px; margin-bottom: 16px; }
+  .btn { display: inline-block; background: #4259ff; color: #fff; border: none; border-radius: 8px; padding: 12px 28px; font-size: 15px; cursor: pointer; }
+  .btn:hover { opacity: .9; }
+  .err { color: #e5484d; font-size: 14px; margin-top: 12px; line-height: 1.6; }
+  .hide { display: none; }
+</style>
+</head>
+<body>
+<div class="wrap">
+  <h1>连接华为运动健康</h1>
+  <p class="sub">正在跳转华为账号授权页,请在弹出的页面中完成授权。</p>
+  <p id="loading" class="loading">加载中…</p>
+  <button id="fallback" class="btn hide" onclick="jump()">若未自动跳转请点此</button>
+  <p id="err" class="err hide"></p>
+</div>
+<script>
+  // H5 中转授权页(huawei-auth.html):读 query 后 location.replace(authUrl) 跳华为授权。
+  // authUrl 由小程序调 POST /api/huawei-health/auth-url 获取后拼在本页 query(real 分支)。
+  // 页面内不含任何密码输入框(合规/防钓鱼观感)。
+  function parseQuery() {
+    var qs = window.location.search.replace(/^\?/, '')
+    var out = {}
+    if (!qs) return out
+    var parts = qs.split('&')
+    for (var i = 0; i < parts.length; i++) {
+      var kv = parts[i].split('=')
+      if (kv[0]) out[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1] || '')
+    }
+    return out
+  }
+
+  var q = parseQuery()
+  var authUrl = q.authUrl || ''
+
+  function jump() {
+    if (!authUrl) {
+      document.getElementById('loading').classList.add('hide')
+      document.getElementById('err').classList.remove('hide')
+      document.getElementById('err').textContent = '缺少授权链接(authUrl),请返回小程序重新发起绑定'
+      return
+    }
+    window.location.replace(authUrl)
+  }
+
+  document.getElementById('fallback').classList.remove('hide')
+  jump()
+</script>
+</body>
+</html>

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

@@ -0,0 +1,97 @@
+<!DOCTYPE html>
+<html lang="zh-CN">
+<head>
+<meta charset="UTF-8">
+<meta name="viewport" content="width=device-width, initial-scale=1.0">
+<title>华为运动健康授权结果</title>
+<style>
+  * { margin: 0; padding: 0; box-sizing: border-box; }
+  body { font-family: -apple-system, "PingFang SC", "Microsoft YaHei", sans-serif; background: #f7f8fa; display: flex; align-items: center; justify-content: center; min-height: 100vh; }
+  .wrap { background: #fff; border-radius: 16px; padding: 40px 32px; width: 88%; max-width: 420px; text-align: center; box-shadow: 0 2px 12px rgba(0,0,0,.06); }
+  h1 { font-size: 20px; color: #1f2329; margin-bottom: 12px; }
+  .icon { font-size: 40px; margin-bottom: 12px; }
+  .status { font-size: 15px; color: #4b5563; line-height: 1.7; margin-bottom: 24px; }
+  .btn { display: inline-block; background: #4259ff; color: #fff; border: none; border-radius: 8px; padding: 12px 28px; font-size: 15px; cursor: pointer; }
+  .btn:hover { opacity: .9; }
+  .btn-plain { background: #f1f3f5; color: #1f2329; margin-left: 8px; }
+  .hide { display: none; }
+</style>
+</head>
+<body>
+<div class="wrap">
+  <div id="ic" class="icon">⏳</div>
+  <h1 id="title">授权处理中</h1>
+  <p id="status" class="status">正在确认华为运动健康授权状态…</p>
+  <button id="retry" class="btn hide" onclick="run()">重新授权</button>
+  <button id="close" class="btn btn-plain hide" onclick="tryClose()">关闭本页</button>
+  <p class="status" id="extra" style="display:none"></p>
+</div>
+<script>
+  // H5 中转回调页(huawei-cb.html):解析 code/state → POST /api/huawei-health/callback → 三态渲染。
+  // state 校验:华为 OAuth 原样带回 memberId,本页仅做类型/长度基本校验;
+  // 服务端 memberId 与 JWT 归属的最终校验在后端接口完成(前端不得仅凭 query 决定绑定对象)。
+
+  function parseQuery() {
+    var qs = window.location.search.replace(/^\?/, '')
+    var out = {}
+    if (!qs) return out
+    var parts = qs.split('&')
+    for (var i = 0; i < parts.length; i++) {
+      var kv = parts[i].split('=')
+      if (kv[0]) out[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1] || '')
+    }
+    return out
+  }
+
+  function render(icon, title, statusText, showRetry) {
+    document.getElementById('ic').textContent = icon
+    document.getElementById('title').textContent = title
+    document.getElementById('status').textContent = statusText
+    document.getElementById('retry').classList.toggle('hide', !showRetry)
+    document.getElementById('close').classList.remove('hide')
+    if (icon === '✅' && showRetry) {
+      // 成功态:≥3s 自动尝试关闭引导
+      setTimeout(tryClose, 3000)
+    }
+  }
+
+  function tryClose() {
+    // 小程序 web-view 场景可由宿主通过 onPostMessage 关闭;浏览器环境降级为隐藏
+    try { document.title = '已授权,请返回小程序' } catch (e) { /* ignore */ }
+  }
+
+  function run() {
+    var q = parseQuery()
+    var code = q.code || ''
+    var state = q.state || ''
+    var memberId = /^\d+$/.test(state) ? parseInt(state, 10) : NaN
+
+    if (!code) {
+      render('⚠️', '授权未完成', '未获取到授权码,请返回小程序重试。', true)
+      return
+    }
+    if (!memberId) {
+      render('⚠️', '参数异常', '授权回调缺少有效的成员标识(state),请返回小程序重试。', true)
+      return
+    }
+
+    var body = JSON.stringify({ code: code, memberId: memberId })
+    fetch('/api/huawei-health/callback', {
+      method: 'POST',
+      headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + (window._cfcToken || '') },
+      body: body
+    }).then(function(res) { return res.json() }).then(function(data) {
+      if (data && data.code === 200 && data.data && data.data.bound) {
+        render('✅', '已授权,请返回小程序', '华为运动健康已成功绑定,请返回小程序查看。', false)
+      } else {
+        render('❌', '授权失败', (data && data.message) || '绑定失败,请重新授权后重试。', true)
+      }
+    }).catch(function() {
+      render('❌', '网络异常', '无法连接服务,请重新授权后重试。', true)
+    })
+  }
+
+  run()
+</script>
+</body>
+</html>