SpringBoot�村��寰�淇″�绋�搴��诲�

璇ラ」��婧����板��锛�https://github.com/ggb2312/JavaNotes/tree/master/springboot-integration-examples 锛��朵腑����SpringBoot���朵�甯哥�ㄦ�������村��锛���濂�婧���浠ュ��绗�璁般���轰����扮�� SpringBoot2.1+锛�娆㈣���浣� Star锛�

1. 寮�������澶�

1.1 ��缃��ヨ��

  • java�虹�
  • SpringBoot绠����虹��ヨ��

1.2 ��澧�����

  • 寮���宸ュ�凤�IDEA
  • �虹���澧�锛�Maven+JDK8
  • ���ㄦ����锛�SpringBoot��lombok��mybatisplus��寰�淇″�绋�搴�
  • SpringBoot����锛�2.1.4

1.3 娑����ヨ����

  • 寰�淇″�绋�搴��诲�娴�绋�

2. 寰�淇″�绋�搴��诲�娴�绋�

寰�淇″�绋�搴��诲�娴�绋�娑����颁�涓�瑙��诧�灏�绋�搴���寮��������″�ㄣ��寰�淇℃���″��

涓���浜や�姝ラ�ゅ�涓�锛�

绗�涓�姝ワ�灏�绋�搴���杩�wx.login()�峰��code��
绗�浜�姝ワ�灏�绋�搴���杩�wx.request()����code�板��������″�ㄣ��
绗�涓�姝ワ�寮��������″���ユ�跺�绋�搴�������code锛�骞舵�哄甫appid��appsecret锛�杩�涓や釜��瑕��板井淇″�绋�搴����版�ョ��锛���code������寰�淇℃���″����
绗���姝ワ�寰�淇℃���″���ユ�跺��������″�ㄥ������appid��appsecret��code杩�琛��¢�����¢����杩�����寮��������″������session_key��openid��
绗�浜�姝ワ�寮��������″����宸辩����涓�涓�skey锛���瀹�涔��诲��舵��锛�涓�openid��session_key杩�琛��宠��锛�骞跺���版�版��搴�涓�锛�mysql��redis绛�锛���
绗���姝ワ�寮��������″��杩�������skey锛���瀹�涔��诲��舵��锛��板�绋�搴���
绗�涓�姝ワ�灏�绋�搴�瀛���skey锛���瀹�涔��诲��舵��锛��版���般��
绗���姝ワ�灏�绋�搴���杩�wx.request()��璧蜂��¤�锋���寮��������″��锛����舵�哄甫skey锛���瀹�涔��诲��舵��锛���
绗�涔�姝ワ�寮��������″���ユ��灏�绋�搴�������skey锛���瀹�涔��诲��舵��锛�锛��ヨ��skey�ㄦ�版��搴�涓�������瀵瑰���openid��session_key��
绗���姝ワ�寮��������″��杩���涓��℃�版����灏�绋�搴���

�诲�娴�绋��跺�濡�涓�锛�

SpringBoot�村��寰�淇″�绋�搴��诲�_第1张图片
�诲�娴�绋��跺�

����瀹��颁���涓�涓�姝ラ�わ���涓哄井淇″�绋�搴��诲����稿�灏辨����涓�涓�姝ラ�ゃ��

绗�涓�姝ワ�灏�绋�搴���杩�wx.login()�峰��code��
绗�浜�姝ワ�灏�绋�搴���杩�wx.request()����code�板��������″�ㄣ��
绗�涓�姝ワ�寮��������″���ユ�跺�绋�搴�������code锛�骞舵�哄甫appid��appsecret锛�杩�涓や釜��瑕��板井淇″�绋�搴����版�ョ��锛���code������寰�淇℃���″�ㄣ��
绗���姝ワ�寰�淇℃���″���ユ�跺��������″�ㄥ������appid��appsecret��code杩�琛��¢�����¢����杩�����寮��������″������session_key��openid��
绗�浜�姝ワ�寮��������″����宸辩����涓�涓�skey锛���瀹�涔��诲��舵��锛�涓�openid��session_key杩�琛��宠��锛�骞跺���版�版��搴�涓�锛�mysql��redis绛�锛���
绗���姝ワ�寮��������″��杩�������skey锛���瀹�涔��诲��舵��锛��板�绋�搴���
绗�涓�姝ワ�灏�绋�搴�瀛���skey锛���瀹�涔��诲��舵��锛��版���般��

SpringBoot�村��寰�淇″�绋�搴��诲�_第2张图片
����浠�缁���娴�绋�

