登入流程時序登入流程時序

具體的登入說明檢視 小程式官方API
項目的結構圖:
springboot項目搭建
使用idea作為開發工具,由gradle建構項目,搭建springboot項目,對這塊兒不熟悉的可以自行去學習,此處不多贅述。下面是核心的配置檔案。application.yml中配置springboot預設的參數,application.properties配置自定義的參數,可以統一配置在一個檔案中,依據個人習慣。
buidle.gradle配置
buildscript {
ext {
springBootVersion = '1.5.10.RELEASE'
}
repositories {
mavenLocal()
maven { url 'http://maven.aliyun.com/nexus/content/groups/public' }
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'org.springframework.boot'
group = 'xin.yangmj'
version = '1.0.1'
sourceCompatibility = 1.8
repositories {
mavenLocal()
maven { url 'http://maven.aliyun.com/nexus/content/groups/public' }
mavenCentral()
}
dependencies {
compile('org.springframework.boot:spring-boot-starter-cache')
compile('org.springframework.boot:spring-boot-starter-data-redis')
compile('org.mybatis.spring.boot:mybatis-spring-boot-starter:1.3.1')
compile('org.springframework.boot:spring-boot-starter-security')
compile('org.springframework.boot:spring-boot-starter-web')
compile('mysql:mysql-connector-java')
compile('org.springframework.security:spring-security-test')
testCompile('org.springframework.boot:spring-boot-starter-test')
compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.7'
}
application.yml
logging:
level:
root: DEBUG
spring:
datasource:
url: jdbc:mysql://localhost/remindme?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
redis:
host: localhost
password:
port: 6379
mybatis:
mapperLocations: classpath:mapper
private static final Long EXPIRES = 86400L;
private RestTemplate wxAuthRestTemplate = new RestTemplate();
@Autowired
private WechatAuthProperties wechatAuthProperties;
@Autowired
private StringRedisTemplate stringRedisTemplate;
public WechatAuthenticationResponse wechatLogin(String code) {
WechatAuthCodeResponse response = getWxSession(code);
String wxOpenId = response.getOpenid();
String wxSessionKey = response.getSessionKey();
Consumer consumer = new Consumer();
consumer.setWechatOpenid(wxOpenId);
loginOrRegisterConsumer(consumer);
Long expires = response.getExpiresIn();
String thirdSession = create3rdSession(wxOpenId, wxSessionKey, expires);
return new WechatAuthenticationResponse(thirdSession);
}
public WechatAuthCodeResponse getWxSession(String code) {
LOGGER.info(code);
String urlString = "?appid={appid}&secret={srcret}&js_code={code}&grant_type={grantType}";
String response = wxAuthRestTemplate.getForObject(
wechatAuthProperties.getSessionHost() + urlString, String.class,
wechatAuthProperties.getAppId(),
wechatAuthProperties.getSecret(),
code,
wechatAuthProperties.getGrantType());
ObjectMapper objectMapper = new ObjectMapper();
ObjectReader reader = objectMapper.readerFor(WechatAuthCodeResponse.class);
WechatAuthCodeResponse res;
try {
res = reader.readValue(response);
} catch (IOException e) {
res = null;
LOGGER.error("反序列化失敗", e);
}
LOGGER.info(response);
if (null == res) {
throw new RuntimeException("調用微信接口失敗");
}
if (res.getErrcode() != null) {
throw new RuntimeException(res.getErrmsg());
}
res.setExpiresIn(res.getExpiresIn() != null ? res.getExpiresIn() : EXPIRES);
return res;
}
public String create3rdSession(String wxOpenId, String wxSessionKey, Long expires) {
String thirdSessionKey = RandomStringUtils.randomAlphanumeric(64);
StringBuffer sb = new StringBuffer();
sb.append(wxSessionKey).append("#").append(wxOpenId);
stringRedisTemplate.opsForValue().set(thirdSessionKey, sb.toString(), expires, TimeUnit.SECONDS);
return thirdSessionKey;
}
private void loginOrRegisterConsumer(Consumer consumer) {
Consumer consumer1 = consumerMapper.findConsumerByWechatOpenid(consumer.getWechatOpenid());
if (null == consumer1) {
consumerMapper.insertConsumer(consumer);
}
}
public void updateConsumerInfo(Consumer consumer) {
Consumer consumerExist = consumerMapper.findConsumerByWechatOpenid(AppContext.getCurrentUserWechatOpenId());
consumerExist.setUpdatedBy(1L);
consumerExist.setUpdatedAt(System.currentTimeMillis());
consumerExist.setGender(consumer.getGender());
consumerExist.setAvatarUrl(consumer.getAvatarUrl());
consumerExist.setWechatOpenid(consumer.getWechatOpenid());
consumerExist.setEmail(consumer.getEmail());
consumerExist.setNickname(consumer.getNickname());
consumerExist.setPhone(consumer.getPhone());
consumerExist.setUsername(consumer.getUsername());
consumerMapper.updateConsumer(consumerExist);
}
}
微信小程式代碼片段
wx.login() 擷取code,然後攜帶code發送請求到自己服務端,擷取登入資訊。然後 wx.getUserInfo() 擷取使用者的基本資訊,例如:昵稱、頭像等,上傳本地伺服器儲存使用者基本資訊。
// 登入
wx.login({
success: function(res) {
if (res.code) {
wx.request({
url: "http://localhost:8080/auth",
data: {
code: res.code
},
method: "POST",
header: {
'content-type': 'application/json',
},
success: function (res) {
console.log(res.data.access_token);
var token = res.data.access_token;
wx.getUserInfo({
success: res => {
// 儲存使用者資訊到服務端
wx.request({
url: "http://localhost:8080/updateConsumerInfo",
data: res.userInfo,
method: "POST",
header: {
'Authorization': 'Bearer ' + token,
'content-type': 'application/json',
},
success: function (res) {
console.log("success");
},
fail: function (error) {
console.log(error);
}
})
}
})
},
fail: function (error) {
console.log(error);
}
})
} else {
console.log("error code " + res.errMsg);
}
}
})
效果展示
重新整理微信小程式緩存,編譯使發送請求
發送登入請求,完成後擷取到 access_token
發送擷取使用者資訊請求
小程式請求本地伺服器登入接口
本地伺服器請求微信伺服器登入接口
小程式請求本地伺服器更新使用者資訊接口
redis儲存會話資訊
mysql資料庫存儲使用者資訊
微信小程式登入JAVA背景
注:本文著作權歸作者,由demo大師代發,拒絕轉載,轉載需要作者授權
微信小程式與Java背景通信
一.寫在前面 最近接觸了小程式的開發,後端選擇Java,因為小程式的代碼運作在騰訊的伺服器上,而我們自己編寫的Java代碼運作在我們自己部署的伺服器上,是以一開始不是很明白小程式如何與背景進行通信的, ...
微信小程式與Java背景的通信
一.寫在前面 最近接觸了小程式的開發,後端選擇Java,因為小程式的代碼運作在騰訊的伺服器上,而我們自己編寫的Java代碼運作在我們自己部署的伺服器上,是以一開始不是很明白小程式如何與背景進行通信的, ...
微信小程式:java背景擷取openId
一.功能描述 openId是某個微信賬戶對應某個小程式或者公衆号的唯一辨別,但openId必須經過背景解密才能擷取(之前實作過前台解密,可是由于微信小程式的種種限制,前台解密無法在小程式釋出後使用) ...
微信小程式與java背景互動
java背景使用的ssm架構,小程式連接配接的本地接口.跟正常的web通路沒什麼差別,也是背景擷取url,傳回json資料:隻是小程式前台請求的url要帶上http://localhost:80801. ...
【原創】微信小程式支付java背景案例(公衆号支付同适用)(簽名錯誤問題)
前言 1.微信小程式支付官方接口文檔:[點選檢視微信開放平台api開發文檔]2.遇到的坑:預支付統一下單簽名結果傳回[簽名錯誤]失敗,建議用官方[簽名驗證工具]檢查簽名是否存在問題.3.遇到的坑:簽名 ...
基于Shiro,JWT實作微信小程式登入完整例子
小程式官方流程圖如下,官方位址 : https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/login.html ...
微信小程式登入,擷取code,擷取openid,擷取session_key
微信小程式登入 wx.login(Object object) 調用接口擷取登入憑證(code).通過憑證進而換取使用者登入态資訊,包括使用者的唯一辨別(openid)及本次登入的會話密鑰(session ...
Taro -- 微信小程式登入
Taro微信小程式登入 1.調用Taro.login()擷取登入憑證code: 2.調用Taro.request()将code傳到伺服器: 3.伺服器端調用微信登入校驗接口(appid+appsecr ...
微信小程式需要https背景的創業機會思考
最近比較關注微信小程式,而且微信小程式的背景必須強制要求https, https相對http成本要高很多了. 這裡我感覺有2個商機 (1)提供https 中轉伺服器 ,按流量來收費 (2) 微信小程式 ...
随機推薦
Write Your software base on plugin(C/C++ ABI)
一個軟體,如果把所有的功能寫進C++源碼,維護,擴充,編譯都特别麻煩. 共享庫字尾名.Linux -> .so Windows -> .dll 關于動态符号顯示問題,具體可以看系統的AP ...
了解CSS盒子模型
概述 網頁設計中常聽的屬性名:内容(content).填充(padding).邊框(border).邊界(margin),CSS盒子模型都具備這些屬性,也主要是這些屬性. 這些屬性我們可以把它轉移到我 ...
iphone6閃存檢測
iPhone6自從釋出以後一直又不少的诟病和非議,比如一機難求,容易掰彎,程式崩潰等, 甚至傳出了蘋果将要召回這些問題裝置,最近有人終于查出了iPhone6安裝大量程式後崩潰的原因,原因就是大容量的i ...
wxPython制作跑monkey工具(python3)
一. wxPython制作跑monkey工具python檔案源代碼内容Run Monkey.py如下: #!/usr/bin/env python import wx import os import ...
EtherCAT主站對PHY有要求?
/********************************************************************** * EtherCAT主站對PHY有要求? * 說明: * ...
Java IO(三)——位元組流
一.流類 Java的流式輸入/輸出是建立在四個抽象類的基礎上的:InputStream.OutputStream.Reader.Writer.它們用來建立具體的流式子類.盡管程式通過具體子類執行輸入/ ...
Codeforces 1154E Two Teams
題目連結:http://codeforces.com/problemset/problem/1154/E 題目大意: 有n個隊員,編号1~n,每個人的能力各自對應1~n中的一個數,每個人的能力都不相同 ...
ARM Cortex-A9 (tiny 4412)
要求 移植linux增加系統調用并燒寫至開發闆 詳細步驟 一.搭建linux編譯環境 1.GCC 編譯器的安裝: tar xzvf arm-linux-gcc-4.5.1-v6-vfp-2012030 ...