Bladeren bron

first commit

张延森 6 jaren geleden
commit
e8684d5bbb
27 gewijzigde bestanden met toevoegingen van 1585 en 0 verwijderingen
  1. 29
    0
      .gitignore
  2. 286
    0
      mvnw
  3. 161
    0
      mvnw.cmd
  4. 72
    0
      pom.xml
  5. 13
    0
      src/main/java/com/huiju/miniapp/MiniappApplication.java
  6. 41
    0
      src/main/java/com/huiju/miniapp/common/Encrypt.java
  7. 42
    0
      src/main/java/com/huiju/miniapp/common/HttpUtil.java
  8. 59
    0
      src/main/java/com/huiju/miniapp/common/InitWxMaService.java
  9. 56
    0
      src/main/java/com/huiju/miniapp/common/ResponseBean.java
  10. 43
    0
      src/main/java/com/huiju/miniapp/common/TemplateMsgUtil.java
  11. 26
    0
      src/main/java/com/huiju/miniapp/config/AccessConfig.java
  12. 110
    0
      src/main/java/com/huiju/miniapp/controller/CommController.java
  13. 59
    0
      src/main/java/com/huiju/miniapp/controller/MessageController.java
  14. 112
    0
      src/main/java/com/huiju/miniapp/controller/MiniAppController.java
  15. 67
    0
      src/main/java/com/huiju/miniapp/controller/UserController.java
  16. 45
    0
      src/main/java/com/huiju/miniapp/entity/MiniappConfiger.java
  17. 31
    0
      src/main/java/com/huiju/miniapp/entity/SystemConfiger.java
  18. 141
    0
      src/main/java/com/huiju/miniapp/interceptor/AccessInterceptor.java
  19. 18
    0
      src/main/java/com/huiju/miniapp/mapper/MiniappConfigerMapper.java
  20. 18
    0
      src/main/java/com/huiju/miniapp/mapper/SystemConfigerMapper.java
  21. 18
    0
      src/main/java/com/huiju/miniapp/service/IMiniappConfigerService.java
  22. 17
    0
      src/main/java/com/huiju/miniapp/service/ISystemConfigerService.java
  23. 56
    0
      src/main/java/com/huiju/miniapp/service/impl/MiniappConfigerServiceImpl.java
  24. 31
    0
      src/main/java/com/huiju/miniapp/service/impl/SystemConfigerServiceImpl.java
  25. 24
    0
      src/main/resources/application.yml
  26. 5
    0
      src/main/resources/mapper/MiniappConfigerMapper.xml
  27. 5
    0
      src/main/resources/mapper/SystemConfigerMapper.xml

+ 29
- 0
.gitignore Bestand weergeven

@@ -0,0 +1,29 @@
1
+HELP.md
2
+/target/
3
+!.mvn/wrapper/maven-wrapper.jar
4
+
5
+### STS ###
6
+.apt_generated
7
+.classpath
8
+.factorypath
9
+.project
10
+.settings
11
+.springBeans
12
+.sts4-cache
13
+
14
+### IntelliJ IDEA ###
15
+.idea
16
+*.iws
17
+*.iml
18
+*.ipr
19
+
20
+### NetBeans ###
21
+/nbproject/private/
22
+/nbbuild/
23
+/dist/
24
+/nbdist/
25
+/.nb-gradle/
26
+/build/
27
+
28
+### VS Code ###
29
+.vscode/

+ 286
- 0
mvnw Bestand weergeven