3. 寮��������″��

椤圭��缁���锛�

SpringBoot�村��寰�淇″�绋�搴��诲�_第3张图片
椤圭��缁���

3.1 ��濮���缃�

锛�1锛�pom.xml��缃�


        
            org.apache.httpcomponents
            httpclient
            4.5.2
        

        
            org.bouncycastle
            bcprov-jdk16
            1.46
        

        
        
        
            org.apache.shiro
            shiro-core
            1.4.0
            
                
                    slf4j-api
                    org.slf4j
                
            
        

        
        
            com.alibaba
            fastjson
            1.2.47
        

        
        
            org.projectlombok
            lombok
            true
        
        
        
            com.baomidou
            mybatis-plus-boot-starter
            3.1.1
        
        
        
            mysql
            mysql-connector-java
            5.1.47
        

锛�2锛�application.properties

spring.application.name = lastwhisper-wxlogin
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/wxlogin?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true&useSSL=false
spring.datasource.username=root
spring.datasource.password=root

3.2 灏�绋�搴��ㄦ�疯〃

��寤轰�涓��ㄦ�疯〃瀛��ㄧ�ㄦ�风��openid绛��版����

CREATE TABLE `user`  (
  `open_id` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT 'open_id',
  `skey` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT 'skey',
  `create_time` timestamp(0) NULL DEFAULT CURRENT_TIMESTAMP COMMENT '��寤烘�堕��',
  `last_visit_time` timestamp(0) NULL DEFAULT CURRENT_TIMESTAMP COMMENT '�����诲��堕��',
  `session_key` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT 'session_key',
  `city` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '甯�',
  `province` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '��',
  `country` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '��',
  `avatar_url` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '澶村��',
  `gender` tinyint(11) NULL DEFAULT NULL COMMENT '�у��',
  `nick_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '缃���',
  PRIMARY KEY (`open_id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '寰�淇$�ㄦ�蜂俊��' ROW_FORMAT = Dynamic;

3.3 pojo

package cn.lastwhisper.springbootwx.pojo;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;

import java.util.Date;

/**
 * @author lastwhisper
 * @desc
 * @email [email protected]
 */
@Data
@TableName("user")
public class User {
    private static final long serialVersionUID = 1L;
    /**
     * open_id
     */
    @TableId(value = "open_id",type = IdType.INPUT)
    private String openId;
    /**
     * skey
     */
    private String skey;
    /**
     * ��寤烘�堕��
     */
    @TableField("create_time")
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date createTime;
    /**
     * �����诲��堕��
     */
    @TableField("last_visit_time")
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date lastVisitTime;
    /**
     * session_key
     */
    @TableField("session_key")
    private String sessionKey;
    /**
     * 甯�
     */
    @TableField("city")
    private String city;
    /**
     * ��
     */
    @TableField("province")
    private String province;
    /**
     * ��
     */
    @TableField("country")
    private String country;
    /**
     * 澶村��
     */
    @TableField("avatar_url")
    private String avatarUrl;
    /**
     * �у��
     */
    @TableField("gender")
    private Integer gender;
    /**
     * 缃���
     */
    @TableField("nick_name")
    private String nickName;

}

3.4 common

灏�瑁�涓�浜�宸ュ�风被

锛�1锛�GlobalResult

package cn.lastwhisper.springbootwx.common;

/**
 * @Description: ��瀹�涔���搴��版��缁���
 *              杩�涓�绫绘����渚�缁��ㄦ�凤�ios锛�瀹���锛�寰�淇″�����ㄧ��
 *              �ㄦ�锋�ュ��姝ょ被�版������瑕�浣跨�ㄦ��绫荤���规�杞��㈡��瀵逛����版��绫诲���煎�锛�绫伙�����list锛�
 *              �朵���琛�澶���
 *              200锛�琛ㄧず����
 *              500锛�琛ㄧず��璇�锛���璇�淇℃����msg瀛�娈典腑
 *              501锛�bean楠�璇���璇�锛�涓�绠″�灏�涓���璇��戒互map褰㈠�杩���
 *              502锛������ㄦ�����扮�ㄦ��token�洪��
 *              555锛�寮�甯告���轰俊��
 */
public class GlobalResult {

    // ��搴�涓��$�舵��
    private Integer status;

    // ��搴�娑���
    private String msg;

    // ��搴�涓����版��
    private Object data;
    
    private String ok;  // 涓�浣跨��

    public static GlobalResult build(Integer status, String msg, Object data) {
        return new GlobalResult(status, msg, data);
    }

    public static GlobalResult ok(Object data) {
        return new GlobalResult(data);
    }

    public static GlobalResult ok() {
        return new GlobalResult(null);
    }
    
    public static GlobalResult errorMsg(String msg) {
        return new GlobalResult(500, msg, null);
    }
    
    public static GlobalResult errorMap(Object data) {
        return new GlobalResult(501, "error", data);
    }
    
    public static GlobalResult errorTokenMsg(String msg) {
        return new GlobalResult(502, msg, null);
    }
    
    public static GlobalResult errorException(String msg) {
        return new GlobalResult(555, msg, null);
    }

    public GlobalResult() {

    }

    public GlobalResult(Integer status, String msg, Object data) {
        this.status = status;
        this.msg = msg;
        this.data = data;
    }

    public GlobalResult(Object data) {
        this.status = 200;
        this.msg = "OK";
        this.data = data;
    }

    public Boolean isOK() {
        return this.status == 200;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    public String getOk() {
        return ok;
    }

    public void setOk(String ok) {
        this.ok = ok;
    }

}

锛�2锛�HttpClientUtil

package cn.lastwhisper.springbootwx.common;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpClientUtil {

    public static String doGet(String url, Map param) {

        // ��寤�Httpclient瀵硅薄
        CloseableHttpClient httpclient = HttpClients.createDefault();

        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // ��寤�uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();

            // ��寤�http GET璇锋�
            HttpGet httpGet = new HttpGet(uri);

            // �ц�璇锋�
            response = httpclient.execute(httpGet);
            // �ゆ��杩����舵������涓�200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    public static String doGet(String url) {
        return doGet(url, null);
    }

    public static String doPost(String url, Map param) {
        // ��寤�Httpclient瀵硅薄
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // ��寤�Http Post璇锋�
            HttpPost httpPost = new HttpPost(url);
            // ��寤哄���板��琛�
            if (param != null) {
                List paramList = new ArrayList<>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }
                // 妯℃��琛ㄥ��
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
                httpPost.setEntity(entity);
            }
            // �ц�http璇锋�
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return resultString;
    }

    public static String doPost(String url) {
        return doPost(url, null);
    }

    public static String doPostJson(String url, String json) {
        // ��寤�Httpclient瀵硅薄
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // ��寤�Http Post璇锋�
            HttpPost httpPost = new HttpPost(url);
            // ��寤鸿�锋���瀹�
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // �ц�http璇锋�
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return resultString;
    }
}

锛�3锛�WechatUtil

package cn.lastwhisper.springbootwx.common;/**
 * Create by eval on 2019/3/20
 */

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.shiro.codec.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName WechatUtil
 * @Description TODO
 * @Author eval
 * @Date 9:44 2019/3/20
 * @Version 1.0
 */
public class WechatUtil {
    public static JSONObject getSessionKeyOrOpenId(String code) {
        String requestUrl = "https://api.weixin.qq.com/sns/jscode2session";
        Map requestUrlParam = new HashMap<>();
        // https://mp.weixin.qq.com/wxopen/devprofile?action=get_profile&token=164113089&lang=zh_CN
        //灏�绋�搴�appId
        requestUrlParam.put("appid", "灏�绋�搴�appId");
        //灏�绋�搴�secret
        requestUrlParam.put("secret", "灏�绋�搴�secret");
        //灏�绋�搴�绔�杩�����code
        requestUrlParam.put("js_code", code);
        //榛�璁ゅ����
        requestUrlParam.put("grant_type", "authorization_code");
        //����post璇锋�璇诲��璋��ㄥ井淇℃�ュ�h�峰��openid�ㄦ�峰��涓���璇�
        JSONObject jsonObject = JSON.parseObject(HttpClientUtil.doPost(requestUrl, requestUrlParam));
        return jsonObject;
    }

    public static JSONObject getUserInfo(String encryptedData, String sessionKey, String iv) {
        // 琚���瀵����版��
        byte[] dataByte = Base64.decode(encryptedData);
        // ��瀵�绉���
        byte[] keyByte = Base64.decode(sessionKey);
        // ��绉婚��
        byte[] ivByte = Base64.decode(iv);
        try {
            // 濡���瀵��ヤ�瓒�16浣�锛��d�灏辫ˉ瓒�.  杩�涓�if 涓�����瀹瑰���瑕�
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            // ��濮���
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// ��濮���
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, "UTF-8");
                return JSON.parseObject(result);
            }
        } catch (Exception e) {
        }
        return null;
    }
}

