zoukankan      html  css  js  c++  java
  • SpringBoot 获取微信小程序openid

    最近做一个项目用到小程序,为了简化用户啊登录,通过获取小程序用户的openid来唯一标示用户。

    1、官方教程

    2、具体步骤

    3、具体实现

    4、可能出现的错误

    5、代码下载

    1、官方教程

    先来看看官方怎么说的:官方链接

    官方的意思是用户打开小程序会产生一个临时的code(code有实效性),通过这个code加上一些参数作 可以获取openID和sessionKey。

    具体需要什么参数呢?官方介绍

    2,具体步骤

    A,拿到appid和appsecret

    B,通过小程序wx.login({...}); 函数获取code

    C,把code、appid、secret、type作为参数 发送给服务器换取 openID

    3,具体实现

    由于code是用户登录是产生的,grat_type是默认的,所以只要再拿到appIDappSecret

    小程序的 appId 和小程序的 appSecret获取方法:

    A:登录微信公众平台 https://mp.weixin.qq.com

    B:找到开发

    小程序客户端获取code

    在小程序app.js 中加入 下面的代码:当编译工程时会自动发送请求并且把code发送给服务器。

    // 登录
        wx.login({
          success: res => {
            // 发送 res.code 到后台换取 openId, sessionKey, unionId
            if (res.code) {
              wx.request({
                url: 'http://localhost:8080/cis',
                data: {
                  code: res.code
                },
                header: {
                  'content-type': 'application/x-www-form-urlencoded'
                },
                success(res) {
                  console.log("openid:" + res.data.openid);
                  if (res.data.openid != "" || res.data.openid != null) {
                    // 登录成功
                    wx.setStorageSync("openid", res.data.openid);//将用户id保存到缓存中
                    wx.setStorageSync("session_key", res.data.session_key);//将session_key保存到缓存中
                  } else {
                    // 登录失败
                    // TODO 跳转到错误页面,要求用户重试
    
    
                    return false;
                  }
                }
              })
            } else {
              console.log('获取用户登录态失败!' + res.errMsg)
            }
          }
        })
      

    服务端用idea建立springboot工程 导入web依赖

    A:

    B:

    C:

    D:

    在pom.xml中引入依赖:

         <!--Http Requset封装-->
            <!--http requset-->
            <dependency>
                <groupId>com.github.kevinsawicki</groupId>
                <artifactId>http-request</artifactId>
                <version>6.0</version>
            </dependency>
    
            <!--json 解析-->
            <!--https://mvnrepository.com/artifact/com.alibaba/fastjson -->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>fastjson</artifactId>
                <version>1.2.49</version>
            </dependency>

    E:

    建立controller包和server包,在server包下创建impl包:

     WeChatController类用来处理请求,接收参数(code),代码如下:

    import com.cnetopro.httpdemo.service.WeChatService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class WeChatController {
        @Autowired
        WeChatService wc;
    
        @RequestMapping("/cis")
        public void getcode(@RequestParam(value = "code")String  code){
            System.out.println(code);
    
           wc.codetoopenid(code);
    
        }
    }

    WeChatService接口用来 发送get请求获取openID和sessionkey,代码如下

    import org.springframework.stereotype.Service;
    
    
    public interface WeChatService {
        public String codetoopenid(String code);
    }

    WeChartServiceimpl类用来实现WeChartService里面的方法,代码如下

    注意把xxxx...替换成自己的 appid

    把eeeeee...替换成自己的secret

    import com.alibaba.fastjson.JSON;
    import com.alibaba.fastjson.JSONObject;
    import com.cnetopro.httpdemo.service.WeChatService;
    import com.github.kevinsawicki.http.HttpRequest;
    import org.springframework.stereotype.Service;
    
    import java.util.HashMap;
    import java.util.Map;
    
    @Service
    public class WeChatServiceimpl implements WeChatService {
    
        @Override
        public String codetoopenid(String code) {
            Map<String, String> data = new HashMap<String, String>();
            data.put("appid", "xxxxxxxxxxxxxxxxx");
            data.put("secret", "eeeeeeeeeeeeeeeeeeeeeeeeee");
            data.put("js_code", code);
            data.put("grant_type", "authorization_code");
    
    
            String response = HttpRequest.get("https://api.weixin.qq.com/sns/jscode2session").form(data).body();
            System.out.println("Response was: " + response);
            JSONObject obj= JSON.parseObject(response);//将json字符串转换为json对
            System.out.println(obj);
    
    
    
            return null;
        }
    }

    运行结果:

    成功获取openID和sessionkey

    WeChatServiceimpl代码说明:

    用这个jar包来封装https请求

      <!--http requset-->
            <dependency>
                <groupId>com.github.kevinsawicki</groupId>
                <artifactId>http-request</artifactId>
                <version>6.0</version>
            </dependency>

    用这个jar包来处理接收的数据

           <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>fastjson</artifactId>
                <version>1.2.49</version>
            </dependency>

    4、可能出现的错误说明

    1.小程序

     错误:http://localhost:8080 不在以下 request 合法域名列表中,请参考文档

    解决办法:点击小程序开发工具右上角详情>本地设置>不校验合法域名

    2.idea开发工具控制台报错

    (这个错误困扰了3个小时)

     {"errcode":40013,"errmsg":"invalid appid, hints: [ req_id: dHMAcEyFe-9lrrvA ]"}

    错误原因1: appId填错了

    错误原因2:secret填错了

    错误原因3(非常重要):微信开发着工具创建小程序时的appId与 服务器端代码的appId不一致,(因为有时喜欢用接口测试号appid)

    5、代码下载

    github:下载地址

    gitee:下载地址

  • 相关阅读:
    Linux thread 泄露问题
    QQ通讯原理
    小谈Onlinegame服务器端设计
    Linux 如何打开端口
    linux系统软件更新
    MVC
    wubi+ubuntu
    [转]openfire源码部署~
    Apache开源项目分类列表[转]
    [转]java.util.MissingResourceException: Can't find bundle for base name
  • 原文地址:https://www.cnblogs.com/easyidea/p/12367588.html
Copyright © 2011-2022 走看看