@@ -0,0 +1,286 @@
1
+#!/bin/sh
2
+# ----------------------------------------------------------------------------
3
+# Licensed to the Apache Software Foundation (ASF) under one
4
+# or more contributor license agreements.  See the NOTICE file
5
+# distributed with this work for additional information
6
+# regarding copyright ownership.  The ASF licenses this file
7
+# to you under the Apache License, Version 2.0 (the
8
+# "License"); you may not use this file except in compliance
9
+# with the License.  You may obtain a copy of the License at
10
+#
11
+#    https://www.apache.org/licenses/LICENSE-2.0
12
+#
13
+# Unless required by applicable law or agreed to in writing,
14
+# software distributed under the License is distributed on an
15
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16
+# KIND, either express or implied.  See the License for the
17
+# specific language governing permissions and limitations
18
+# under the License.
19
+# ----------------------------------------------------------------------------
20
+
21
+# ----------------------------------------------------------------------------
22
+# Maven2 Start Up Batch script
23
+#
24
+# Required ENV vars:
25
+# ------------------
26
+#   JAVA_HOME - location of a JDK home dir
27
+#
28
+# Optional ENV vars
29
+# -----------------
30
+#   M2_HOME - location of maven2's installed home dir
31
+#   MAVEN_OPTS - parameters passed to the Java VM when running Maven
32
+#     e.g. to debug Maven itself, use
33
+#       set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
34
+#   MAVEN_SKIP_RC - flag to disable loading of mavenrc files
35
+# ----------------------------------------------------------------------------
36
+
37
+if [ -z "$MAVEN_SKIP_RC" ] ; then
38
+
39
+  if [ -f /etc/mavenrc ] ; then
40
+    . /etc/mavenrc
41
+  fi
42
+
43
+  if [ -f "$HOME/.mavenrc" ] ; then
44
+    . "$HOME/.mavenrc"
45
+  fi
46
+
47
+fi
48
+
49
+# OS specific support.  $var _must_ be set to either true or false.
50
+cygwin=false;
51
+darwin=false;
52
+mingw=false
53
+case "`uname`" in
54
+  CYGWIN*) cygwin=true ;;
55
+  MINGW*) mingw=true;;
56
+  Darwin*) darwin=true
57
+    # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
58
+    # See https://developer.apple.com/library/mac/qa/qa1170/_index.html
59
+    if [ -z "$JAVA_HOME" ]; then
60
+      if [ -x "/usr/libexec/java_home" ]; then
61
+        export JAVA_HOME="`/usr/libexec/java_home`"
62
+      else
63
+        export JAVA_HOME="/Library/Java/Home"
64
+      fi
65
+    fi
66
+    ;;
67
+esac
68
+
69
+if [ -z "$JAVA_HOME" ] ; then
70
+  if [ -r /etc/gentoo-release ] ; then
71
+    JAVA_HOME=`java-config --jre-home`
72
+  fi
73
+fi
74
+
75
+if [ -z "$M2_HOME" ] ; then
76
+  ## resolve links - $0 may be a link to maven's home
77
+  PRG="$0"
78
+
79
+  # need this for relative symlinks
80
+  while [ -h "$PRG" ] ; do
81
+    ls=`ls -ld "$PRG"`
82
+    link=`expr "$ls" : '.*-> \(.*\)$'`
83
+    if expr "$link" : '/.*' > /dev/null; then
84
+      PRG="$link"
85
+    else
86
+      PRG="`dirname "$PRG"`/$link"
87
+    fi
88
+  done
89
+
90
+  saveddir=`pwd`
91
+
92
+  M2_HOME=`dirname "$PRG"`/..
93
+
94
+  # make it fully qualified
95
+  M2_HOME=`cd "$M2_HOME" && pwd`
96
+
97
+  cd "$saveddir"
98
+  # echo Using m2 at $M2_HOME
99
+fi
100
+
101
+# For Cygwin, ensure paths are in UNIX format before anything is touched
102
+if $cygwin ; then
103
+  [ -n "$M2_HOME" ] &&
104
+    M2_HOME=`cygpath --unix "$M2_HOME"`
105
+  [ -n "$JAVA_HOME" ] &&
106
+    JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
107
+  [ -n "$CLASSPATH" ] &&
108
+    CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
109
+fi
110
+
111
+# For Mingw, ensure paths are in UNIX format before anything is touched
112
+if $mingw ; then
113
+  [ -n "$M2_HOME" ] &&
114
+    M2_HOME="`(cd "$M2_HOME"; pwd)`"
115
+  [ -n "$JAVA_HOME" ] &&
116
+    JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
117
+  # TODO classpath?
118
+fi
119
+
120
+if [ -z "$JAVA_HOME" ]; then
121
+  javaExecutable="`which javac`"
122
+  if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
123
+    # readlink(1) is not available as standard on Solaris 10.
124
+    readLink=`which readlink`
125
+    if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
126
+      if $darwin ; then
127
+        javaHome="`dirname \"$javaExecutable\"`"
128
+        javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
129
+      else
130
+        javaExecutable="`readlink -f \"$javaExecutable\"`"
131
+      fi
132
+      javaHome="`dirname \"$javaExecutable\"`"
133
+      javaHome=`expr "$javaHome" : '\(.*\)/bin'`
134
+      JAVA_HOME="$javaHome"
135
+      export JAVA_HOME
136
+    fi
137
+  fi
138
+fi
139
+
140
+if [ -z "$JAVACMD" ] ; then
141
+  if [ -n "$JAVA_HOME"  ] ; then
142
+    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
143
+      # IBM's JDK on AIX uses strange locations for the executables
144
+      JAVACMD="$JAVA_HOME/jre/sh/java"
145
+    else
146
+      JAVACMD="$JAVA_HOME/bin/java"
147
+    fi
148
+  else
149
+    JAVACMD="`which java`"
150
+  fi
151
+fi
152
+
153
+if [ ! -x "$JAVACMD" ] ; then
154
+  echo "Error: JAVA_HOME is not defined correctly." >&2
155
+  echo "  We cannot execute $JAVACMD" >&2
156
+  exit 1
157
+fi
158
+
159
+if [ -z "$JAVA_HOME" ] ; then
160
+  echo "Warning: JAVA_HOME environment variable is not set."
161
+fi
162
+
163
+CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
164
+
165
+# traverses directory structure from process work directory to filesystem root
166
+# first directory with .mvn subdirectory is considered project base directory
167
+find_maven_basedir() {
168
+
169
+  if [ -z "$1" ]
170
+  then
171
+    echo "Path not specified to find_maven_basedir"
172
+    return 1
173
+  fi
174
+
175
+  basedir="$1"
176
+  wdir="$1"
177
+  while [ "$wdir" != '/' ] ; do
178
+    if [ -d "$wdir"/.mvn ] ; then
179
+      basedir=$wdir
180
+      break
181
+    fi
182
+    # workaround for JBEAP-8937 (on Solaris 10/Sparc)
183
+    if [ -d "${wdir}" ]; then
184
+      wdir=`cd "$wdir/.."; pwd`
185
+    fi
186
+    # end of workaround
187
+  done
188
+  echo "${basedir}"
189
+}
190
+
191
+# concatenates all lines of a file
192
+concat_lines() {
193
+  if [ -f "$1" ]; then
194
+    echo "$(tr -s '\n' ' ' < "$1")"
195
+  fi
196
+}
197
+
198
+BASE_DIR=`find_maven_basedir "$(pwd)"`
199
+if [ -z "$BASE_DIR" ]; then
200
+  exit 1;
201
+fi
202
+
203
+##########################################################################################
204
+# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
205
+# This allows using the maven wrapper in projects that prohibit checking in binary data.
206
+##########################################################################################
207
+if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
208
+    if [ "$MVNW_VERBOSE" = true ]; then
209
+      echo "Found .mvn/wrapper/maven-wrapper.jar"
210
+    fi
211
+else
212
+    if [ "$MVNW_VERBOSE" = true ]; then
213
+      echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
214
+    fi
215
+    jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"
216
+    while IFS="=" read key value; do
217
+      case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
218
+      esac
219
+    done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
220
+    if [ "$MVNW_VERBOSE" = true ]; then
221
+      echo "Downloading from: $jarUrl"
222
+    fi
223
+    wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
224
+
225
+    if command -v wget > /dev/null; then
226
+        if [ "$MVNW_VERBOSE" = true ]; then
227
+          echo "Found wget ... using wget"
228
+        fi
229
+        wget "$jarUrl" -O "$wrapperJarPath"
230
+    elif command -v curl > /dev/null; then
231
+        if [ "$MVNW_VERBOSE" = true ]; then
232
+          echo "Found curl ... using curl"
233
+        fi
234
+        curl -o "$wrapperJarPath" "$jarUrl"
235
+    else
236
+        if [ "$MVNW_VERBOSE" = true ]; then
237
+          echo "Falling back to using Java to download"
238
+        fi
239
+        javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
240
+        if [ -e "$javaClass" ]; then
241
+            if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
242
+                if [ "$MVNW_VERBOSE" = true ]; then
243
+                  echo " - Compiling MavenWrapperDownloader.java ..."
244
+                fi
245
+                # Compiling the Java class
246
+                ("$JAVA_HOME/bin/javac" "$javaClass")
247
+            fi
248
+            if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
249
+                # Running the downloader
250
+                if [ "$MVNW_VERBOSE" = true ]; then
251
+                  echo " - Running MavenWrapperDownloader.java ..."
252
+                fi
253
+                ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
254
+            fi
255
+        fi
256
+    fi
257
+fi
258
+##########################################################################################
259
+# End of extension
260
+##########################################################################################
261
+
262
+export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
263
+if [ "$MVNW_VERBOSE" = true ]; then
264
+  echo $MAVEN_PROJECTBASEDIR
265
+fi
266
+MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
267
+
268
+# For Cygwin, switch paths to Windows format before running java
269
+if $cygwin; then
270
+  [ -n "$M2_HOME" ] &&
271
+    M2_HOME=`cygpath --path --windows "$M2_HOME"`
272
+  [ -n "$JAVA_HOME" ] &&
273
+    JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
274
+  [ -n "$CLASSPATH" ] &&
275
+    CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
276
+  [ -n "$MAVEN_PROJECTBASEDIR" ] &&
277
+    MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
278
+fi
279
+
280
+WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
281
+
282
+exec "$JAVACMD" \
283
+  $MAVEN_OPTS \
284
+  -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
285
+  "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
286
+  ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"

+ 161
- 0
mvnw.cmd Bestand weergeven