3.5 mapper

package cn.lastwhisper.springbootwx.mapper;

import cn.lastwhisper.springbootwx.pojo.User;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;

/**
 * @desc
 * 
 * @author lastwhisper
 * @email [email protected]
 */
public interface UserMapper extends BaseMapper {
}

��缃�SpringBoot����mapper

package cn.lastwhisper.springbootwx;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@MapperScan("cn.lastwhisper.springbootwx.mapper") //璁剧疆mapper�ュ�g��������
@SpringBootApplication
public class SpringbootwxApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootwxApplication.class, args);
    }

}

3.6 controller

�ㄤ��ユ�剁�ㄦ�疯�锋�锛��¢��绛惧��锛�骞剁����skey锛�瀛���skey��openid绛��版��

package cn.lastwhisper.springbootwx.controller;

import cn.lastwhisper.springbootwx.common.GlobalResult;
import cn.lastwhisper.springbootwx.mapper.UserMapper;
import cn.lastwhisper.springbootwx.pojo.User;
import cn.lastwhisper.springbootwx.common.WechatUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.UUID;

/**
 * @author lastwhisper
 * @desc
 * @email [email protected]
 */
@Controller
public class UserController {

    @Autowired
    private UserMapper userMapper;

    /**
     * 寰�淇$�ㄦ�风�诲�璇���
     */
    @PostMapping("wx/login")
    @ResponseBody
    public GlobalResult user_login(@RequestParam(value = "code", required = false) String code,
                                   @RequestParam(value = "rawData", required = false) String rawData,
                                   @RequestParam(value = "signature", required = false) String signature,
                                   @RequestParam(value = "encrypteData", required = false) String encrypteData,
                                   @RequestParam(value = "iv", required = false) String iv) {
        // �ㄦ�烽������淇℃��锛�rawData
        // 绛惧��锛�signature
        JSONObject rawDataJson = JSON.parseObject(rawData);
        // 1.�ユ�跺�绋�搴�������code
        // 2.寮��������″�� �诲���璇��¢���ュ�� appi + appsecret + code
        JSONObject SessionKeyOpenId = WechatUtil.getSessionKeyOrOpenId(code);
        // 3.�ユ�跺井淇℃�ュ�f���� �峰��杩���������
        String openid = SessionKeyOpenId.getString("openid");
        String sessionKey = SessionKeyOpenId.getString("session_key");

        // 4.�¢��绛惧�� 灏�绋�搴�������绛惧��signature涓����″�ㄧ��������绛惧��signature2 = sha1(rawData + sessionKey)
        String signature2 = DigestUtils.sha1Hex(rawData + sessionKey);
        if (!signature.equals(signature2)) {
            return GlobalResult.build(500, "绛惧���¢��澶辫触", null);
        }
        // 5.�规��杩�����User瀹�浣�绫伙��ゆ���ㄦ�锋�������扮�ㄦ�凤�����璇�锛�灏��ㄦ�蜂俊��瀛��版�版��搴�锛�涓�����璇�锛��存�版���扮�诲��堕��
        User user = this.userMapper.selectById(openid);
        // uuid������涓�key锛��ㄤ�缁存�ゅ井淇″�绋�搴��ㄦ�蜂����$����浼�璇�
        String skey = UUID.randomUUID().toString();
        if (user == null) {
            // �ㄦ�蜂俊���ュ�
            String nickName = rawDataJson.getString("nickName");
            String avatarUrl = rawDataJson.getString("avatarUrl");
            String gender = rawDataJson.getString("gender");
            String city = rawDataJson.getString("city");
            String country = rawDataJson.getString("country");
            String province = rawDataJson.getString("province");

            user = new User();
            user.setOpenId(openid);
            user.setSkey(skey);
            user.setCreateTime(new Date());
            user.setLastVisitTime(new Date());
            user.setSessionKey(sessionKey);
            user.setCity(city);
            user.setProvince(province);
            user.setCountry(country);
            user.setAvatarUrl(avatarUrl);
            user.setGender(Integer.parseInt(gender));
            user.setNickName(nickName);

            this.userMapper.insert(user);
        } else {
            // 宸插����锛��存�扮�ㄦ�风�诲��堕��
            user.setLastVisitTime(new Date());
            // ���拌�剧疆浼�璇�skey
            user.setSkey(skey);
            this.userMapper.updateById(user);
        }
        //encrypteData姣�rowData澶�浜�appid��openid
        //JSONObject userInfo = WechatUtil.getUserInfo(encrypteData, sessionKey, iv);
        //6. ���扮��skey杩���缁�灏�绋�搴�
        GlobalResult result = GlobalResult.build(200, null, skey);
        return result;
    }
}

