新增 添加微信扫码DEMO

This commit is contained in:
yuantao
2025-11-28 18:51:52 +08:00
commit 40583c68e0
18 changed files with 3190 additions and 0 deletions

6
package-lock.json generated Normal file
View File

@@ -0,0 +1,6 @@
{
"name": "demo",
"lockfileVersion": 3,
"requires": true,
"packages": {}
}

24
wxQrcodeScan/.gitignore vendored Normal file
View File

@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

3
wxQrcodeScan/.vscode/extensions.json vendored Normal file
View File

@@ -0,0 +1,3 @@
{
"recommendations": ["Vue.volar"]
}

74
wxQrcodeScan/README.md Normal file
View File

@@ -0,0 +1,74 @@
# 微信二维码扫描用户资料收集系统
基于 Vue 3 + TypeScript + wxsdk-pure 开发的微信 H5 应用,实现扫描包含特定字符串的二维码并收集用户资料的功能。
## 🚀 功能特性
-**微信 JSSDK 集成**:基于 wxsdk-pure 实现微信 H5 能力
-**二维码扫描**:调用微信原生扫描功能
-**字符串匹配**:检查扫描结果是否包含指定字符串
-**用户资料收集**:完整的表单验证和数据收集
-**现代化 UI**:渐变背景、毛玻璃效果、响应式设计
-**TypeScript 支持**:完整的类型定义
## 📁 项目结构
```
wxQrcodeScan/
├── src/
│ ├── components/
│ │ ├── QrcodeScanner.vue # 二维码扫描组件
│ │ └── UserForm.vue # 用户资料表单组件
│ ├── services/
│ │ └── wechatSdk.ts # 微信 JSSDK 服务
│ ├── types/
│ │ └── wxsdk-pure.d.ts # wxsdk-pure 类型声明
│ ├── App.vue # 主应用组件
│ └── main.ts # 应用入口
├── PROJECT_GUIDE.md # 详细开发指南
└── README.md # 项目说明
```
## 🛠️ 技术栈
- **前端框架**: Vue 3.5.24
- **语言**: TypeScript
- **构建工具**: Vite 7.2.4
- **微信 SDK**: wxsdk-pure
- **样式**: CSS3 + 响应式设计
## 🚀 快速开始
### 1. 安装依赖
```bash
npm install
```
### 2. 开发模式
```bash
npm run dev
```
### 3. 构建部署
```bash
npm run build
npm run preview
```
## 📚 详细文档
详见 [PROJECT_GUIDE.md](./PROJECT_GUIDE.md) 获取完整的开发指南、API 参考和故障排除。
## 🔗 相关链接
- [微信 JSSDK 官方文档](https://developers.weixin.qq.com/doc/subscription/guide/h5/jssdk.html)
- [wxsdk-pure npm 包](https://www.npmjs.com/package/wxsdk-pure)
- [Vue 3 官方文档](https://cn.vuejs.org/)
- [Vite 构建工具](https://vitejs.dev/)
## 📄 许可证
MIT License

13
wxQrcodeScan/index.html Normal file
View File

@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, user-scalable=no" />
<title>微信扫码DEMO</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>

1448
wxQrcodeScan/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

23
wxQrcodeScan/package.json Normal file
View File

@@ -0,0 +1,23 @@
{
"name": "wxqrcodescan",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vue-tsc -b && vite build",
"preview": "vite preview"
},
"dependencies": {
"vue": "^3.5.24",
"wxsdk-pure": "^1.1.2"
},
"devDependencies": {
"@types/node": "^24.10.1",
"@vitejs/plugin-vue": "^6.0.1",
"@vue/tsconfig": "^0.8.1",
"typescript": "~5.9.3",
"vite": "^7.2.4",
"vue-tsc": "^3.1.4"
}
}

144
wxQrcodeScan/src/App.vue Normal file
View File

@@ -0,0 +1,144 @@
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import QrcodeScanner from './components/QrcodeScanner.vue'
import wechatSdk from './services/wechatSdk'
// 后端签名接口地址(需要配置为实际的后端地址)
const signatureApiUrl = ref('https://api.pandorastudio.cn/common/wxShare?url=')
// 响应式数据
const appInfo = ref({
title: '微信二维码扫描系统',
})
// 方法
const handleScanMatch = (result: string) => {
console.log('扫描匹配:', result)
// 这里可以添加匹配后的处理逻辑
}
const handleFormSubmitted = (userData: any) => {
console.log('用户资料提交:', userData)
// 提交成功后跳转到成功页面或显示成功提示
alert('资料提交成功!感谢您的参与。')
}
// 配置微信分享功能
const configureWeChatShare = () => {
if (wechatSdk.isWeChatEnvironment() && wechatSdk.isReady()) {
try {
wechatSdk.configureShare({
title: '微信二维码扫描系统',
desc: '扫描包含特定字符串的二维码进行用户资料收集',
shareUrl: window.location.href,
shareImgUrl: 'https://res.wx.qq.com/open/res/zh_CN/htmledition/inc/push/4.1.21/share/res/0bdd4e1/icon-share.png', // 使用微信默认分享图标
})
console.log('微信分享功能配置完成')
} catch (error) {
console.warn('微信分享功能配置失败:', error)
}
} else {
console.log('当前不在微信环境或SDK未准备就绪跳过分享配置')
}
}
// 生命周期
onMounted(() => {
// 延迟配置分享功能,等待微信 JSSDK 初始化
setTimeout(() => {
configureWeChatShare()
}, 2000)
})
</script>
<template>
<div id="app">
<header class="app-header">
<div class="header-content">
<h1 class="app-title">{{ appInfo.title }}</h1>
</div>
</header>
<main class="app-main">
<QrcodeScanner :signature-api-url="signatureApiUrl" @scan-match="handleScanMatch" @form-submitted="handleFormSubmitted" />
</main>
<footer class="app-footer">
<div class="footer-content">
<p>&copy; 2025 微信二维码扫描系统. PandoraStudio 提供.</p>
</div>
</footer>
</div>
</template>
<style scoped>
#app {
min-height: 100vh;
display: flex;
flex-direction: column;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
}
.app-header {
background: rgba(255, 255, 255, 0.1);
backdrop-filter: blur(10px);
border-bottom: 1px solid rgba(255, 255, 255, 0.2);
padding: 20px;
color: white;
}
.header-content {
text-align: center;
}
.app-title {
margin: 0;
font-size: 28px;
font-weight: 600;
background: linear-gradient(45deg, #fff, #e1bee7);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
}
.app-main {
flex: 1;
padding: 40px 20px;
display: flex;
align-items: flex-start;
justify-content: center;
}
.app-footer {
background: rgba(0, 0, 0, 0.1);
border-top: 1px solid rgba(255, 255, 255, 0.1);
padding: 20px;
color: rgba(255, 255, 255, 0.8);
}
.footer-content {
text-align: center;
}
.footer-content p {
margin: 0;
font-size: 14px;
}
/* 响应式设计 */
@media (max-width: 768px) {
.app-header {
padding: 16px;
}
.app-title {
font-size: 24px;
}
.app-main {
padding: 20px 16px;
}
}
</style>

View File

@@ -0,0 +1,381 @@
<template>
<div class="qrcode-scanner">
<!-- 扫码匹配成功直接显示表单 -->
<div v-if="isMatch && showUserForm" class="user-form-container">
<UserForm :scan-result="lastScanResult" @form-submitted="onUserFormSubmitted" @form-cancelled="onUserFormCancelled" />
</div>
<div class="scanner-content" v-else>
<div v-if="!isWeChatEnvironment" class="environment-warning">
<div class="warning-icon"></div>
<p>请在微信环境中使用此功能</p>
</div>
<div v-else-if="!isSdkReady" class="sdk-initializing">
<div class="loading-spinner"></div>
<p>正在初始化微信 JSSDK...</p>
</div>
<div v-else class="scanner-controls">
<div class="scan-info">
<p>扫描目标二维码需要包含 <strong>"pandora"</strong></p>
</div>
<button @click="startScan" class="scan-button"> 开始扫描 </button>
<!-- 扫码失败提示 -->
<div v-if="errorMessage && !isScanning" class="error-message">
{{ errorMessage }}
</div>
<!-- 扫码成功但未匹配 -->
<div v-if="scanSuccess && !isMatch && !isScanning" class="scan-result no-match">
<h3> 扫描失败</h3>
<p>扫描结果不包含指定 "pandora"</p>
<div class="scan-actions">
<button @click="reScan" class="reset-button"> 重新扫描 </button>
</div>
</div>
</div>
</div>
<div v-if="errorMessage" class="error-message">
{{ errorMessage }}
</div>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import wechatSdk from '../services/wechatSdk'
import UserForm from './UserForm.vue'
interface Props {
signatureApiUrl: string // 后端签名接口地址(必填)
}
const props = defineProps<Props>()
const emit = defineEmits<{
scanMatch: [result: string]
formSubmitted: [userData: any]
}>()
// 响应式数据
const isWeChatEnvironment = ref(false)
const isSdkReady = ref(false)
const isScanning = ref(false)
const scanSuccess = ref(false)
const scanError = ref(false)
const lastScanResult = ref('')
const isMatch = ref(false)
const showUserForm = ref(false)
const errorMessage = ref('')
// 硬编码的扫描目标字符串
const TARGET_STRING = 'pandora' // 扫描结果需要包含此字符串才匹配
// 方法
const initializeSdk = async () => {
try {
isWeChatEnvironment.value = wechatSdk.isWeChatEnvironment()
if (!isWeChatEnvironment.value) {
console.warn('不在微信环境中,无法使用 JSSDK 功能')
return
}
if (!props.signatureApiUrl) {
throw new Error('请提供后端签名接口地址')
}
console.log('正在初始化微信 JSSDK...')
// 使用 wxsdk-pure 初始化(包含 scanQRCode 功能)
await wechatSdk.initialize(props.signatureApiUrl)
isSdkReady.value = true
console.log('微信 JSSDK 初始化成功scanQRCode 功能已就绪')
} catch (error) {
console.error('微信 JSSDK 初始化失败:', error)
errorMessage.value = error instanceof Error ? error.message : '微信 JSSDK 初始化失败'
isSdkReady.value = false
}
}
const startScan = () => {
console.log('开始新扫描,扫描前状态:', {
isScanning: isScanning.value,
scanSuccess: scanSuccess.value,
scanError: scanError.value,
lastScanResult: lastScanResult.value,
isMatch: isMatch.value,
showUserForm: showUserForm.value,
})
// 开始新扫描时,只重置结果相关状态,保持扫描中状态
isScanning.value = true
scanSuccess.value = false
scanError.value = false
lastScanResult.value = ''
isMatch.value = false
showUserForm.value = false
errorMessage.value = ''
console.log('扫描开始,扫描后状态:', {
isScanning: isScanning.value,
scanSuccess: scanSuccess.value,
scanError: scanError.value,
lastScanResult: lastScanResult.value,
isMatch: isMatch.value,
showUserForm: showUserForm.value,
})
wechatSdk.scanQRCode(
(result: string) => {
// 扫码成功,处理结果
lastScanResult.value = result
isMatch.value = wechatSdk.checkScanResult(result, TARGET_STRING)
isScanning.value = false // 结束扫描状态
if (isMatch.value) {
// 匹配成功,直接显示表单
showUserForm.value = true
emit('scanMatch', result)
} else {
// 不匹配,显示错误信息
scanSuccess.value = true // 仅用于显示失败信息
errorMessage.value = '扫描结果不匹配指定要求,请重新扫描包含 "pandora" 字符串的二维码'
}
},
(error: any) => {
isScanning.value = false // 结束扫描状态
// 判断是否是用户主动取消
if (error?.errMsg?.includes('cancel') || error?.errMsg?.includes('取消')) {
console.log('用户取消了扫码操作')
// 取消时不显示错误信息,只恢复到初始状态
} else {
scanError.value = true
errorMessage.value = `扫描失败: ${error?.errMsg || '未知错误'}`
}
}
)
}
const resetScanState = () => {
console.log('重置扫描状态...')
// 重置所有扫描相关状态(除了扫描中状态)
scanSuccess.value = false
scanError.value = false
lastScanResult.value = ''
isMatch.value = false
showUserForm.value = false
errorMessage.value = ''
console.log('扫描状态已重置')
}
const reScan = () => {
console.log('重新扫描被点击')
resetScanState()
// 稍微延迟一下再开始扫描确保UI状态更新完成
setTimeout(() => {
startScan()
}, 100)
}
const onUserFormSubmitted = (userData: any) => {
emit('formSubmitted', userData)
resetScanState() // 重置扫描状态,回到扫码界面
console.log('表单提交完成,重置扫描状态')
}
const onUserFormCancelled = () => {
showUserForm.value = false // 关闭表单
resetScanState() // 重置所有状态,让扫码按钮恢复初始状态
console.log('表单取消,重置扫描状态')
}
// 生命周期
onMounted(() => {
initializeSdk()
})
</script>
<style scoped>
.qrcode-scanner {
max-width: 500px;
margin: 0 auto;
padding: 20px;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}
.scanner-header {
text-align: center;
margin-bottom: 30px;
}
.scanner-header h2 {
color: #333;
margin-bottom: 10px;
}
.status-indicator {
padding: 8px 16px;
border-radius: 20px;
font-size: 14px;
font-weight: 500;
background-color: #f0f0f0;
color: #666;
}
.status-indicator.active {
background-color: #e3f2fd;
color: #1976d2;
}
.status-indicator.success {
background-color: #e8f5e8;
color: #2e7d32;
}
.status-indicator.error {
background-color: #ffebee;
color: #c62828;
}
.environment-warning,
.sdk-initializing {
text-align: center;
padding: 40px 20px;
color: #666;
}
.warning-icon {
font-size: 48px;
margin-bottom: 16px;
}
.loading-spinner {
width: 40px;
height: 40px;
border: 3px solid #f0f0f0;
border-top: 3px solid #1976d2;
border-radius: 50%;
animation: spin 1s linear infinite;
margin: 0 auto 16px;
}
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
.scanner-controls {
space-y: 20px;
}
.scan-info {
margin-bottom: 20px;
padding: 12px;
background-color: rgba(25, 118, 210, 0.1);
border: 1px solid rgba(25, 118, 210, 0.3);
border-radius: 6px;
text-align: center;
}
.scan-info p {
margin: 0;
color: #fff;
font-size: 14px;
}
.scan-info strong {
color: #fff;
font-weight: 600;
}
.scan-button {
width: 100%;
padding: 14px;
background-color: #1976d2;
color: white;
border: none;
border-radius: 6px;
font-size: 16px;
font-weight: 500;
cursor: pointer;
transition: background-color 0.3s;
}
.scan-button:hover:not(:disabled) {
background-color: #1565c0;
}
.scan-button:disabled {
background-color: #ccc;
cursor: not-allowed;
}
.scan-result {
margin-top: 20px;
padding: 16px;
border-radius: 8px;
border-left: 4px solid #f44336;
}
.scan-result.no-match {
background-color: #ffebee;
border-left-color: #f44336;
}
.scan-result h3 {
margin: 0 0 8px 0;
font-size: 16px;
color: #f44336;
}
.scan-result p {
margin: 0 0 12px 0;
color: #666;
}
.user-form-container {
margin-top: 20px;
padding: 0;
}
.scan-actions {
margin-top: 16px;
text-align: center;
}
.reset-button {
background-color: #fff;
color: #f44336;
border: 1px solid #f44336;
padding: 8px 20px;
border-radius: 6px;
font-size: 14px;
cursor: pointer;
transition: all 0.3s;
}
.reset-button:hover {
background-color: #f44336;
color: white;
}
.error-message {
margin-top: 16px;
padding: 12px;
background-color: #ffebee;
color: #c62828;
border-radius: 6px;
text-align: center;
}
</style>

View File

@@ -0,0 +1,559 @@
<template>
<div class="user-form">
<div class="form-header">
<h3>请填写您的资料</h3>
<p class="form-subtitle">二维码扫描成功请完善您的个人信息</p>
</div>
<form @submit.prevent="submitForm" class="user-data-form">
<div class="form-group">
<label for="name" class="required">姓名</label>
<input
id="name"
v-model="formData.name"
type="text"
required
placeholder="请输入您的姓名"
class="form-input"
/>
<span v-if="errors.name" class="error-text">{{ errors.name }}</span>
</div>
<div class="form-group">
<label for="phone" class="required">手机号码</label>
<input
id="phone"
v-model="formData.phone"
type="tel"
required
placeholder="请输入您的手机号码"
class="form-input"
@blur="validatePhone"
/>
<span v-if="errors.phone" class="error-text">{{ errors.phone }}</span>
</div>
<div class="form-group">
<label for="email">邮箱地址</label>
<input
id="email"
v-model="formData.email"
type="email"
placeholder="请输入您的邮箱地址(可选)"
class="form-input"
@blur="validateEmail"
/>
<span v-if="errors.email" class="error-text">{{ errors.email }}</span>
</div>
<div class="form-group">
<label for="company">公司/组织</label>
<input
id="company"
v-model="formData.company"
type="text"
placeholder="请输入您的公司或组织名称(可选)"
class="form-input"
/>
</div>
<div class="form-group">
<label for="position">职位</label>
<input
id="position"
v-model="formData.position"
type="text"
placeholder="请输入您的职位(可选)"
class="form-input"
/>
</div>
<div class="form-group">
<label for="purpose">参与目的</label>
<select id="purpose" v-model="formData.purpose" class="form-select">
<option value="">请选择您的参与目的</option>
<option value="business">商务合作</option>
<option value="technical">技术交流</option>
<option value="partnership">合作伙伴</option>
<option value="feedback">产品反馈</option>
<option value="other">其他</option>
</select>
</div>
<div class="form-group">
<label for="message">备注信息</label>
<textarea
id="message"
v-model="formData.message"
placeholder="请输入其他需要说明的信息(可选)"
class="form-textarea"
rows="3"
></textarea>
</div>
<div class="form-group checkbox-group">
<label class="checkbox-label">
<input
v-model="formData.agreement"
type="checkbox"
required
class="checkbox-input"
/>
<span class="checkbox-text">
我已阅读并同意 <a href="#" @click.prevent="showAgreement">用户协议</a> <a href="#" @click.prevent="showPrivacy">隐私政策</a>
</span>
</label>
<span v-if="errors.agreement" class="error-text">{{ errors.agreement }}</span>
</div>
<div class="form-actions">
<button type="button" @click="cancel" class="btn btn-secondary" :disabled="isSubmitting">
取消
</button>
<button type="submit" class="btn btn-primary" :disabled="isSubmitting || !isFormValid">
{{ isSubmitting ? '提交中...' : '提交资料' }}
</button>
</div>
<div v-if="submitSuccess" class="success-message">
<div class="success-icon"></div>
<p>资料提交成功感谢您的参与</p>
</div>
<div v-if="submitError" class="error-message">
<div class="error-icon"></div>
<p>{{ submitError }}</p>
</div>
</form>
<!-- 用户协议弹窗 -->
<div v-if="showAgreementModal" class="modal-overlay" @click="hideAgreement">
<div class="modal-content" @click.stop>
<div class="modal-header">
<h3>用户协议</h3>
<button @click="hideAgreement" class="modal-close">×</button>
</div>
<div class="modal-body">
<p>这里是用户协议的内容...</p>
<!-- 实际项目中这里应该是完整的用户协议 -->
</div>
<div class="modal-footer">
<button @click="hideAgreement" class="btn btn-primary">我知道了</button>
</div>
</div>
</div>
<!-- 隐私政策弹窗 -->
<div v-if="showPrivacyModal" class="modal-overlay" @click="hidePrivacy">
<div class="modal-content" @click.stop>
<div class="modal-header">
<h3>隐私政策</h3>
<button @click="hidePrivacy" class="modal-close">×</button>
</div>
<div class="modal-body">
<p>这里是隐私政策的内容...</p>
<!-- 实际项目中这里应该是完整的隐私政策 -->
</div>
<div class="modal-footer">
<button @click="hidePrivacy" class="btn btn-primary">我知道了</button>
</div>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import wechatSdk from '../services/wechatSdk'
interface Props {
scanResult: string
}
const props = defineProps<Props>()
const emit = defineEmits<{
formSubmitted: [userData: any]
formCancelled: []
}>()
// 表单数据
const formData = ref({
name: '',
phone: '',
email: '',
company: '',
position: '',
purpose: '',
message: '',
agreement: false
})
// 错误信息
const errors = ref({
name: '',
phone: '',
email: '',
agreement: ''
})
// 状态
const isSubmitting = ref(false)
const submitSuccess = ref(false)
const submitError = ref('')
const showAgreementModal = ref(false)
const showPrivacyModal = ref(false)
// 计算属性
const isFormValid = computed(() => {
return formData.value.name.trim() &&
formData.value.phone.trim() &&
formData.value.agreement &&
!errors.value.name &&
!errors.value.phone &&
!errors.value.email
})
// 方法
const validatePhone = () => {
const phone = formData.value.phone
const phoneRegex = /^1[3-9]\d{9}$/
if (!phone) {
errors.value.phone = '请输入手机号码'
} else if (!phoneRegex.test(phone)) {
errors.value.phone = '请输入正确的手机号码'
} else {
errors.value.phone = ''
}
}
const validateEmail = () => {
const email = formData.value.email
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
if (email && !emailRegex.test(email)) {
errors.value.email = '请输入正确的邮箱地址'
} else {
errors.value.email = ''
}
}
const showAgreement = () => {
showAgreementModal.value = true
}
const hideAgreement = () => {
showAgreementModal.value = false
}
const showPrivacy = () => {
showPrivacyModal.value = true
}
const hidePrivacy = () => {
showPrivacyModal.value = false
}
const getWeChatUserInfo = async () => {
try {
const userInfo = await wechatSdk.getUserProfile()
if (userInfo) {
// 如果获取到微信用户信息,可以预填充一些字段
if (userInfo.nickName && !formData.value.name) {
formData.value.name = userInfo.nickName
}
}
} catch (error) {
console.log('用户未授权获取微信信息或获取失败:', error)
}
}
const submitForm = async () => {
// 最终验证
validatePhone()
validateEmail()
if (!formData.value.agreement) {
errors.value.agreement = '请阅读并同意用户协议和隐私政策'
return
}
if (!isFormValid.value) {
return
}
isSubmitting.value = true
submitError.value = ''
try {
// 模拟提交数据到服务器
const userData = {
...formData.value,
scanResult: props.scanResult,
submitTime: new Date().toISOString(),
userAgent: navigator.userAgent,
url: window.location.href
}
// 这里应该调用实际的 API
console.log('提交用户数据:', userData)
// 模拟 API 调用延迟
await new Promise(resolve => setTimeout(resolve, 1000))
submitSuccess.value = true
// 延迟发送成功事件,让用户看到成功消息
setTimeout(() => {
emit('formSubmitted', userData)
}, 1500)
} catch (error) {
console.error('提交失败:', error)
submitError.value = '提交失败,请稍后重试'
} finally {
isSubmitting.value = false
}
}
const cancel = () => {
emit('formCancelled')
}
// 生命周期
onMounted(() => {
getWeChatUserInfo()
})
</script>
<style scoped>
.user-form {
max-width: 500px;
margin: 0 auto;
padding: 24px;
background-color: #fff;
border-radius: 12px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
.form-header {
text-align: center;
margin-bottom: 24px;
}
.form-header h3 {
color: #333;
margin: 0 0 8px 0;
font-size: 20px;
}
.form-subtitle {
color: #666;
margin: 0;
font-size: 14px;
}
.user-data-form {
space-y: 20px;
}
.form-group {
margin-bottom: 20px;
}
.form-group label {
display: block;
margin-bottom: 6px;
font-weight: 500;
color: #333;
}
.form-group label.required::after {
content: ' *';
color: #f44336;
}
.form-input,
.form-select,
.form-textarea {
width: 100%;
padding: 12px;
border: 1px solid #ddd;
border-radius: 6px;
font-size: 14px;
box-sizing: border-box;
transition: border-color 0.3s;
}
.form-input:focus,
.form-select:focus,
.form-textarea:focus {
outline: none;
border-color: #1976d2;
box-shadow: 0 0 0 2px rgba(25, 118, 210, 0.2);
}
.checkbox-group {
margin-top: 24px;
}
.checkbox-label {
display: flex;
align-items: flex-start;
cursor: pointer;
}
.checkbox-input {
margin-right: 8px;
margin-top: 2px;
}
.checkbox-text {
font-size: 14px;
line-height: 1.4;
}
.checkbox-text a {
color: #1976d2;
text-decoration: none;
}
.checkbox-text a:hover {
text-decoration: underline;
}
.error-text {
display: block;
color: #f44336;
font-size: 12px;
margin-top: 4px;
}
.form-actions {
display: flex;
gap: 12px;
margin-top: 24px;
}
.btn {
flex: 1;
padding: 12px 24px;
border: none;
border-radius: 6px;
font-size: 14px;
font-weight: 500;
cursor: pointer;
transition: all 0.3s;
}
.btn:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.btn-primary {
background-color: #1976d2;
color: white;
}
.btn-primary:hover:not(:disabled) {
background-color: #1565c0;
}
.btn-secondary {
background-color: #f5f5f5;
color: #666;
border: 1px solid #ddd;
}
.btn-secondary:hover:not(:disabled) {
background-color: #eeeeee;
}
.success-message,
.error-message {
margin-top: 16px;
padding: 16px;
border-radius: 6px;
text-align: center;
}
.success-message {
background-color: #e8f5e8;
color: #2e7d32;
}
.error-message {
background-color: #ffebee;
color: #c62828;
}
.success-icon,
.error-icon {
font-size: 24px;
margin-bottom: 8px;
}
/* 弹窗样式 */
.modal-overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
align-items: center;
justify-content: center;
z-index: 1000;
}
.modal-content {
background-color: white;
border-radius: 8px;
max-width: 500px;
max-height: 80vh;
overflow: hidden;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
}
.modal-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 16px 20px;
border-bottom: 1px solid #eee;
}
.modal-header h3 {
margin: 0;
color: #333;
}
.modal-close {
background: none;
border: none;
font-size: 24px;
color: #666;
cursor: pointer;
padding: 0;
width: 30px;
height: 30px;
display: flex;
align-items: center;
justify-content: center;
}
.modal-body {
padding: 20px;
max-height: 60vh;
overflow-y: auto;
}
.modal-footer {
padding: 16px 20px;
border-top: 1px solid #eee;
text-align: right;
}
</style>

5
wxQrcodeScan/src/main.ts Normal file
View File

@@ -0,0 +1,5 @@
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
createApp(App).mount('#app')

View File

@@ -0,0 +1,278 @@
import wxSDK from 'wxsdk-pure'
export interface WeChatConfig {
appId: string
timestamp: number
nonceStr: string
signature: string
}
export interface ScanResult {
resultStr: string
errMsg?: string
}
export class WeChatSdkService {
private static instance: WeChatSdkService
private wxSdk: any = null
private isInitialized = false
private constructor() {}
static getInstance(): WeChatSdkService {
if (!WeChatSdkService.instance) {
WeChatSdkService.instance = new WeChatSdkService()
}
return WeChatSdkService.instance
}
/**
* 初始化微信 JSSDK使用 wxsdk-pure
* @param apiUrl 后端签名接口地址
*/
async initialize(apiUrl: string): Promise<void> {
if (this.isInitialized) {
return
}
try {
console.log('正在初始化微信 JSSDK...')
// 使用 wxsdk-pure 初始化,包含扫描功能
this.wxSdk = await wxSDK({
apiUrl: apiUrl,
title: '微信二维码扫描系统',
desc: '扫描包含特定字符串的二维码进行用户资料收集',
debug: false,
// 在 jsApiList 中配置扫描功能
jsApiList: [
'scanQRCode', // 扫描二维码
'chooseImage', // 选择图片
'previewImage', // 预览图片
'getUserProfile', // 获取用户信息
'closeWindow', // 关闭窗口
'onMenuShareTimeline', // 分享到朋友圈
'onMenuShareAppMessage' // 分享给好友
],
callback: {
ready: () => {
console.log('微信 SDK 就绪,所有功能已加载')
},
success: (type: string) => {
console.log(`${type} 分享配置成功`)
},
error: (err: any) => {
console.error('wxsdk-pure 初始化失败:', err)
throw new Error(`wxsdk-pure 初始化失败: ${err?.message || err}`)
}
}
})
this.isInitialized = true
console.log('微信 JSSDK 初始化成功scanQRCode 功能已可用')
} catch (error) {
console.error('微信 JSSDK 初始化失败:', error)
this.isInitialized = false
throw error
}
}
/**
* 检查是否在微信环境中
*/
isWeChatEnvironment(): boolean {
return /MicroMessenger/i.test(navigator.userAgent)
}
/**
* 检查 JSSDK 是否已初始化
*/
isReady(): boolean {
return this.isInitialized && this.wxSdk && typeof this.wxSdk.scanQRCode === 'function'
}
/**
* 扫描二维码(使用 wxsdk-pure 返回的微信 SDK 实例)
* @param successCallback 成功回调
* @param errorCallback 错误回调
*/
scanQRCode(successCallback: (result: string) => void, errorCallback?: (error: any) => void): void {
if (!this.isReady()) {
const error = '微信 JSSDK 未初始化,请先调用 initialize 方法'
console.error(error)
errorCallback?.(new Error(error))
return
}
try {
this.wxSdk.scanQRCode({
needResult: 1, // 扫描结果由微信处理1表示返回结果
scanType: ['qrCode', 'barCode'], // 可以扫描的类型
success: (res: ScanResult) => {
const result = res.resultStr
console.log('扫描成功:', result)
successCallback(result)
},
fail: (error: any) => {
console.error('扫描失败:', error)
const errorMsg = error?.errMsg || error?.message || '扫描失败'
errorCallback?.(new Error(errorMsg))
},
complete: () => {
console.log('扫描完成')
}
})
} catch (error) {
console.error('调用扫描功能失败:', error)
errorCallback?.(error)
}
}
/**
* 检查扫描结果是否包含特定字符串
* @param scanResult 扫描结果
* @param targetString 目标字符串
*/
checkScanResult(scanResult: string, targetString: string): boolean {
return scanResult.includes(targetString)
}
/**
* 分享到朋友圈
* @param title 分享标题
* @param desc 分享描述
* @param shareUrl 分享链接
* @param shareImgUrl 分享图片链接
*/
shareToTimeline(title: string, desc: string, shareUrl: string, shareImgUrl: string): void {
if (!this.isReady()) {
console.warn('微信 SDK 未初始化,无法分享')
return
}
try {
this.wxSdk.onMenuShareTimeline({
title: title,
desc: desc,
link: shareUrl,
imgUrl: shareImgUrl,
success: () => {
console.log('分享到朋友圈成功')
},
fail: () => {
console.error('分享到朋友圈失败')
}
})
} catch (error) {
console.error('分享到朋友圈配置失败:', error)
}
}
/**
* 分享给好友
* @param title 分享标题
* @param desc 分享描述
* @param shareUrl 分享链接
* @param shareImgUrl 分享图片链接
*/
shareToMessage(title: string, desc: string, shareUrl: string, shareImgUrl: string): void {
if (!this.isReady()) {
console.warn('微信 SDK 未初始化,无法分享')
return
}
try {
this.wxSdk.onMenuShareAppMessage({
title: title,
desc: desc,
link: shareUrl,
imgUrl: shareImgUrl,
success: () => {
console.log('分享给好友成功')
},
fail: () => {
console.error('分享给好友失败')
}
})
} catch (error) {
console.error('分享给好友配置失败:', error)
}
}
/**
* 配置分享功能
* @param config 分享配置
*/
configureShare(config: {
title?: string
desc?: string
shareUrl?: string
shareImgUrl?: string
}): void {
const title = config.title || '微信二维码扫描系统'
const desc = config.desc || '扫描包含特定字符串的二维码进行用户资料收集'
const shareUrl = config.shareUrl || window.location.href
const shareImgUrl = config.shareImgUrl || '/vite.svg'
this.shareToTimeline(title, desc, shareUrl, shareImgUrl)
this.shareToMessage(title, desc, shareUrl, shareImgUrl)
}
/**
* 获取用户信息(需要用户授权)
*/
getUserProfile(): Promise<any> {
return new Promise((resolve, reject) => {
if (!this.isReady()) {
reject(new Error('微信 JSSDK 未初始化'))
return
}
try {
this.wxSdk.getUserProfile({
desc: '用于完善用户资料',
success: (res: any) => {
console.log('获取用户信息成功:', res)
resolve(res.userInfo)
},
fail: (error: any) => {
console.error('获取用户信息失败:', error)
const errorMsg = error?.errMsg || error?.message || '获取用户信息失败'
reject(new Error(errorMsg))
}
})
} catch (error) {
console.error('调用 getUserProfile 失败:', error)
reject(error)
}
})
}
/**
* 关闭当前页面
*/
closeWindow(): void {
if (this.isWeChatEnvironment() && this.isReady()) {
try {
this.wxSdk.closeWindow()
} catch (error) {
console.error('关闭页面失败:', error)
// 如果微信 API 失败,使用 fallback
window.close()
}
} else {
window.close()
}
}
/**
* 重置 SDK 状态(用于重新初始化)
*/
reset(): void {
this.wxSdk = null
this.isInitialized = false
}
}
export default WeChatSdkService.getInstance()

144
wxQrcodeScan/src/style.css Normal file
View File

@@ -0,0 +1,144 @@
/* 微信二维码扫描系统 - 全局样式 */
/* 重置默认样式 */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
/* 全局滚动条样式 */
::-webkit-scrollbar {
width: 8px;
}
::-webkit-scrollbar-track {
background: rgba(255, 255, 255, 0.1);
border-radius: 4px;
}
::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.3);
border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
background: rgba(255, 255, 255, 0.5);
}
/* 全局按钮样式 */
.btn {
border-radius: 8px;
border: 1px solid transparent;
padding: 0.6em 1.2em;
font-size: 1em;
font-weight: 500;
font-family: inherit;
cursor: pointer;
transition: all 0.25s;
}
.btn:hover {
transform: translateY(-1px);
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
.btn:focus,
.btn:focus-visible {
outline: 4px auto -webkit-focus-ring-color;
}
/* 卡片组件样式 */
.card {
background: rgba(255, 255, 255, 0.1);
backdrop-filter: blur(10px);
border-radius: 12px;
border: 1px solid rgba(255, 255, 255, 0.2);
padding: 1.5rem;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}
/* 加载动画 */
.loading {
display: inline-block;
width: 20px;
height: 20px;
border: 2px solid rgba(255, 255, 255, 0.3);
border-radius: 50%;
border-top-color: #fff;
animation: spin 1s ease-in-out infinite;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
/* 表单样式 */
.form-group {
margin-bottom: 1rem;
}
.form-label {
display: block;
margin-bottom: 0.5rem;
font-weight: 500;
color: rgba(255, 255, 255, 0.9);
}
.form-input {
width: 100%;
padding: 0.75rem;
border: 1px solid rgba(255, 255, 255, 0.3);
border-radius: 6px;
background: rgba(255, 255, 255, 0.1);
color: white;
font-size: 14px;
transition: border-color 0.3s, background-color 0.3s;
}
.form-input::placeholder {
color: rgba(255, 255, 255, 0.6);
}
.form-input:focus {
outline: none;
border-color: rgba(255, 255, 255, 0.6);
background: rgba(255, 255, 255, 0.15);
}
/* 工具提示 */
.tooltip {
position: relative;
cursor: help;
}
.tooltip::after {
content: attr(data-tooltip);
position: absolute;
bottom: 100%;
left: 50%;
transform: translateX(-50%);
background: rgba(0, 0, 0, 0.8);
color: white;
padding: 4px 8px;
border-radius: 4px;
font-size: 12px;
white-space: nowrap;
opacity: 0;
visibility: hidden;
transition: opacity 0.3s, visibility 0.3s;
z-index: 1000;
}
.tooltip:hover::after {
opacity: 1;
visibility: visible;
}

31
wxQrcodeScan/src/types/wxsdk-pure.d.ts vendored Normal file
View File

@@ -0,0 +1,31 @@
// wxsdk-pure 类型声明
// 注意wxsdk-pure 是一个功能完整的微信 JSSDK 封装库,支持扫码、分享等所有常用功能
declare module 'wxsdk-pure' {
export interface WxSDKConfig {
apiUrl: string
sdk?: string
title?: string | string[]
desc?: string
shareIcon?: string | string[]
shareLinks?: string | string[]
debug?: boolean
jsApiList?: string[]
openTagList?: string[]
timeout?: number
callback?: {
ready?: () => void
success?: (type: string) => void
error?: (err: any) => void
}
}
/**
* wxsdk-pure 的主要函数
* @param config 配置对象
* @returns Promise 返回初始化后的微信 SDK 实例
*/
function wxSDK(config: WxSDKConfig): Promise<any>
export default wxSDK
}

View File

@@ -0,0 +1,16 @@
{
"extends": "@vue/tsconfig/tsconfig.dom.json",
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"types": ["vite/client"],
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue"]
}

View File

@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}

View File

@@ -0,0 +1,26 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "ES2023",
"lib": ["ES2023"],
"module": "ESNext",
"types": ["node"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["vite.config.ts"]
}

View File

@@ -0,0 +1,8 @@
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
// https://vite.dev/config/
export default defineConfig({
plugins: [vue()],
base: './',
})