@@ -0,0 +1,161 @@
1
+@REM ----------------------------------------------------------------------------
2
+@REM Licensed to the Apache Software Foundation (ASF) under one
3
+@REM or more contributor license agreements.  See the NOTICE file
4
+@REM distributed with this work for additional information
5
+@REM regarding copyright ownership.  The ASF licenses this file
6
+@REM to you under the Apache License, Version 2.0 (the
7
+@REM "License"); you may not use this file except in compliance
8
+@REM with the License.  You may obtain a copy of the License at
9
+@REM
10
+@REM    https://www.apache.org/licenses/LICENSE-2.0
11
+@REM
12
+@REM Unless required by applicable law or agreed to in writing,
13
+@REM software distributed under the License is distributed on an
14
+@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15
+@REM KIND, either express or implied.  See the License for the
16
+@REM specific language governing permissions and limitations
17
+@REM under the License.
18
+@REM ----------------------------------------------------------------------------
19
+
20
+@REM ----------------------------------------------------------------------------
21
+@REM Maven2 Start Up Batch script
22
+@REM
23
+@REM Required ENV vars:
24
+@REM JAVA_HOME - location of a JDK home dir
25
+@REM
26
+@REM Optional ENV vars
27
+@REM M2_HOME - location of maven2's installed home dir
28
+@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
29
+@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending
30
+@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
31
+@REM     e.g. to debug Maven itself, use
32
+@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
33
+@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
34
+@REM ----------------------------------------------------------------------------
35
+
36
+@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
37
+@echo off
38
+@REM set title of command window
39
+title %0
40
+@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'
41
+@if "%MAVEN_BATCH_ECHO%" == "on"  echo %MAVEN_BATCH_ECHO%
42
+
43
+@REM set %HOME% to equivalent of $HOME
44
+if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
45
+
46
+@REM Execute a user defined script before this one
47
+if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
48
+@REM check for pre script, once with legacy .bat ending and once with .cmd ending
49
+if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
50
+if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
51
+:skipRcPre
52
+
53
+@setlocal
54
+
55
+set ERROR_CODE=0
56
+
57
+@REM To isolate internal variables from possible post scripts, we use another setlocal
58
+@setlocal
59
+
60
+@REM ==== START VALIDATION ====
61
+if not "%JAVA_HOME%" == "" goto OkJHome
62
+
63
+echo.
64
+echo Error: JAVA_HOME not found in your environment. >&2
65
+echo Please set the JAVA_HOME variable in your environment to match the >&2
66
+echo location of your Java installation. >&2
67
+echo.
68
+goto error
69
+
70
+:OkJHome
71
+if exist "%JAVA_HOME%\bin\java.exe" goto init
72
+
73
+echo.
74
+echo Error: JAVA_HOME is set to an invalid directory. >&2
75
+echo JAVA_HOME = "%JAVA_HOME%" >&2
76
+echo Please set the JAVA_HOME variable in your environment to match the >&2
77
+echo location of your Java installation. >&2
78
+echo.
79
+goto error
80
+
81
+@REM ==== END VALIDATION ====
82
+
83
+:init
84
+
85
+@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
86
+@REM Fallback to current working directory if not found.
87
+
88
+set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
89
+IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
90
+
91
+set EXEC_DIR=%CD%
92
+set WDIR=%EXEC_DIR%
93
+:findBaseDir
94
+IF EXIST "%WDIR%"\.mvn goto baseDirFound
95
+cd ..
96
+IF "%WDIR%"=="%CD%" goto baseDirNotFound
97
+set WDIR=%CD%
98
+goto findBaseDir
99
+
100
+:baseDirFound
101
+set MAVEN_PROJECTBASEDIR=%WDIR%
102
+cd "%EXEC_DIR%"
103
+goto endDetectBaseDir
104
+
105
+:baseDirNotFound
106
+set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
107
+cd "%EXEC_DIR%"
108
+
109
+:endDetectBaseDir
110
+
111
+IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
112
+
113
+@setlocal EnableExtensions EnableDelayedExpansion
114
+for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
115
+@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
116
+
117
+:endReadAdditionalConfig
118
+
119
+SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
120
+set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
121
+set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
122
+
123
+set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"
124
+FOR /F "tokens=1,2 delims==" %%A IN (%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties) DO (
125
+	IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B 
126
+)
127
+
128
+@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
129
+@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
130
+if exist %WRAPPER_JAR% (
131
+    echo Found %WRAPPER_JAR%
132
+) else (
133
+    echo Couldn't find %WRAPPER_JAR%, downloading it ...
134
+	echo Downloading from: %DOWNLOAD_URL%
135
+    powershell -Command "(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"
136
+    echo Finished downloading %WRAPPER_JAR%
137
+)
138
+@REM End of extension
139
+
140
+%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
141
+if ERRORLEVEL 1 goto error
142
+goto end
143
+
144
+:error
145
+set ERROR_CODE=1
146
+
147
+:end
148
+@endlocal & set ERROR_CODE=%ERROR_CODE%
149
+
150
+if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
151
+@REM check for post script, once with legacy .bat ending and once with .cmd ending
152
+if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
153
+if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
154
+:skipRcPost
155
+
156
+@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
157
+if "%MAVEN_BATCH_PAUSE%" == "on" pause
158
+
159
+if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
160
+
161
+exit /B %ERROR_CODE%

+ 72
- 0
pom.xml Bestand weergeven

@@ -0,0 +1,72 @@
1
+<?xml version="1.0" encoding="UTF-8"?>
2
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3
+	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4
+	<modelVersion>4.0.0</modelVersion>
5
+	<parent>
6
+		<groupId>org.springframework.boot</groupId>
7
+		<artifactId>spring-boot-starter-parent</artifactId>
8
+		<version>2.1.5.RELEASE</version>
9
+		<relativePath/> <!-- lookup parent from repository -->
10
+	</parent>
11
+	<groupId>com.huiju</groupId>
12
+	<artifactId>miniapp</artifactId>
13
+	<version>v0.0.1</version>
14
+	<name>miniapp</name>
15
+	<description>MiniApp micro-service</description>
16
+
17
+	<properties>
18
+		<java.version>1.8</java.version>
19
+	</properties>
20
+
21
+	<dependencies>
22
+		<dependency>
23
+			<groupId>org.springframework.boot</groupId>
24
+			<artifactId>spring-boot-starter-web</artifactId>
25
+		</dependency>
26
+		<dependency>
27
+			<groupId>com.baomidou</groupId>
28
+			<artifactId>mybatis-plus-boot-starter</artifactId>
29
+			<version>3.1.1</version>
30
+		</dependency>
31
+		<dependency>
32
+			<groupId>org.springframework.boot</groupId>
33
+			<artifactId>spring-boot-starter-jdbc</artifactId>
34
+		</dependency>
35
+
36
+		<dependency>
37
+			<groupId>mysql</groupId>
38
+			<artifactId>mysql-connector-java</artifactId>
39
+			<scope>runtime</scope>
40
+		</dependency>
41
+		<dependency>
42
+			<groupId>org.projectlombok</groupId>
43
+			<artifactId>lombok</artifactId>
44
+			<optional>true</optional>
45
+		</dependency>
46
+		<dependency>
47
+			<groupId>com.github.binarywang</groupId>
48
+			<artifactId>weixin-java-miniapp</artifactId>
49
+			<version>3.3.0</version>
50
+		</dependency>
51
+		<dependency>
52
+			<groupId>com.alibaba</groupId>
53
+			<artifactId>fastjson</artifactId>
54
+			<version>1.2.56</version>
55
+		</dependency>
56
+		<dependency>
57
+			<groupId>com.squareup.okhttp3</groupId>
58
+			<artifactId>okhttp</artifactId>
59
+			<version>3.14.2</version>
60
+		</dependency>
61
+	</dependencies>
62
+
63
+	<build>
64
+		<plugins>
65
+			<plugin>
66
+				<groupId>org.springframework.boot</groupId>
67
+				<artifactId>spring-boot-maven-plugin</artifactId>
68
+			</plugin>
69
+		</plugins>
70
+	</build>
71
+
72
+</project>

+ 13
- 0
src/main/java/com/huiju/miniapp/MiniappApplication.java Bestand weergeven

@@ -0,0 +1,13 @@
1
+package com.huiju.miniapp;
2
+
3
+import org.springframework.boot.SpringApplication;
4
+import org.springframework.boot.autoconfigure.SpringBootApplication;
5
+
6
+@SpringBootApplication
7
+public class MiniappApplication {
8
+
9
+	public static void main(String[] args) {
10
+		SpringApplication.run(MiniappApplication.class, args);
11
+	}
12
+
13
+}

+ 41
- 0
src/main/java/com/huiju/miniapp/common/Encrypt.java Bestand weergeven

@@ -0,0 +1,41 @@
1
+package com.huiju.miniapp.common;
2
+
3
+import org.apache.commons.codec.binary.Base64;
4
+import org.springframework.util.DigestUtils;
5
+
6
+import java.io.UnsupportedEncodingException;
7
+import java.net.URLEncoder;
8
+
9
+public class Encrypt {
10
+    public static String md5(String str, String ...salt) {
11
+        byte[] secBytes = null;
12
+
13
+        String plainText = str;
14
+        if (salt.length > 0 && null != salt[0]) {
15
+            plainText += salt[0];
16
+        }
17
+
18
+        return DigestUtils.md5DigestAsHex(plainText.getBytes());
19
+    }
20
+
21
+    public static String base64(String str) {
22
+        String rtn = "";
23
+        try {
24
+            rtn = new String(Base64.encodeBase64(str.getBytes("UTF-8")));
25
+        } catch (UnsupportedEncodingException e) {
26
+            e.printStackTrace();
27
+        }
28
+
29
+        return rtn;
30
+    }
31
+
32
+    public static String urlEncode(String str) {
33
+        String rtn = "";
34
+        try {
35
+            rtn = URLEncoder.encode(str, "UTF-8");
36
+        } catch (UnsupportedEncodingException e) {
37
+            e.printStackTrace();
38
+        }
39
+        return rtn;
40
+    }
41
+}

+ 42
- 0
src/main/java/com/huiju/miniapp/common/HttpUtil.java Bestand weergeven