4. 寰�淇″�绋�搴�

椤圭��缁���锛�

SpringBoot�村��寰�淇″�绋�搴��诲�_第4张图片
椤圭��缁���

4.1 ��濮���缃�

SpringBoot�村��寰�淇″�绋�搴��诲�_第5张图片
��濮���缃�

4.2 me.wxml


    
  
  
  
      
      
  

4.3 me.wxss

��

4.4 me.json

{
  
}

4.5 me.js

// pages/me/me.js
Page({

  /**
   * 椤甸�㈢����濮��版��
   */
  data: {
    hasUserInfo: false,
    userInfo: null
  },

  onLoad: function() {
    // 椤甸�㈠��杞芥�朵娇�ㄧ�ㄦ�锋�����昏�锛�寮瑰�虹‘璁ょ��妗�  
    this.userAuthorized()
  },
  
  userAuthorized() {
    wx.getSetting({
      success: data => {
        if (data.authSetting['scope.userInfo']) {
          wx.getUserInfo({
            success: data => {
              this.setData({
                hasUserInfo: true,
                userInfo: data.userInfo
              })
            }
          })
        } else {
          this.setData({
            hasUserInfo: false
          })
        }
      }
    })
  },

  onGetUserInfo(e) {
    const userInfo = e.detail.userInfo
    if (userInfo) {
      // 1. 灏�绋�搴���杩�wx.login()�峰��code
      wx.login({
        success: function(login_res) {
          //�峰���ㄦ�蜂俊��
          wx.getUserInfo({
            success: function(info_res) {
              // 2. 灏�绋�搴���杩�wx.request()����code�板��������″��
              wx.request({
                url: 'http://localhost:8080/wx/login',
                method: 'POST',
                header: {
                  'content-type': 'application/x-www-form-urlencoded'
                },
                data: {
                  code: login_res.code, //涓存�剁�诲���璇�
                  rawData: info_res.rawData, //�ㄦ�烽������淇℃��
                  signature: info_res.signature, //绛惧��
                  encrypteData: info_res.encryptedData, //�ㄦ�锋����淇℃��
                  iv: info_res.iv //瑙e��绠�娉�������
                },
                success: function(res) {
                  if (res.data.status == 200) {
                    // 7.灏�绋�搴�瀛���skey锛���瀹�涔��诲��舵��锛��版����
                    wx.setStorageSync('userInfo', userInfo);
                    wx.setStorageSync('skey', res.data.data);
                  } else{
                    console.log('���″�ㄥ�甯�');
                  }
                },
                fail: function(error) {
                  //璋��ㄦ���$���诲��ュ�eけ璐�
                  console.log(error);
                }
              })
            }
          })
        }
      })
      this.setData({
        hasUserInfo: true,
        userInfo: userInfo
      })
    }
  }

})

