栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

小程序开发入门3-微信小程序登录流程设计

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

小程序开发入门3-微信小程序登录流程设计

登录时序图

获取小程序的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
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、小程序代码

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;
    
    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);
        }
    }

    
    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;
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/946758.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号