@@ -0,0 +1,42 @@
1
+package com.huiju.miniapp.common;
2
+
3
+import okhttp3.*;
4
+
5
+import java.io.IOException;
6
+
7
+public class HttpUtil {
8
+    public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
9
+    static OkHttpClient client = new OkHttpClient();
10
+
11
+    /**
12
+     * 暂时不对结果负责
13
+     * @param url
14
+     * @param json
15
+     * @throws IOException
16
+     */
17
+    public static void post(String url, String json) throws IOException {
18
+        RequestBody body = RequestBody.create(JSON, json);
19
+        Request request = new Request.Builder()
20
+                .url(url)
21
+                .post(body)
22
+                .build();
23
+        client.newCall(request).execute();
24
+    }
25
+
26
+    public static void asyncPost(String url, String json) {
27
+        new Thread() {
28
+            public void run() {
29
+                RequestBody body = RequestBody.create(JSON, json);
30
+                Request request = new Request.Builder()
31
+                        .url(url)
32
+                        .post(body)
33
+                        .build();
34
+                try {
35
+                    client.newCall(request).execute();
36
+                } catch (IOException e) {
37
+                    e.printStackTrace();
38
+                }
39
+            }
40
+        }.start();
41
+    }
42
+}

+ 59
- 0
src/main/java/com/huiju/miniapp/common/InitWxMaService.java Bestand weergeven

@@ -0,0 +1,59 @@
1
+package com.huiju.miniapp.common;
2
+
3
+import cn.binarywang.wx.miniapp.api.WxMaService;
4
+import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
5
+import cn.binarywang.wx.miniapp.config.WxMaInMemoryConfig;
6
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
7
+import com.huiju.miniapp.entity.MiniappConfiger;
8
+import com.huiju.miniapp.service.IMiniappConfigerService;
9
+import org.springframework.beans.factory.annotation.Autowired;
10
+import org.springframework.stereotype.Component;
11
+
12
+import javax.annotation.PostConstruct;
13
+import java.util.HashMap;
14
+import java.util.List;
15
+import java.util.Map;
16
+
17
+@Component
18
+public class InitWxMaService {
19
+    private static Map<String, WxMaService> maServices = new HashMap<>();
20
+
21
+    @Autowired
22
+    IMiniappConfigerService miniappConfigerService;
23
+
24
+    public static WxMaService getMaService(String appid) {
25
+        return maServices.get(appid);
26
+    }
27
+
28
+    @PostConstruct
29
+    public void init() {
30
+        QueryWrapper<MiniappConfiger> queryWrapper = new QueryWrapper<>();
31
+        queryWrapper.eq("state", 1);
32
+        List<MiniappConfiger> configs = miniappConfigerService.list();
33
+        if (null == configs || configs.size() == 0) return;
34
+
35
+        for (MiniappConfiger config: configs) {
36
+            initService(config);
37
+        }
38
+    }
39
+
40
+    public static WxMaService initService(MiniappConfiger config) {
41
+        WxMaInMemoryConfig wxMaInMemoryConfig = new WxMaInMemoryConfig();
42
+        wxMaInMemoryConfig.setAppid(config.getAppid());
43
+        wxMaInMemoryConfig.setSecret(config.getSecret());
44
+        wxMaInMemoryConfig.setToken(config.getToken());
45
+        wxMaInMemoryConfig.setAesKey(config.getAesKey());
46
+        wxMaInMemoryConfig.setMsgDataFormat(config.getMsgDataFormat());
47
+
48
+        WxMaService service = new WxMaServiceImpl();
49
+        service.setWxMaConfig(wxMaInMemoryConfig);
50
+
51
+        maServices.put(config.getAppid(), service);
52
+        return service;
53
+    }
54
+
55
+    public static WxMaService resetService(MiniappConfiger config) {
56
+        maServices.remove(config.getAppid());
57
+        return initService(config);
58
+    }
59
+}

+ 56
- 0
src/main/java/com/huiju/miniapp/common/ResponseBean.java Bestand weergeven

@@ -0,0 +1,56 @@
1
+package com.huiju.miniapp.common;
2
+
3
+import java.io.Serializable;
4
+
5
+/**
6
+ * 接口统一状态返回BEAN.
7
+ */
8
+public class ResponseBean<T> implements Serializable {
9
+
10
+    private static final long serialVersionUID = 3593827217136880822L;
11
+
12
+    public static final int CODE_SUCCESS = 0;
13
+
14
+    private int code;
15
+    private String message;
16
+    private T data;
17
+
18
+    public static <T> ResponseBean success(T data, String ...msgs) {
19
+        ResponseBean responseBean = new ResponseBean();
20
+        responseBean.code = ResponseBean.CODE_SUCCESS;
21
+        responseBean.data = data;
22
+
23
+        if (null != msgs && msgs.length > 0) {
24
+            responseBean.message = msgs[0];
25
+        }
26
+
27
+        return responseBean;
28
+    }
29
+
30
+    public static <T> ResponseBean error(String msg, int code, T ...datas) {
31
+        ResponseBean responseBean = new ResponseBean();
32
+        responseBean.code = code;
33
+        responseBean.message = msg;
34
+
35
+        if (null != datas && datas.length > 0) {
36
+            responseBean.data = datas[0];
37
+        }
38
+
39
+        return responseBean;
40
+    }
41
+
42
+    public T getData() {
43
+        return this.data;
44
+    }
45
+    public int getCode() {
46
+        return this.code;
47
+    }
48
+    public String getMessage() {
49
+        return this.message;
50
+    }
51
+
52
+    @Override
53
+    public String toString() {
54
+        return  "{ code: "+code+", message: "+message+", data: <T> }";
55
+    }
56
+}

+ 43
- 0
src/main/java/com/huiju/miniapp/common/TemplateMsgUtil.java Bestand weergeven

@@ -0,0 +1,43 @@
1
+package com.huiju.miniapp.common;
2
+
3
+import cn.binarywang.wx.miniapp.bean.WxMaTemplateData;
4
+import cn.binarywang.wx.miniapp.bean.WxMaTemplateMessage;
5
+
6
+import java.util.ArrayList;
7
+import java.util.List;
8
+import java.util.Map;
9
+
10
+
11
+public class TemplateMsgUtil {
12
+
13
+    public static WxMaTemplateMessage create(String tplId, String formId, String toUser, String page, List<Object> data) {
14
+        if (null == data || data.size() == 0) return null;
15
+        if (null == tplId || null == formId || null == toUser) return null;
16
+
17
+        List<WxMaTemplateData> tplData = new ArrayList<>();
18
+
19
+        for (int i = 1; i <= tplData.size(); i ++) {
20
+            Object o = data.get(i - 1);
21
+
22
+            String val = null;
23
+            String color = "#173177";
24
+            if (o instanceof String ) {
25
+                val = (String) o;
26
+            } else if (o instanceof Map) {
27
+                val = (String) ((Map) o).get("value");
28
+
29
+                String colour = (String) ((Map) o).get("color");
30
+                if (null != colour && colour.startsWith("#")) {
31
+                    color = colour;
32
+                }
33
+            } else {
34
+                throw new IllegalArgumentException("发送内容暂时不支持 " + o.getClass() + "格式数据");
35
+            }
36
+
37
+            String name = "keyword" + i;
38
+            tplData.add(new WxMaTemplateData(name, val, color));
39
+        }
40
+
41
+        return WxMaTemplateMessage.builder().templateId(tplId).formId(formId).page(page).data(tplData).toUser(toUser).build();
42
+    }
43
+}

+ 26
- 0
src/main/java/com/huiju/miniapp/config/AccessConfig.java Bestand weergeven

@@ -0,0 +1,26 @@
1
+package com.huiju.miniapp.config;
2
+
3
+import com.huiju.miniapp.interceptor.AccessInterceptor;
4
+import org.springframework.context.annotation.Configuration;
5
+import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
6
+import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
7
+
8
+import javax.annotation.Resource;
9
+
10
+/**
11
+ * @author FXF
12
+ * @date 2019-02-22
13
+ */
14
+@Configuration
15
+public class AccessConfig implements WebMvcConfigurer {
16
+
17
+	@Resource
18
+	private AccessInterceptor accessInterceptor;
19
+
20
+	@Override
21
+	public void addInterceptors(InterceptorRegistry registry) {
22
+		// 自定义拦截器,添加拦截路径和排除拦截路径
23
+		registry.addInterceptor(accessInterceptor).addPathPatterns("/**");
24
+	}
25
+	
26
+}