4.6 app.json

璁剧疆app.json��pages

{
  "pages":[
    "pages/me/me"
  ],
  "window":{
    "backgroundTextStyle":"light",
    "navigationBarBackgroundColor": "#fff",
    "navigationBarTitleText": "WeChat",
    "navigationBarTextStyle":"black"
  },
  "debug":true
}

5. 娴�璇�

���ㄥ��������″��锛�����SpringBoot��main�规���

��寮�寰�淇″�绋�搴�寮�����宸ュ��

SpringBoot�村��寰�淇″�绋�搴��诲�_第6张图片
娓�绌虹�瀛�

�瑰�绘�����诲�锛�骞跺��璁搞��

SpringBoot�村��寰�淇″�绋�搴��诲�_第7张图片
�����诲�

�诲�����

SpringBoot�村��寰�淇″�绋�搴��诲�_第8张图片
�诲�����

�ョ���版��搴�锛�openid��skey浠ュ���ㄦ�蜂俊��绛�瀛��ヤ��版��搴���

�ㄦ�蜂俊���ュ�

���跺井淇″�绋�搴�灏�skey绛�瀛��ㄥ�版���帮�姣�娆″��璧疯�锋��堕�藉��浠ユ�哄甫涓���

SpringBoot�村��寰�淇″�绋�搴��诲�_第9张图片
skey瀛��ㄦ����

你可能感兴趣的:(SpringBoot�村��寰�淇″�绋�搴��诲�)