1. 程式人生 > >[Kotlin]第一章、微信公眾平臺驗證

[Kotlin]第一章、微信公眾平臺驗證

有一段時間沒寫過部落格了,最近研究Kotlin,聽說優雅,簡潔,高效,正好需要寫個微信公眾號,順帶手就把Kotlin學習了。

本章要點:

一、簡單介紹

本次要用的技術主要是最新的組合SpringBoot+MySQL+JPA+Redis+Kotlin+Maven,打算全程式碼使用Kotlin來實現,主要使用的元件如下:

  • SpringBoot,1.5.9.RELEASE
  • Spring,4.3.13.RELEASE
  • Spring Security,4.3.13.RELEASE
  • MySQL,5.0+
  • Maven,3.3.X

開發IDE使用IDEA 2017.3,IDEA是Kotlin的創始者,開發Kotlin必然使用IDEA,雖然我比較習慣Eclipse。

二、搭建基本環境

環境搭建其實非常簡單,使用IDEA的嚮導,就能很容易的建立一個Kotlin+maven的專案,怎麼搞?移步到這裡

三、編寫程式碼邏輯

首先,我們先看下Maven的配置檔案

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
>
<modelVersion>4.0.0</modelVersion> <groupId>com.fncity.mp</groupId> <artifactId>fix</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <name>fix</name> <description>Demo project for Spring Boot</description
>
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> <kotlin.version>1.2.10</kotlin.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.session</groupId> <artifactId>spring-session</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.7.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.7.0</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.6</version> </dependency> <dependency> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-stdlib-jdk8</artifactId> <version>${kotlin.version}</version> </dependency> <dependency> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-test</artifactId> <version>${kotlin.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> <version>2.3.0</version> </dependency> <dependency> <groupId>com.sun.xml.bind</groupId> <artifactId>jaxb-core</artifactId> <version>2.3.0</version> </dependency> <dependency> <groupId>com.sun.xml.bind</groupId> <artifactId>jaxb-impl</artifactId> <version>2.3.0</version> </dependency> </dependencies> <build> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*</include> </includes> </resource> </resources> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <plugin> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-maven-plugin</artifactId> <version>${kotlin.version}</version> <executions> <execution> <id>compile</id> <phase>compile</phase> <goals> <goal>compile</goal> </goals> </execution> <execution> <id>test-compile</id> <phase>test-compile</phase> <goals> <goal>test-compile</goal> </goals> </execution> </executions> <configuration> <jvmTarget>1.8</jvmTarget> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <executions> <execution> <id>compile</id> <phase>compile</phase> <goals> <goal>compile</goal> </goals> </execution> <execution> <id>testCompile</id> <phase>test-compile</phase> <goals> <goal>testCompile</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project>

這裡有一點需要注意,在Resource節點中,加上了

<resource>
    <directory>src/main/resources</directory>
    <includes>
        <include>**/*</include>
    </includes>
</resource>

這段配置,通過對Parent POM的觀察,發現Resource中application.xml,application.yml等配置檔案被excludes掉了,導致在打包的時候,配置檔案沒有被打入,部署時會拋找不到配置檔案的錯誤。
上面的配置其實是由IDEA自動生成的,後面我們在對其進行個性化配置。

最終的目錄結構是這樣的:
目錄結構

對於公眾號的驗證,官方已經給了演算法,只要將演算法翻譯成Kotlin即可。

首先新建一個Kotlin Class,名為Signature,其實我把它當做一個工具類。內容如下:

package com.fncity.mp.core

import com.fncity.common.core.utils.HashUtils
import org.slf4j.Logger
import org.slf4j.LoggerFactory

class Signature {
    private val logger: Logger = LoggerFactory.getLogger(Signature::class.java)

    // 將Token放到一個map中,以後需要從資料庫中獲取
    private var tokenMap = mapOf(pair = "fix" to "********************")

    fun checkSignature(signature: String, timestamp: String, nonce: String, type: String): Boolean {
        // 從引數中獲取type,並在Map中得到token
        val token: String = tokenMap[type].toString()
        // 將引數放入一個數組中
        val arr: Array<String> = arrayOf(token, timestamp, nonce)
        // 將陣列進行排序
        arr.sort()
        // 再將排序好的資料依次拼接成一個字串
        val content = StringBuilder()
        for (str: String in arr) {
            content.append(str)
        }
        logger.debug(content.toString())
        // 將字串進行SHA-1加密,得出結果
        val result = HashUtils.sha1(content.toString())
        logger.debug("Result String:" + result)
        logger.debug("Result:" + result.equals(signature.toUpperCase(), false))
        // 將結果與傳進來的簽名進行比對,並返回結果
        return result.equals(signature.toUpperCase(), false)
    }
}

以上程式碼很簡單,就是將簽名演算法翻譯成程式。附SHA-1的演算法:

package com.fncity.common.core.utils

import java.security.MessageDigest

object HashUtils {
    fun sha512(input: String) = hashString("SHA-512", input)

    fun sha256(input: String) = hashString("SHA-256", input)

    fun sha1(input: String) = hashString("SHA-1", input)

    private fun hashString(type: String, input: String): String {
        val HEX_CHARS = "0123456789ABCDEF"
        val bytes = MessageDigest
                .getInstance(type)
                .digest(input.toByteArray())
        val result = StringBuilder(bytes.size * 2)

        bytes.forEach {
            val i = it.toInt()
            result.append(HEX_CHARS[i shr 4 and 0x0f])
            result.append(HEX_CHARS[i and 0x0f])
        }

        return result.toString()
    }
}

此演算法程式碼是Google出來某位老外的,感覺相對比較簡潔。轉自此地址

接下來,當然是寫Controller了,我給他命名為:SignatureController,程式碼如下:

package com.fncity.mp.core

import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.web.bind.annotation.*

@RestController
@ResponseBody
open class SignatureController {
    private var logger: Logger = LoggerFactory.getLogger(SignatureController::class.java)

    @GetMapping("/tokenSign/{type}")
    open fun sign(@PathVariable type: String,
                  @RequestParam signature: String,
                  @RequestParam nonce: String,
                  @RequestParam timestamp: String,
                  @RequestParam echostr: String): String {
        val valid = Signature().checkSignature(signature, timestamp, nonce, type)
        when (valid) {
            true -> return echostr
        }
        logger.error("Signature invalid!")
        return ""
    }
}

很簡單,呼叫一下簽名演算法,如果是true,將echostr返回就可以了,否則就返回個空字串。

驗證部分就到這,簡單,就這麼簡單,不明白的同學請先學習下Kotlin和SpringBoot的基本知識。

後面可能會更新關於JPA的相關內容。