+ 110
- 0
src/main/java/com/huiju/miniapp/controller/CommController.java Bestand weergeven

@@ -0,0 +1,110 @@
1
+package com.huiju.miniapp.controller;
2
+
3
+/**
4
+ * 集中处理 管理端系统 接口
5
+ */
6
+
7
+import com.alibaba.fastjson.JSONObject;
8
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
9
+import com.baomidou.mybatisplus.core.metadata.IPage;
10
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
11
+import com.huiju.miniapp.common.Encrypt;
12
+import com.huiju.miniapp.common.InitWxMaService;
13
+import com.huiju.miniapp.common.ResponseBean;
14
+import com.huiju.miniapp.entity.MiniappConfiger;
15
+import com.huiju.miniapp.entity.SystemConfiger;
16
+import com.huiju.miniapp.service.IMiniappConfigerService;
17
+import com.huiju.miniapp.service.ISystemConfigerService;
18
+import org.apache.http.HttpStatus;
19
+import org.springframework.beans.factory.annotation.Autowired;
20
+import org.springframework.web.bind.annotation.*;
21
+
22
+import javax.servlet.http.HttpServletRequest;
23
+import javax.servlet.http.HttpSession;
24
+import java.time.LocalDateTime;
25
+
26
+@RestController
27
+@RequestMapping("/api")
28
+public class CommController {
29
+    @Autowired
30
+    ISystemConfigerService iSystemConfigerService;
31
+
32
+    @Autowired
33
+    IMiniappConfigerService iMiniappConfigerService;
34
+
35
+    @PostMapping("/admin/login")
36
+    public ResponseBean login(@RequestBody String paramStr, HttpServletRequest request) {
37
+        if (null == paramStr || "".equals(paramStr.trim())) {
38
+            return ResponseBean.error("账户或密码不能为空", HttpStatus.SC_BAD_REQUEST);
39
+        }
40
+
41
+        JSONObject params = JSONObject.parseObject(paramStr);
42
+        if (null == params) {
43
+            return ResponseBean.error("登录参数输出格式非法", HttpStatus.SC_BAD_REQUEST);
44
+        }
45
+
46
+        HttpSession httpSession = request.getSession();
47
+        String user = params.getString("user");
48
+        String password = params.getString("password");
49
+        if (null == user || null == password) {
50
+            return ResponseBean.error("账户或密码不能为空", HttpStatus.SC_BAD_REQUEST);
51
+        }
52
+
53
+        SystemConfiger systemConfiger = iSystemConfigerService.getByUser(user);
54
+        if (null == systemConfiger) {
55
+            return ResponseBean.error("账户或密码不正确", HttpStatus.SC_BAD_REQUEST);
56
+        }
57
+
58
+        if (!checkPass(user, password, systemConfiger.getPassword())) {
59
+            return ResponseBean.error("账户或密码不正确", HttpStatus.SC_BAD_REQUEST);
60
+        }
61
+
62
+        // 登录成功
63
+        httpSession.setAttribute("token", user);
64
+        systemConfiger.setPassword("");
65
+        return ResponseBean.success(systemConfiger);
66
+    }
67
+
68
+    @PostMapping("/admin/logout")
69
+    public ResponseBean logout(HttpServletRequest request) {
70
+        HttpSession httpSession = request.getSession();
71
+        httpSession.removeAttribute("token");
72
+        return ResponseBean.success("");
73
+    }
74
+
75
+    @GetMapping("/admin/miniapp")
76
+    public ResponseBean list(
77
+            @RequestParam(defaultValue = "1") Integer page,
78
+            @RequestParam(defaultValue = "10") Integer pageSize
79
+    ) {
80
+        IPage<MiniappConfiger> pg = new Page<>(page, pageSize);
81
+        QueryWrapper<MiniappConfiger> wrapper = new QueryWrapper<>();
82
+        wrapper.orderByDesc("create_date");
83
+
84
+        IPage<MiniappConfiger> result = iMiniappConfigerService.page(pg, wrapper);
85
+        return ResponseBean.success(result);
86
+    }
87
+
88
+
89
+    @PostMapping("/admin/miniapp")
90
+    public ResponseBean save(@RequestBody MiniappConfiger miniappConfiger) {
91
+        return iMiniappConfigerService.registe(miniappConfiger);
92
+    }
93
+
94
+    @PutMapping("/admin/miniapp/{id}")
95
+    public ResponseBean update(@RequestBody MiniappConfiger miniappConfiger) {
96
+        boolean success = iMiniappConfigerService.updateById(miniappConfiger);
97
+
98
+        if (success) {
99
+            InitWxMaService.resetService(miniappConfiger);
100
+            return ResponseBean.success(miniappConfiger);
101
+        } else {
102
+            return ResponseBean.error("更新失败, 请重试", HttpStatus.SC_INTERNAL_SERVER_ERROR);
103
+        }
104
+    }
105
+
106
+    private boolean checkPass(String user, String pass, String compare) {
107
+        String target = Encrypt.md5(pass, user);
108
+        return target.equals(compare);
109
+    }
110
+}

+ 59
- 0
src/main/java/com/huiju/miniapp/controller/MessageController.java Bestand weergeven

@@ -0,0 +1,59 @@
1
+package com.huiju.miniapp.controller;
2
+
3
+import cn.binarywang.wx.miniapp.api.WxMaService;
4
+import cn.binarywang.wx.miniapp.bean.WxMaTemplateMessage;
5
+import com.alibaba.fastjson.JSONArray;
6
+import com.alibaba.fastjson.JSONObject;
7
+import com.huiju.miniapp.common.InitWxMaService;
8
+import com.huiju.miniapp.common.ResponseBean;
9
+import com.huiju.miniapp.common.TemplateMsgUtil;
10
+import org.apache.http.HttpStatus;
11
+import org.springframework.web.bind.annotation.*;
12
+
13
+import java.util.ArrayList;
14
+import java.util.List;
15
+
16
+@RestController
17
+@RequestMapping("/api")
18
+public class MessageController {
19
+
20
+    @PostMapping("/{appid}/tpl/{tplId}/form/{formId}/to/{user}")
21
+    public ResponseBean send(
22
+            @PathVariable String appid,
23
+            @PathVariable String tplId,
24
+            @PathVariable String formId,
25
+            @PathVariable String user,
26
+            @RequestBody String paramsStr
27
+    ) {
28
+        if (null == paramsStr || "".equals(paramsStr.trim())) {
29
+            return ResponseBean.error("发送内容不能为空", HttpStatus.SC_NOT_ACCEPTABLE);
30
+        }
31
+
32
+        JSONObject params = JSONObject.parseObject(paramsStr);
33
+        String page = params.getString("page");
34
+        JSONArray data = params.getJSONArray("data");
35
+
36
+        if (null == page) page = "";
37
+        if (null == data || data.isEmpty()) {
38
+            return ResponseBean.error("发送模板数据不能为空", HttpStatus.SC_NOT_ACCEPTABLE);
39
+        }
40
+
41
+        List<Object> dt = new ArrayList<>();
42
+        for (int i = 0; i < data.size(); i++) {
43
+            dt.add(data.get(i));
44
+        }
45
+
46
+        WxMaService wxMaService = InitWxMaService.getMaService(appid);
47
+        if (null == wxMaService) return ResponseBean.error("当前小程序未注册接口", HttpStatus.SC_BAD_REQUEST);
48
+
49
+        try {
50
+            WxMaTemplateMessage message = TemplateMsgUtil.create(tplId, formId, user, page, dt);
51
+            wxMaService.getMsgService().sendTemplateMsg(message);
52
+        } catch (Exception e) {
53
+            e.printStackTrace();
54
+            return ResponseBean.error("发送模板消息失败" + e.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR);
55
+        }
56
+
57
+        return ResponseBean.success("模板消息发送成功");
58
+    }
59
+}

+ 112
- 0
src/main/java/com/huiju/miniapp/controller/MiniAppController.java Bestand weergeven

