微信小程序登录(基于java后台)

//调用微信的登录接口
wx.login({
    success:function(r){
    //获取到微信的登录凭证code
    var code = r.code
    if(code){
        //调用微信的用户信息接口
        wx.getUserInfo({
            success:function(res){
                    console.log({encryptedData: res.encryptedData, iv: res.iv, code: code}),
            //请求自己的服务器,解密用户信息,获取unionId
            wx.request({
                url:'服务器登录接口',
                method:'post',//get,del
                herder:{
                    'content-type': 'application/x-www-form-urlencoded'
                },
                //请求的参数data
                data: {encryptedData: res.encryptedData, iv: res.iv, code: code},
                success:function(data){
                //判断是否解密成功
                    if(data.data.status==1){
                        var userInfo_=data.data.userInfo;
                        console.log(userInfo_)
                    }esle{
                        conlose.log('解密失败')
                    }
                },
                fail:function(){
                    conlose.log('系统错误')
                }
            })

            },
            fail:function(){
                console.log("获取用户信息失败")
            }
})  
    }else{
                console.log("获取用户登录状态失败"+r.errmsg)
    }
    },
        fail:function(){
        callback(false)
        }
})

java服务端

    //需要一个工具类来进行加解密
    package com.login.util;

import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.spec.InvalidParameterSpecException;

/**
 * Created by yfs on 2017/2/6.
 * <p>
 * AES-128-CBC 加密方式 注: AES-128-CBC可以自己定义“密钥”和“偏移量“。 AES-128是jdk自动生成的“密钥”。
 */
public class AesCbcUtil {

    static {
        // BouncyCastle是一个开源的加解密解决方案,主页在http://www.bouncycastle.org/
        // 需要在pom定义版本
        /*
         * <dependency> <groupId>org.bouncycastle</groupId>
         * <artifactId>bcprov-jdk16</artifactId> <version>1.46</version>
         * </dependency>
         * 
         */
        Security.addProvider(new BouncyCastleProvider());
    }

    /**
     * AES解密
     *
     * @param data
     *            //密文,被加密的数据
     * @param key
     *            //秘钥
     * @param iv
     *            //偏移量
     * @param encodingFormat
     *            //解密后的结果需要进行的编码
     * @return
     * @throws Exception
     */
    public static String decrypt(String data, String key, String iv, String encodingFormat) throws Exception {
        // initialize();

        // 被加密的数据
        byte[] dataByte = Base64.decodeBase64(data);
        // 加密秘钥
        byte[] keyByte = Base64.decodeBase64(key);
        // 偏移量
        byte[] ivByte = Base64.decodeBase64(iv);

        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");

            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, encodingFormat);
                return result;
            }
            return null;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidParameterSpecException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return null;
    }

}
//登录接口实现
package cn.guddqs.wxmini.controller;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.login.util.AesCbcUtil;

import cn.guddqs.wxmini.entity.User;
import net.sf.json.JSONObject;

@Controller
public class LoginController {
    public static String GETlogin(String u) {
        String result = "";
        BufferedReader in = null;

        try {

            URL realUrl = new URL(u);
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.connect();

            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }

            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求失败");
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();

                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }

        return result;

    }

    @ResponseBody
    @RequestMapping("/login")
    public Map<String, String> addr_getList(String encryptedData, String iv, String code) {

        Map map = new HashMap<>();

        if (code == null || code.length() == 0) {

            map.put("status", 0);
            map.put("msg", "code是空的");
            // System.out.println("code" + code);
            return map;
        }

        System.out.println(code);
        String wxappid = "**********************";
        String wxSecret = "***************************";
        String grant_type = "authorization_code";

        String u = "https://api.weixin.qq.com/sns/jscode2session?" + "appid=" + wxappid + "&secret=" + wxSecret
                + "&js_code=" + code + "&grant_type=" + grant_type;
        ;
        String s = LoginController.GETlogin(u);
            //将这个拼接出来的url打印出来看一下
        System.out.println(u);

        JSONObject json = JSONObject.fromObject(s);

        System.out.println("这里是openid和session_key" + json);
        String session_key = (String) json.get("session_key");
        String openid = (String) json.get("openid");

        try {
            System.out.println("进入解密成功程序");
            String result = AesCbcUtil.decrypt(encryptedData, session_key, iv, "utf-8");
            //JSONObject jsonObject = JSONObject.fromObject(result);
            System.out.println(result.length()+"wdsaxsadsadsadsa");
             if (null != result && result.length() > 0) {
                map.put("status", 1);
                map.put("msg", "解密成功");
                HashMap userinfo = new HashMap<>();
                userinfo.put("openid", json.get("openid"));
                userinfo.put("session_key", json.get("session_key"));
                map.put("userInfo", userinfo);
            }

        } catch (Exception e) {
            System.out.println("解密失败");
        }


        return map;

    }

}

/**
*   基于java ssm框架,需要的jar包可以在网上找到
*/

原文:https://my.oschina.net/u/3235888/blog/832895#comment-list

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值