我的小程序之旅三:微信小程序登录流程设计

登录时序图

获取小程序的AppID和AppSecret

一、微信获取登录用户的openId

1、wx.login()

{
    "code": "192038921jkjKHWJKEB21",
    "msg": "login:ok"
}

2、https://api.weixin.qq.com/sns/jscode2session?appid={你的appId}&secret={你的secret}&js_code={前端传过来的code}&grant_type=authorization_code

/**
 * auth.code2Session
 * https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html
 * 请求参数   属性        类型       默认值 必填  说明
 * @param   appId       string                是    小程序 appId
 * @param   secret      string                是    小程序 appSecret
 * @param   jsCode      string                是    登录时获取的 code
 *          grantType   string                是    授权类型,此处只需填写 authorization_code
 * 返回值
 * @return  JSON 数据包
 *           属性         类型       说明
 *          openid      string      用户唯一标识
 *          session_key     string      会话密钥
 *          unionid         string      用户在开放平台的唯一标识符,在满足 UnionID 下发条件的情况下会返回,详见 UnionID 机制说明。
 *          errcode         number      错误码
 *          errmsg      string      错误信息
 *
 *          errcode 的合法值
 *
 *          值           说明                         最低版本
 *          -1          系统繁忙,此时请开发者稍候再试
 *          0           请求成功
 *          40029       code 无效
 *          45011       频率限制,每个用户每分钟100次
 */
JSONObject authCode2Session(String appId, String secret, String jsCode);
import com.alibaba.dc.basic.ability.service.WeChatService;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;

@Service
@Slf4j
public class WeChatServiceImpl implements WeChatService {

    @Resource(name = "restTemplateOfBasicAbility")
    private RestTemplate restTemplate;

    @Override
    public JSONObject authCode2Session(String appId, String secret, String jsCode) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId + "&secret=" + secret + "&js_code=" + jsCode + "&grant_type=authorization_code";
        String str = restTemplate.getForObject(url, String.class);
        log.info("api/wx-mini/getSessionKey:" + str);
        if (StringUtils.isEmpty(str)) {
            return null;
        } else {
            return JSONObject.parseObject(str);
        }
    }
}

二、微信小程序获取用户手机号授权以及解码

encryptedData(小程序端获得)、sessionKey(jscode2session接口获取)

1、小程序代码

<button open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber">手机号码授权</button>
getPhoneNumber: function(e) {     
    console.log(e.detail.errMsg)     
    console.log(e.detail.iv)     
    console.log(e.detail.encryptedData)     
    if (e.detail.errMsg == 'getPhoneNumber:fail user deny'){    
      wx.showModal({    
          title: '提示',    
          showCancel: false,    
          content: '未授权',    
          success: function (res) { }    
      })    
    } else {    
      wx.showModal({    
          title: '提示',    
          showCancel: false,    
          content: '同意授权',    
          success: function (res) { }    
      })    
    }    
  }    

2、后端解码代码

import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.Arrays;
import org.bouncycastle.util.encoders.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.Security;

@Slf4j
public class WeChatUtil {
    private static final String KEY_ALGORITHM = "AES";
    private static final String ALGORITHM_STR = "AES/CBC/PKCS7Padding";
    private static Key key;
    private static Cipher cipher;
    /**
     * 手机号解码
     *
     * @param encryptDataB64
     * @param sessionKeyB64
     * @param ivB64
     * @return
     */
    public static String decryptData(String encryptDataB64, String sessionKeyB64, String ivB64) {
        log.info("encryptDataB64:" + encryptDataB64);
        log.info("sessionKeyB64:" + sessionKeyB64);
        log.info("ivB64:" + ivB64);
        return new String(
                decryptOfDiyIv(
                        Base64.decode(encryptDataB64),
                        Base64.decode(sessionKeyB64),
                        Base64.decode(ivB64)
                )
        );
    }
    private static void init(byte[] keyBytes) {
        // 如果密钥不足16位,那么就补足.  这个if 中的内容很重要
        int base = 16;
        if (keyBytes.length % base != 0) {
            int groups = keyBytes.length / base + 1;
            byte[] temp = new byte[groups * base];
            Arrays.fill(temp, (byte) 0);
            System.arraycopy(keyBytes, 0, temp, 0, keyBytes.length);
            keyBytes = temp;
        }
        // 初始化
        Security.addProvider(new BouncyCastleProvider());
        // 转化成JAVA的密钥格式
        key = new SecretKeySpec(keyBytes, KEY_ALGORITHM);
        try {
            // 初始化cipher
            cipher = Cipher.getInstance(ALGORITHM_STR, "BC");
        } catch (Exception e) {
            log.error("初始化cipher失败", e);
        }
    }

    /**
     * 解密方法
     *
     * @param encryptedData 要解密的字符串
     * @param keyBytes      解密密钥
     * @param ivs           自定义对称解密算法初始向量 iv
     * @return 解密后的字节数组
     */
    private static byte[] decryptOfDiyIv(byte[] encryptedData, byte[] keyBytes, byte[] ivs) {
        byte[] encryptedText = null;
        init(keyBytes);
        try {
            cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(ivs));
            encryptedText = cipher.doFinal(encryptedData);
        } catch (Exception e) {
            log.error("解密失败", e);
        }
        return encryptedText;
    }
}

 

posted @ 2022-01-19 16:04  sum墨  阅读(407)  评论(0编辑  收藏  举报