@@ -0,0 +1,112 @@
1
+package com.huiju.miniapp.controller;
2
+
3
+import cn.binarywang.wx.miniapp.api.WxMaService;
4
+import cn.binarywang.wx.miniapp.bean.WxMaMessage;
5
+import cn.binarywang.wx.miniapp.constant.WxMaConstants;
6
+import com.huiju.miniapp.common.HttpUtil;
7
+import com.huiju.miniapp.common.InitWxMaService;
8
+import com.huiju.miniapp.common.ResponseBean;
9
+import com.huiju.miniapp.entity.MiniappConfiger;
10
+import com.huiju.miniapp.service.IMiniappConfigerService;
11
+import org.apache.http.HttpStatus;
12
+import org.springframework.beans.factory.annotation.Autowired;
13
+import org.springframework.web.bind.annotation.*;
14
+
15
+import java.time.LocalDateTime;
16
+import java.util.Objects;
17
+
18
+@RestController
19
+@RequestMapping("/api")
20
+public class MiniAppController {
21
+
22
+    @Autowired
23
+    IMiniappConfigerService miniappConfigerService;
24
+
25
+    @PostMapping("/{appid}/signup")
26
+    public ResponseBean registe(@PathVariable String appid, @RequestBody MiniappConfiger miniappConfiger) {
27
+        if (!appid.equals(miniappConfiger.getAppid())) {
28
+            return ResponseBean.error("注册参数与请求路径不匹配", HttpStatus.SC_BAD_REQUEST);
29
+        }
30
+
31
+        // 印象中 secret 必须长度 43
32
+        if (null == miniappConfiger.getSecret() || miniappConfiger.getSecret().length() < 5) {
33
+            return ResponseBean.error("小程序 secret 参数为空或非法", HttpStatus.SC_BAD_REQUEST);
34
+        }
35
+
36
+        ResponseBean resp = miniappConfigerService.registe(miniappConfiger);
37
+        if (resp.getCode() == ResponseBean.CODE_SUCCESS) {
38
+            return ResponseBean.success("服务注册成功");
39
+        }
40
+
41
+        return resp;
42
+    }
43
+
44
+    /**
45
+     * 小程序接入
46
+     * 没有进行 signature 校验, 直接返回 echostr
47
+     * @param echostr
48
+     * @return
49
+     */
50
+    @GetMapping("/{appid}/portal")
51
+    public String access(String echostr) {
52
+        return echostr;
53
+    }
54
+
55
+    @PostMapping("/{appid}/portal")
56
+    public String receiveMsg(@PathVariable String appid,
57
+                             @RequestBody String requestBody,
58
+                             @RequestParam(name = "msg_signature", required = false) String msgSignature,
59
+                             @RequestParam(name = "encrypt_type", required = false) String encryptType,
60
+                             @RequestParam(name = "signature", required = false) String signature,
61
+                             @RequestParam("timestamp") String timestamp,
62
+                             @RequestParam("nonce") String nonce) {
63
+        final WxMaService wxService = InitWxMaService.getMaService(appid);
64
+        if (null == wxService) {
65
+            throw new RuntimeException("未注册的小程序服务:" + encryptType);
66
+        }
67
+
68
+        MiniappConfiger miniappConfiger = miniappConfigerService.getById(appid);
69
+        if (null == miniappConfiger) {
70
+            return "success";
71
+        }
72
+
73
+        // 如果小程序服务端没有设置回调接口, 就放弃接收到的消息
74
+        String cbURL = miniappConfiger.getCallbackUrl();
75
+        if (null == cbURL || "".equals(cbURL.trim())) {
76
+            return "success";
77
+        } else {
78
+            cbURL += "/message";
79
+        }
80
+
81
+        final boolean isJson = Objects.equals(wxService.getWxMaConfig().getMsgDataFormat(),
82
+                WxMaConstants.MsgDataFormat.JSON);
83
+        if (null == encryptType || "".equals(encryptType.trim())) {
84
+            // 明文传输的消息
85
+            WxMaMessage inMessage;
86
+            if (isJson) {
87
+                inMessage = WxMaMessage.fromJson(requestBody);
88
+            } else {//xml
89
+                inMessage = WxMaMessage.fromXml(requestBody);
90
+            }
91
+
92
+            HttpUtil.asyncPost(cbURL, inMessage.toJson());
93
+            return "success";
94
+        }
95
+
96
+        if ("aes".equals(encryptType)) {
97
+            // 是aes加密的消息
98
+            WxMaMessage inMessage;
99
+            if (isJson) {
100
+                inMessage = WxMaMessage.fromEncryptedJson(requestBody, wxService.getWxMaConfig());
101
+            } else {//xml
102
+                inMessage = WxMaMessage.fromEncryptedXml(requestBody, wxService.getWxMaConfig(),
103
+                        timestamp, nonce, msgSignature);
104
+            }
105
+
106
+            HttpUtil.asyncPost(cbURL, inMessage.toJson());
107
+            return "success";
108
+        }
109
+
110
+        throw new RuntimeException("不可识别的加密类型:" + encryptType);
111
+    }
112
+}

+ 67
- 0
src/main/java/com/huiju/miniapp/controller/UserController.java Bestand weergeven

@@ -0,0 +1,67 @@
1
+package com.huiju.miniapp.controller;
2
+
3
+import cn.binarywang.wx.miniapp.api.WxMaService;
4
+import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
5
+import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
6
+import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
7
+import com.huiju.miniapp.common.InitWxMaService;
8
+import com.huiju.miniapp.common.ResponseBean;
9
+import me.chanjar.weixin.common.error.WxErrorException;
10
+import org.apache.http.HttpStatus;
11
+import org.springframework.web.bind.annotation.GetMapping;
12
+import org.springframework.web.bind.annotation.PathVariable;
13
+import org.springframework.web.bind.annotation.RequestMapping;
14
+import org.springframework.web.bind.annotation.RestController;
15
+
16
+@RestController
17
+@RequestMapping("/api/miniapp")
18
+public class UserController {
19
+
20
+    @GetMapping("/{appid}/login")
21
+    public ResponseBean login(@PathVariable String appid, String code) {
22
+        if (null == code || "".equals(code.trim())) {
23
+            return ResponseBean.error("code 不能为空", HttpStatus.SC_BAD_REQUEST);
24
+        }
25
+
26
+        final WxMaService wxService = InitWxMaService.getMaService(appid);
27
+
28
+        try {
29
+            WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(code);
30
+            return ResponseBean.success(session);
31
+        } catch (WxErrorException e) {
32
+            e.printStackTrace();
33
+            return ResponseBean.error("依据 code 解析 session 失败, " + e.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR);
34
+        }
35
+    }
36
+
37
+    @GetMapping("/{appid}/user/info")
38
+    public ResponseBean info(@PathVariable String appid, String sessionKey,
39
+                       String signature, String rawData, String encryptedData, String iv) {
40
+
41
+        final WxMaService wxService = InitWxMaService.getMaService(appid);
42
+
43
+        // 用户信息校验
44
+        if (!wxService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
45
+            return  ResponseBean.error("校验 session 加密数据失败", HttpStatus.SC_INTERNAL_SERVER_ERROR);
46
+        }
47
+
48
+        // 解密用户信息
49
+        WxMaUserInfo userInfo = wxService.getUserService().getUserInfo(sessionKey, encryptedData, iv);
50
+        return ResponseBean.success(userInfo);
51
+    }
52
+
53
+    @GetMapping("/{appid}/user/phone")
54
+    public ResponseBean phone(@PathVariable String appid, String sessionKey, String signature,
55
+                        String rawData, String encryptedData, String iv) {
56
+        final WxMaService wxService = InitWxMaService.getMaService(appid);
57
+
58
+        // 用户信息校验
59
+        if (!wxService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
60
+            return ResponseBean.error("校验 session 加密数据失败", HttpStatus.SC_INTERNAL_SERVER_ERROR);
61
+        }
62
+
63
+        // 解密
64
+        WxMaPhoneNumberInfo phoneNoInfo = wxService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);
65
+        return ResponseBean.success(phoneNoInfo);
66
+    }
67
+}

+ 45
- 0
src/main/java/com/huiju/miniapp/entity/MiniappConfiger.java Bestand weergeven

