微信小程序获取openid、unionid以及手机号码

版权声明:转载原创文章请以超链接形式请注明原文章出处,尊重作者,尊重原创!


恰饭广告




注意:获取openid和unionid以及手机号码的请求必须写在后台代码,微信官方不允许直接请求

新建login页面(login.wxml)

<!--pages/login/login.wxml-->
<button bindtap="getOpen">获取openid</button>
<button bindtap="getUnion">获取unionid</button>

login.js

  getUnion:function(e) {
    wx.login({
      success: function (r) {
        var code=r.code;
        if(code){
          wx.getUserInfo({
            success:function(res){
              wx.request({
                url: 'http://localhost:8080/getUnionId.do',
                method: 'POST',
                header: {
                  'content-type': 'application/x-www-form-urlencoded',
                },
                data: { encryptedData: res.encryptedData, iv: res.iv, code: code },
                success:function(re){
                  console.log(re.data);
                },
                fail:function(){
                  console.log("错误");
                }
              });
            },
            fail: function(){
              wx.showModal({
                title: '警告',
                content: '尚未进行授权,请点击确定跳转到授权页面进行授权。',
                success: function (res) {
                  if (res.confirm) {
                    wx.navigateTo({
                      url: 'author',
                    })
                  }
                  else {
                    wx.showToast({
                      title: '授权失败',
                      icon: 'none',
                      duration: 2000
                    })
                  }
                }
              })
            }
          });
        }
      },
      fail: function () {
        console.log("错误");
      }
    })
  },

  getOpen:function(e){
    wx.login({
      success: function (res) {
        wx.request({
          url: 'http://localhost:8080/getOpenId.do',
          method: 'POST',
          data: {
            code: res.code
          },
          header:{
            'content-type': 'application/x-www-form-urlencoded',
          },
          success:function(res){
            console.log(res.data);
          },
          fail: function () {
           console.log("失败");
          }
        })
      },
      fail: function () {
        console.log("错误");
      }
    })
  },

注意:获取openid不用用户授权,但unionid不行,所以必须处理授权弹窗页面

获取用户授权页面 

author.wxml

<!--pages/login/author.wxml-->
<button open-type="getUserInfo" bindgetuserinfo="bindGetUserInfo">授权</button>

author.js

  bindGetUserInfo: function (e) {
    var that = this;
    var userinfo = e.detail.userInfo;
    if (userinfo==null){
      wx.showToast({
        title: '授权失败',
        icon: 'none',
        duration: 2000
      })
    }
    else{
      //返回刚才的页面
      wx.navigateBack({
        delta: 1
      })
    }
  },

java后台(springboot)

pom.xml jar包引入

        <dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcprov-jdk15on</artifactId>
            <version>1.55</version>
        </dependency>

三大帮助类(AesUtil.java,JacksonUtil.java,WeChatUtil.java )

AesUtil.java 

import org.apache.tomcat.util.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;

public class AesUtil {
    static {
        //BouncyCastle是一个开源的加解密解决方案,主页在http://www.bouncycastle.org/
        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 {

        //被加密的数据
        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;
    }

}

JacksonUtil.java 

import java.util.List;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonUtil {

    private static ObjectMapper mapper = new ObjectMapper();

    static {
        mapper.setSerializationInclusion(Include.NON_EMPTY);
    }

    //json转bean
    public static <T> T deserialize(String json,Class<T> cls){
        T t = null;
        try{
            t=mapper.readValue(json, cls);
        }catch (Exception ex){
            return null;
        }
        return t;
    }

    public static Object getFileValue(String json,String filedName) {
        try{
            JsonNode rootNode = mapper.readTree(json);
            return rootNode.get(filedName);
        }
        catch (Exception ex){
            return "";
        }
    }

    //json数组转bean
    public static <T> List<T> decode(String json,Class<T> cls) {
        List<T> list;
        try{
            JavaType javaType = mapper.getTypeFactory().constructParametricType(List.class, cls);
            list=(List<T>)mapper.readValue(json, javaType);
        }
        catch (Exception ex){
            return null;
        }
        return list;
    }

    //bean转json
    public static String beanToJson(Object obj) {
        String json="";
        try {
            json=mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return json;
    }

    //list转json
    public static String listToJson(List list){
        String json="";
        try {
            json=mapper.writeValueAsString(list);
        } catch (JsonProcessingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return json;
    }
}

WeChatUtil.java  

import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;

public class WeChatUtil {
    public static String httpRequest(String requestUrl,String requestMethod,String output){
        try{
            URL url = new URL(requestUrl);
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            if(null != output){
                OutputStream outputStream = connection.getOutputStream();
                outputStream.write(output.getBytes("utf-8"));
                outputStream.close();
            }
            // 从输入流读取返回内容
            InputStream inputStream = connection.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null){
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            inputStream = null;
            connection.disconnect();
            return buffer.toString();
        }catch(Exception e){
            e.printStackTrace();
        }
        return "";
    }
}

controller接口

import basic.JacksonUtil;
import basic.WeChatUtil;
import basic.AesUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class WeChat {

    // 微信小程序ID
    String appid = xxxxx";
    // 微信小程序秘钥
    String secret = "xxxxxxx";

    @RequestMapping("/getOpenId.do")
    public String getOpenId(String code) throws JsonProcessingException {
        try{
            // 根据小程序穿过来的code想这个url发送请求
            String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";
            // 发送请求,返回Json字符串
            String str = WeChatUtil.httpRequest(url, "POST", null);
            return str;
        }
        catch (Exception ex){
            return null;
        }
    }

    @RequestMapping("/getUnionId.do")
    public String getUnionId(String encryptedData, String iv, String code)  {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";
        try{
            String str = WeChatUtil.httpRequest(url, "POST", null);
            String session_key=JacksonUtil.getFileValue(str,"session_key").toString();
            String result = AesUtil.decrypt(encryptedData, session_key, iv, "UTF-8");
            return result;
        }
        catch (Exception ex){
            return null;
        }
    }
}

注意:获取unionid以及手机号码的api是非个人的收费api,必须去微信开放平台申请并绑定微信小程序

原文链接:https://www.idaobin.com/archives/2294.html

让我恰个饭吧.ヘ( ̄ω ̄ヘ)

支付宝 ——————- 微信
图片加载中图片加载中



恰饭广告

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

− 7 = 1