Procházet zdrojové kódy

feat(分享): 课程详情页内分享入口 + 我的海报改为合成海报

liaoxg před 1 měsícem
rodič
revize
85f5ec7ad5

+ 5 - 34
train-backend/src/main/java/com/train/controller/InviteController.java

@@ -1,6 +1,5 @@
 package com.train.controller;
 
-import com.alibaba.fastjson.JSONObject;
 import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
 import com.train.cfc.entity.CfcUser;
 import com.train.cfc.mapper.CfcUserMapper;
@@ -15,17 +14,12 @@ import io.swagger.v3.oas.annotations.Operation;
 import io.swagger.v3.oas.annotations.tags.Tag;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Value;
-import org.springframework.http.HttpEntity;
-import org.springframework.http.HttpHeaders;
-import org.springframework.http.MediaType;
-import org.springframework.http.ResponseEntity;
 import org.springframework.util.StringUtils;
 import org.springframework.web.bind.annotation.PostMapping;
 import org.springframework.web.bind.annotation.RequestAttribute;
 import org.springframework.web.bind.annotation.RequestBody;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RestController;
-import org.springframework.web.client.RestTemplate;
 
 import javax.annotation.Resource;
 import java.io.File;
@@ -58,17 +52,9 @@ public class InviteController {
     @Resource
     private CfcReferralSyncService cfcReferralSyncService;
 
-    @Value("${wechat.test-mode}")
-    private boolean testMode;
-
     @Value("${upload.base-dir}")
     private String baseDir;
 
-    @Value("${wechat.qrcode-url:https://api.weixin.qq.com/wxa/getwxacodeunlimit}")
-    private String qrcodeUrl;
-
-    private final RestTemplate restTemplate = new RestTemplate();
-
     /**
      * 我的专属海报 + 邀请码 + 分享文案。
      * @return {inviteCode, posterUrl, sharePath, shareText}
@@ -116,27 +102,12 @@ public class InviteController {
      * 图片字节缓存到本地上传目录,返回可访问 URL。test-mode 或失败返回空串(前端降级本地海报)。
      */
     private String generatePosterCode(String inviteCode) {
-        if (testMode) {
+        // 统一走 WechatService:test-mode/接口失败返回 null,由前端降级为本地海报
+        byte[] bytes = wechatService.generateWxacodeBytes(inviteCode, "pages/enroll/list");
+        if (bytes == null || bytes.length == 0) {
             return "";
         }
         try {
-            String accessToken = wechatService.getAccessToken();
-            JSONObject body = new JSONObject();
-            body.put("scene", inviteCode);
-            body.put("page", "pages/enroll/list");
-            body.put("check_path", false);
-            body.put("width", 430);
-            HttpHeaders headers = new HttpHeaders();
-            headers.setContentType(MediaType.APPLICATION_JSON);
-            ResponseEntity<byte[]> response = restTemplate.postForEntity(
-                    qrcodeUrl + "?access_token=" + accessToken,
-                    new HttpEntity<>(body.toJSONString(), headers),
-                    byte[].class);
-            byte[] bytes = response.getBody();
-            if (bytes == null || bytes.length == 0) {
-                log.warn("getwxacodeunlimit 返回空字节,inviteCode={}", inviteCode);
-                return "";
-            }
             File dir = new File(baseDir);
             if (!dir.exists() && !dir.mkdirs()) {
                 log.error("海报目录创建失败: {}", baseDir);
@@ -149,8 +120,8 @@ public class InviteController {
             }
             return "/uploads/" + filename;
         } catch (Exception e) {
-            // 微信接口失败/网络异常:降级为前端本地海报,不阻塞分享
-            log.error("生成小程序码失败,降级本地海报 inviteCode={}", inviteCode, e);
+            // 写盘失败:降级为前端本地海报,不阻塞分享
+            log.error("海报写入失败,降级本地海报 inviteCode={}", inviteCode, e);
             return "";
         }
     }

+ 35 - 0
train-frontend/pages/course/detail.vue

@@ -112,6 +112,16 @@
         </view>
       </view>
     </template>
+
+    <!-- 分享入口:小程序端转发卡片(带 inviteCode),H5 端复制带邀请码链接 -->
+    <view class="share-bar">
+      <!-- #ifdef MP-WEIXIN -->
+      <button class="share-bar-btn" open-type="share">分享给好友</button>
+      <!-- #endif -->
+      <!-- #ifndef MP-WEIXIN -->
+      <button class="share-bar-btn" @click="copyShareLink">复制分享链接</button>
+      <!-- #endif -->
+    </view>
   </view>
 </template>
 
@@ -226,6 +236,28 @@ export default {
       if (c.name) return (c.level || '') + ' · ' + c.name
       return '爱伴·AI之旅|课程详情'
     },
+    /** H5 端复制带邀请码的分享链接(小程序端用 open-type="share" 走 onShareAppMessage) */
+    copyShareLink() {
+      var code = getInviteCode()
+      var link = ''
+      // #ifdef H5
+      if (typeof window !== 'undefined' && window.location) {
+        link = window.location.href
+      }
+      // #endif
+      if (!link) {
+        link = '/pages/course/detail' + (this.courseId ? '?courseId=' + this.courseId : '')
+      }
+      if (code) {
+        link += (link.indexOf('?') > -1 ? '&' : '?') + 'inviteCode=' + code
+      }
+      uni.setClipboardData({
+        data: link,
+        success: function() {
+          uni.showToast({ title: '分享链接已复制', icon: 'success' })
+        }
+      })
+    },
     loadAll() {
       var self = this
       getMyCourse(self.courseId).then(function(resp) {
@@ -382,4 +414,7 @@ export default {
 .nav-item:active { background: #F8FAFC; }
 .nav-icon { font-size: 44rpx; margin-bottom: 8rpx; }
 .nav-text { font-size: 24rpx; color: #2A2326; text-align: center; }
+.share-bar { margin: 8rpx 0 32rpx; }
+.share-bar-btn { width: 100%; height: 84rpx; line-height: 84rpx; background: #FFF; color: #FC7A57; font-size: 28rpx; font-weight: 600; border-radius: 42rpx; border: 2rpx solid #FED7AA; }
+.share-bar-btn:active { opacity: 0.85; }
 </style>

+ 68 - 73
train-frontend/pages/share/index.vue

@@ -1,11 +1,7 @@
 <template>
   <view class="share-page">
-    <!-- 生产:后端已生成带参小程序码海报,直接展示图片 -->
-    <view class="poster-card" v-if="posterUrl">
-      <image class="poster-image" :src="posterUrl" mode="widthFix"></image>
-    </view>
-    <!-- test-mode/降级:本地 canvas 渲染带邀请码海报 -->
-    <view class="poster-card" v-else>
+    <!-- 统一用 canvas 合成海报:品牌 + 邀请码 + 小程序码(生产由后端生成,test-mode 为占位框) -->
+    <view class="poster-card">
       <canvas canvas-id="posterCanvas" id="posterCanvas" class="poster-canvas"></canvas>
     </view>
 
@@ -39,6 +35,12 @@ import { getMyPoster } from '@/utils/api.js'
 import { resolveAssetUrl } from '@/utils/share.js'
 import { guardPage } from '@/utils/guard.js'
 
+var CANVAS_W = 300
+var CANVAS_H = 450
+var QR_X = 85
+var QR_Y = 228
+var QR_SIZE = 130
+
 export default {
   data() {
     return {
@@ -53,7 +55,7 @@ export default {
     this.loadPoster()
   },
   onReady() {
-    // canvas 就绪后绘制海报
+    // canvas 就绪后先绘制占位海报,邀请码/小程序码返回后再重绘
     this.drawPoster()
   },
   methods: {
@@ -65,61 +67,87 @@ export default {
         self.posterUrl = resolveAssetUrl(data.posterUrl || '')
         self.shareText = data.shareText || ''
         if (self.inviteCode) {
-          // 重新绘制带邀请码的海报
+          // 重新绘制带邀请码/小程序码的海报
           setTimeout(function() {
             self.drawPoster()
           }, 300)
         }
-      }).catch(function () {})
+      }).catch(function() {})
     },
     drawPoster() {
       var self = this
       var ctx = uni.createCanvasContext('posterCanvas', self)
-      var width = 300
-      var height = 450
       // 背景
-      var gradient = ctx.createLinearGradient(0, 0, 0, height)
+      var gradient = ctx.createLinearGradient(0, 0, 0, CANVAS_H)
       gradient.addColorStop(0, '#FFF0E8')
       gradient.addColorStop(1, '#FED7AA')
       ctx.setFillStyle(gradient)
-      ctx.fillRect(0, 0, width, height)
+      ctx.fillRect(0, 0, CANVAS_W, CANVAS_H)
       // 顶部品牌区
       ctx.setFillStyle('#F9494F')
-      ctx.fillRect(0, 0, width, 8)
+      ctx.fillRect(0, 0, CANVAS_W, 8)
       ctx.setFillStyle('#2A2326')
       ctx.setFontSize(22)
       ctx.setTextAlign('center')
-      ctx.fillText('爱伴·AI之旅', width / 2, 60)
+      ctx.fillText('爱伴·AI之旅', CANVAS_W / 2, 56)
       ctx.setFillStyle('#5A4F4B')
       ctx.setFontSize(13)
-      ctx.fillText('我的专属邀请码', width / 2, 90)
-      // 中央邀请码卡片
+      ctx.fillText('我的专属邀请码', CANVAS_W / 2, 84)
+      // 邀请码卡片
       ctx.setFillStyle('#FFFFFF')
-      this.roundRect(ctx, 40, 130, width - 80, 120, 12)
+      this.roundRect(ctx, 40, 112, CANVAS_W - 80, 96, 12)
       ctx.setFillStyle('#FC7A57')
-      ctx.setFontSize(15)
-      ctx.fillText('我的邀请码', width / 2, 165)
-      ctx.setFillStyle('#2A2326')
-      ctx.setFontSize(34)
-      ctx.fillText(self.inviteCode || '------', width / 2, 215)
-      // 底部提示
-      ctx.setFillStyle('#F9494F')
       ctx.setFontSize(14)
-      ctx.fillText('扫码加入训练营', width / 2, 320)
-      // 二维码占位区(生产环境接入 getwxacodeunlimit 后绘制小程序码)
+      ctx.fillText('我的邀请码', CANVAS_W / 2, 144)
+      ctx.setFillStyle('#2A2326')
+      ctx.setFontSize(self.inviteCode.length > 8 ? 22 : 34)
+      ctx.fillText(self.inviteCode || '------', CANVAS_W / 2, 188)
+      // 小程序码(带邀请码 scene,扫码即建立推荐关系)
+      this.drawQr(ctx, function() {
+        ctx.setTextAlign('center')
+        ctx.setFillStyle('#F9494F')
+        ctx.setFontSize(14)
+        ctx.fillText('扫码加入训练营', CANVAS_W / 2, 386)
+        ctx.setFillStyle('#94877F')
+        ctx.setFontSize(11)
+        ctx.fillText('长按识别 · 报名可享专属权益', CANVAS_W / 2, 408)
+        ctx.setFillStyle('#5A4F4B')
+        ctx.setFontSize(12)
+        ctx.fillText('爱伴·AI之旅训练营', CANVAS_W / 2, 432)
+        ctx.draw()
+      })
+    },
+    drawQr(ctx, done) {
+      var self = this
+      if (!self.posterUrl) {
+        self.drawQrPlaceholder(ctx)
+        done()
+        return
+      }
+      uni.getImageInfo({
+        src: self.posterUrl,
+        success: function(res) {
+          ctx.drawImage(res.path, QR_X, QR_Y, QR_SIZE, QR_SIZE)
+          done()
+        },
+        fail: function() {
+          self.drawQrPlaceholder(ctx)
+          done()
+        }
+      })
+    },
+    drawQrPlaceholder(ctx) {
       ctx.setFillStyle('#FFFFFF')
-      this.roundRect(ctx, width / 2 - 45, 340, 90, 90, 8)
+      this.roundRect(ctx, QR_X, QR_Y, QR_SIZE, QR_SIZE, 8)
       ctx.setStrokeStyle('#E2E8F0')
       ctx.setLineWidth(1)
-      this.roundRect(ctx, width / 2 - 45, 340, 90, 90, 8)
-      ctx.stroke()
+      ctx.strokeRect(QR_X, QR_Y, QR_SIZE, QR_SIZE)
+      ctx.setTextAlign('center')
       ctx.setFillStyle('#CBD5E1')
       ctx.setFontSize(11)
-      ctx.fillText('小程序码', width / 2, 390)
-      ctx.setFillStyle('#94877F')
-      ctx.setFontSize(12)
-      ctx.fillText('爱伴·AI之旅训练营', width / 2, 420)
-      ctx.draw(false)
+      ctx.fillText('小程序码', CANVAS_W / 2, QR_Y + QR_SIZE / 2 - 4)
+      ctx.setFontSize(10)
+      ctx.fillText('生成中 / 暂不可用', CANVAS_W / 2, QR_Y + QR_SIZE / 2 + 16)
     },
     roundRect(ctx, x, y, w, h, r) {
       ctx.beginPath()
@@ -160,48 +188,19 @@ export default {
       var self = this
       if (this.saving) return
       this.saving = true
-      // 后端已生成海报:保存远程图片到相册
-      if (this.posterUrl) {
-        uni.downloadFile({
-          url: this.posterUrl,
-          success: function(res) {
-            if (res.statusCode !== 200) {
-              self.saving = false
-              uni.showToast({ title: '海报下载失败', icon: 'none' })
-              return
-            }
-            uni.saveImageToPhotosAlbum({
-              filePath: res.tempFilePath,
-              success: function() {
-                uni.showToast({ title: '海报已保存到相册', icon: 'success' })
-              },
-              fail: function() {
-                self.saving = false
-                uni.showToast({ title: '保存失败,请检查相册权限', icon: 'none' })
-              },
-              complete: function() {
-                self.saving = false
-              }
-            })
-          },
-          fail: function() {
-            self.saving = false
-            uni.showToast({ title: '海报下载失败', icon: 'none' })
-          }
-        })
-        return
-      }
-      // 本地 canvas 渲染海报
       uni.canvasToTempFilePath({
         canvasId: 'posterCanvas',
         success: function(res) {
           uni.saveImageToPhotosAlbum({
             filePath: res.tempFilePath,
             success: function() {
+              self.saving = false
               uni.showToast({ title: '海报已保存到相册', icon: 'success' })
             },
             fail: function(err) {
-              if (err && (err.errMsg || '').indexOf('auth') > -1) {
+              self.saving = false
+              var msg = (err && err.errMsg) || ''
+              if (msg.indexOf('auth') > -1 || msg.indexOf('deny') > -1) {
                 uni.showModal({
                   title: '需要相册权限',
                   content: '请在设置中开启「保存到相册」权限',
@@ -215,9 +214,6 @@ export default {
               } else {
                 uni.showToast({ title: '保存失败,请稍后重试', icon: 'none' })
               }
-            },
-            complete: function() {
-              self.saving = false
             }
           })
         },
@@ -241,7 +237,6 @@ export default {
 .share-page { min-height: 100vh; background: #F5F5F5; padding: 24rpx 32rpx; }
 .poster-card { background: #FFF; border-radius: 16rpx; padding: 24rpx; margin-bottom: 24rpx; display: flex; justify-content: center; }
 .poster-canvas { width: 300px; height: 450px; border-radius: 12rpx; }
-.poster-image { width: 100%; border-radius: 12rpx; }
 .invite-row { background: #FFF; border-radius: 16rpx; padding: 32rpx; margin-bottom: 24rpx; display: flex; align-items: center; }
 .share-text-row { padding: 20rpx 32rpx; }
 .share-text-preview { flex: 1; font-size: 24rpx; color: #FC7A57; margin-left: 24rpx; line-height: 1.5; }
@@ -256,4 +251,4 @@ export default {
 .stats-link .arrow { color: #94877F; font-size: 32rpx; margin-left: 8rpx; }
 .bind-link { display: flex; align-items: center; justify-content: center; padding: 8rpx 0 32rpx; color: #FC7A57; font-size: 26rpx; }
 .bind-link .arrow { color: #FC7A57; font-size: 30rpx; margin-left: 8rpx; }
-</style>
+</style>