@@ -0,0 +1,45 @@
1
+package com.huiju.miniapp.entity;
2
+
3
+import com.baomidou.mybatisplus.annotation.IdType;
4
+import com.baomidou.mybatisplus.annotation.TableId;
5
+import lombok.Data;
6
+import lombok.EqualsAndHashCode;
7
+import lombok.experimental.Accessors;
8
+
9
+import java.io.Serializable;
10
+import java.time.LocalDateTime;
11
+
12
+/**
13
+ * <p>
14
+ * 
15
+ * </p>
16
+ *
17
+ * @author jobob
18
+ * @since 2019-06-05
19
+ */
20
+@Data
21
+@EqualsAndHashCode(callSuper = false)
22
+@Accessors(chain = true)
23
+public class MiniappConfiger implements Serializable {
24
+
25
+    private static final long serialVersionUID = 1L;
26
+
27
+    @TableId(value = "appid", type=IdType.INPUT)
28
+    private String appid;
29
+
30
+    private String appname;
31
+
32
+    private String secret;
33
+
34
+    private String token;
35
+
36
+    private String aesKey;
37
+
38
+    private String msgDataFormat;
39
+
40
+    private Integer state;
41
+
42
+    private String callbackUrl;
43
+
44
+    private LocalDateTime createDate;
45
+}

+ 31
- 0
src/main/java/com/huiju/miniapp/entity/SystemConfiger.java Bestand weergeven

@@ -0,0 +1,31 @@
1
+package com.huiju.miniapp.entity;
2
+
3
+import com.baomidou.mybatisplus.annotation.IdType;
4
+import com.baomidou.mybatisplus.annotation.TableField;
5
+import com.baomidou.mybatisplus.annotation.TableId;
6
+import lombok.Data;
7
+import lombok.EqualsAndHashCode;
8
+import lombok.experimental.Accessors;
9
+
10
+import java.io.Serializable;
11
+
12
+@Data
13
+@EqualsAndHashCode(callSuper = false)
14
+@Accessors(chain = true)
15
+public class SystemConfiger implements Serializable {
16
+
17
+    private static final long serialVersionUID = 1L;
18
+
19
+    @TableId(value = "id", type=IdType.AUTO)
20
+    private String id;
21
+
22
+    @TableField("`user`")
23
+    private String user;
24
+
25
+    private String userName;
26
+
27
+    @TableField("`password`")
28
+    private String password;
29
+
30
+    private String ApiUrl;
31
+}

+ 141
- 0
src/main/java/com/huiju/miniapp/interceptor/AccessInterceptor.java Bestand weergeven

@@ -0,0 +1,141 @@
1
+package com.huiju.miniapp.interceptor;
2
+
3
+import com.alibaba.fastjson.JSONObject;
4
+import com.huiju.miniapp.common.Encrypt;
5
+import com.huiju.miniapp.common.ResponseBean;
6
+import com.huiju.miniapp.entity.MiniappConfiger;
7
+import com.huiju.miniapp.service.IMiniappConfigerService;
8
+import org.apache.http.HttpStatus;
9
+import org.springframework.beans.factory.annotation.Autowired;
10
+import org.springframework.stereotype.Component;
11
+import org.springframework.web.servlet.HandlerInterceptor;
12
+import org.springframework.web.servlet.ModelAndView;
13
+
14
+import javax.servlet.http.HttpServletRequest;
15
+import javax.servlet.http.HttpServletResponse;
16
+import javax.servlet.http.HttpSession;
17
+import java.util.HashMap;
18
+import java.util.Map;
19
+import java.util.regex.Pattern;
20
+
21
+@Component
22
+public class AccessInterceptor implements HandlerInterceptor {
23
+    @Autowired
24
+    IMiniappConfigerService iMiniappConfigerService;
25
+
26
+    // 正则白名单
27
+    private String[] whiteList = {
28
+            "/api/admin/login",
29
+            "/api/[^/]*/signup",
30
+    };
31
+
32
+    /*
33
+     * 视图渲染之后的操作
34
+     */
35
+    @Override
36
+    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
37
+            throws Exception {
38
+
39
+    }
40
+
41
+    /*
42
+     * 处理请求完成后视图渲染之前的处理操作
43
+     */
44
+    @Override
45
+    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
46
+            throws Exception {
47
+
48
+    }
49
+
50
+    /*
51
+     * 进入controller层之前拦截请求
52
+     */
53
+    @Override
54
+    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
55
+        // 白名单跳过
56
+        if (inWhiteList(request)) {
57
+            return true;
58
+        }
59
+
60
+        return isPcAdmin(request) ? checkSession(request, response, obj) : checkMiniApp(request, response, obj);
61
+    }
62
+
63
+    private boolean checkMiniApp(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
64
+
65
+        // 消息头必须包含 authorization 字段
66
+        String token = request.getHeader("x-token");
67
+        if (null == token || "".equals(token)) {
68
+            ResponseBean resp = ResponseBean.error("请先进行系统登录操作", HttpStatus.SC_UNAUTHORIZED);
69
+
70
+            response.addHeader("Content-type", "application/json");
71
+            response.getOutputStream().write(JSONObject.toJSONBytes(resp));
72
+            return false;
73
+        }
74
+
75
+        String uri = request.getRequestURI();
76
+        String[] pathItems = uri.split("/");
77
+        if (null == pathItems || pathItems.length < 2) {
78
+            ResponseBean resp = ResponseBean.error("调用接口非法", HttpStatus.SC_BAD_REQUEST);
79
+
80
+            response.addHeader("Content-type", "application/json");
81
+            response.getOutputStream().write(JSONObject.toJSONBytes(resp));
82
+            return false;
83
+        }
84
+
85
+        String appid = pathItems[2];
86
+        MiniappConfiger configer = iMiniappConfigerService.getById(appid);
87
+        if (null == configer) {
88
+            ResponseBean resp = ResponseBean.error("请先进行服务注册", HttpStatus.SC_UNAUTHORIZED);
89
+
90
+            response.addHeader("Content-type", "application/json");
91
+            response.getOutputStream().write(JSONObject.toJSONBytes(resp));
92
+            return false;
93
+        }
94
+
95
+        if (!Encrypt.md5(configer.getSecret(), appid).equals(token)) {
96
+            ResponseBean resp = ResponseBean.error("权限校验失败, 非法调用", HttpStatus.SC_UNAUTHORIZED);
97
+
98
+            response.addHeader("Content-type", "application/json");
99
+            response.getOutputStream().write(JSONObject.toJSONBytes(resp));
100
+            return false;
101
+        }
102
+
103
+        return true;
104
+    }
105
+
106
+    private boolean checkSession(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
107
+
108
+        HttpSession httpSession = request.getSession();
109
+        String token = (String) httpSession.getAttribute("token");
110
+
111
+        // 如果未登录
112
+        if (null == token || "".equals(token)) {
113
+            Map error = new HashMap<String, Object>();
114
+            error.put("code", HttpStatus.SC_UNAUTHORIZED);
115
+            error.put("message", "请先登录系统");
116
+            response.addHeader("Content-type", "application/json");
117
+            response.getOutputStream().write(JSONObject.toJSONBytes(error));
118
+            return false;
119
+        }
120
+        return true;
121
+    }
122
+
123
+    private boolean isPcAdmin(HttpServletRequest request) {
124
+        String uri = request.getRequestURI();
125
+        return uri.startsWith("/api/admin");
126
+    }
127
+
128
+    private boolean inWhiteList(HttpServletRequest request) {
129
+        String requestURI = request.getRequestURI();
130
+
131
+        for (String it : whiteList) {
132
+            if (Pattern.matches(it, requestURI)) {
133
+                return true;
134
+            }
135
+        }
136
+
137
+        return false;
138
+    }
139
+
140
+}
141
+

+ 18
- 0
src/main/java/com/huiju/miniapp/mapper/MiniappConfigerMapper.java Bestand weergeven

@@ -0,0 +1,18 @@
1
+package com.huiju.miniapp.mapper;
2
+
3
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
4
+import com.huiju.miniapp.entity.MiniappConfiger;
5
+import org.apache.ibatis.annotations.Mapper;
6
+
7
+/**
8
+ * <p>
9
+ *  Mapper 接口
10
+ * </p>
11
+ *
12
+ * @author jobob
13
+ * @since 2019-06-05
14
+ */
15
+@Mapper
16
+public interface MiniappConfigerMapper extends BaseMapper<MiniappConfiger> {
17
+
18
+}

+ 18
- 0
src/main/java/com/huiju/miniapp/mapper/SystemConfigerMapper.java Bestand weergeven

@@ -0,0 +1,18 @@
1
+package com.huiju.miniapp.mapper;
2
+
3
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
4
+import com.huiju.miniapp.entity.SystemConfiger;
5
+import org.apache.ibatis.annotations.Mapper;
6
+
7
+/**
8
+ * <p>
9
+ *  Mapper 接口
10
+ * </p>
11
+ *
12
+ * @author jobob
13
+ * @since 2019-06-05
14
+ */
15
+@Mapper
16
+public interface SystemConfigerMapper extends BaseMapper<SystemConfiger> {
17
+
18
+}

+ 18
- 0
src/main/java/com/huiju/miniapp/service/IMiniappConfigerService.java Bestand weergeven

@@ -0,0 +1,18 @@
1
+package com.huiju.miniapp.service;
2
+
3
+import com.baomidou.mybatisplus.extension.service.IService;
4
+import com.huiju.miniapp.common.ResponseBean;
5
+import com.huiju.miniapp.entity.MiniappConfiger;
6
+
7
+/**
8
+ * <p>
9
+ *  服务类
10
+ * </p>
11
+ *
12
+ * @author jobob
13
+ * @since 2019-06-05
14
+ */
15
+public interface IMiniappConfigerService extends IService<MiniappConfiger> {
16
+
17
+    ResponseBean registe(MiniappConfiger miniappConfiger);
18
+}

+ 17
- 0
src/main/java/com/huiju/miniapp/service/ISystemConfigerService.java Bestand weergeven

@@ -0,0 +1,17 @@
1
+package com.huiju.miniapp.service;
2
+
3
+import com.baomidou.mybatisplus.extension.service.IService;
4
+import com.huiju.miniapp.entity.SystemConfiger;
5
+
6
+/**
7
+ * <p>
8
+ *  服务类
9
+ * </p>
10
+ *
11
+ * @author jobob
12
+ * @since 2019-06-05
13
+ */
14
+public interface ISystemConfigerService extends IService<SystemConfiger> {
15
+
16
+    SystemConfiger getByUser(String user);
17
+}

+ 56
- 0
src/main/java/com/huiju/miniapp/service/impl/MiniappConfigerServiceImpl.java Bestand weergeven

@@ -0,0 +1,56 @@
1
+package com.huiju.miniapp.service.impl;
2
+
3
+import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
4
+import com.huiju.miniapp.common.InitWxMaService;
5
+import com.huiju.miniapp.common.ResponseBean;
6
+import com.huiju.miniapp.entity.MiniappConfiger;
7
+import com.huiju.miniapp.mapper.MiniappConfigerMapper;
8
+import com.huiju.miniapp.service.IMiniappConfigerService;
9
+import org.apache.http.HttpStatus;
10
+import org.springframework.beans.factory.annotation.Autowired;
11
+import org.springframework.stereotype.Service;
12
+
13
+import java.time.LocalDateTime;
14
+
15
+/**
16
+ * <p>
17
+ *  服务实现类
18
+ * </p>
19
+ *
20
+ * @author jobob
21
+ * @since 2019-06-05
22
+ */
23
+@Service
24
+public class MiniappConfigerServiceImpl extends ServiceImpl<MiniappConfigerMapper, MiniappConfiger> implements IMiniappConfigerService {
25
+    @Autowired
26
+    MiniappConfigerMapper miniappConfigerMapper;
27
+
28
+    @Override
29
+    public ResponseBean registe(MiniappConfiger miniappConfiger) {
30
+        String appid = miniappConfiger.getAppid();
31
+        if (null == appid || "".equals(appid.trim())) {
32
+            return ResponseBean.error("小程序 AppID 不能为空", HttpStatus.SC_BAD_REQUEST);
33
+        }
34
+
35
+        // 印象中 secret 必须长度 43
36
+        if (null == miniappConfiger.getSecret() || miniappConfiger.getSecret().length() < 5) {
37
+            return ResponseBean.error("小程序 secret 参数为空或非法", HttpStatus.SC_BAD_REQUEST);
38
+        }
39
+
40
+
41
+        MiniappConfiger config = miniappConfigerMapper.selectById(appid);
42
+        if (null != config) {
43
+            return ResponseBean.error("请不要重复注册小程序服务", HttpStatus.SC_BAD_REQUEST);
44
+        }
45
+
46
+        miniappConfiger.setState(1);
47
+        miniappConfiger.setCreateDate(LocalDateTime.now());
48
+        int succes = miniappConfigerMapper.insert(miniappConfiger);
49
+        if (succes < 1) {
50
+            return ResponseBean.error("服务注册失败", HttpStatus.SC_INTERNAL_SERVER_ERROR);
51
+        }
52
+
53
+        InitWxMaService.initService(miniappConfiger);
54
+        return ResponseBean.success(miniappConfiger);
55
+    }
56
+}

+ 31
- 0
src/main/java/com/huiju/miniapp/service/impl/SystemConfigerServiceImpl.java Bestand weergeven

@@ -0,0 +1,31 @@
1
+package com.huiju.miniapp.service.impl;
2
+
3
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
4
+import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
5
+import com.huiju.miniapp.entity.SystemConfiger;
6
+import com.huiju.miniapp.mapper.SystemConfigerMapper;
7
+import com.huiju.miniapp.service.ISystemConfigerService;
8
+import org.springframework.beans.factory.annotation.Autowired;
9
+import org.springframework.stereotype.Service;
10
+
11
+/**
12
+ * <p>
13
+ *  服务实现类
14
+ * </p>
15
+ *
16
+ * @author jobob
17
+ * @since 2019-06-05
18
+ */
19
+@Service
20
+public class SystemConfigerServiceImpl extends ServiceImpl<SystemConfigerMapper, SystemConfiger> implements ISystemConfigerService {
21
+    @Autowired
22
+    SystemConfigerMapper systemConfigerMapper;
23
+
24
+    @Override
25
+    public SystemConfiger getByUser(String user) {
26
+        QueryWrapper<SystemConfiger> queryWrapper = new QueryWrapper<>();
27
+        queryWrapper.eq("user", user);
28
+
29
+        return systemConfigerMapper.selectOne(queryWrapper);
30
+    }
31
+}

+ 24
- 0
src/main/resources/application.yml Bestand weergeven

@@ -0,0 +1,24 @@
1
+server:
2
+  port: 8001
3
+spring:
4
+  application:
5
+    name: miniapp-service
6
+  datasource:
7
+    username: miniapp
8
+    password: AwQ!0@PJvG2Q9XqG
9
+    url: jdbc:mysql://rm-uf6z3z6jq11x653d77o.mysql.rds.aliyuncs.com:3306/miniapp?useUnicode=true&serverTimezone=CTT&characterEncoding=utf8&allowMultiQueries=true&autoReconnect=true&zeroDateTimeBehavior=convertToNull
10
+    driver-class-name: com.mysql.cj.jdbc.Driver
11
+    initial-size: 10 # 初始化连接数
12
+    max-active: 20 # 最大连接数
13
+    min-idle: 8 # 最小空闲数
14
+    max-idle: 8 # 最大空闲数
15
+
16
+##mybatis-plus
17
+mybatis-plus:
18
+  global-config:
19
+    db-config:
20
+      id-type: auto
21
+  configuration:
22
+    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
23
+    call-setters-on-nulls: true
24
+  mapper-locations: classpath:mapper/*.xml

+ 5
- 0
src/main/resources/mapper/MiniappConfigerMapper.xml Bestand weergeven

@@ -0,0 +1,5 @@
1
+<?xml version="1.0" encoding="UTF-8"?>
2
+<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
3
+<mapper namespace="com.huiju.miniapp.mapper.MiniappConfigerMapper">
4
+
5
+</mapper>

+ 5
- 0
src/main/resources/mapper/SystemConfigerMapper.xml Bestand weergeven

@@ -0,0 +1,5 @@
1
+<?xml version="1.0" encoding="UTF-8"?>
2
+<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
3
+<mapper namespace="com.huiju.miniapp.mapper.SystemConfigerMapper">
4
+
5
+</mapper>