微信小程序如何获取OpenID

微信小程序如何获取OpenID

前端获取openid的方式(openid为用户唯一标识)

  • app.js
App({
    /**
     * 当小程序初始化完成时,会触发 onLaunch(全局只触发一次)
     */
    onLaunch: function () {
        var that = this;
        wx.login({
            success:res=>{                          // 每次用户登录都会拿到一个code
                wx.request({
                    url: that.globalData.wx_url_1 + res.code + that.globalData.wx_url_2,
                    success:res=>{
                        that.globalData.openid = res.data.openid;
                    }
                })
            }
        });
    },
 
    /**
     * 设置全局变量
     */
    globalData: {
        openid:0,
        wx_url_1: 'https://api.weixin.qq.com/sns/jscode2session?appid=自己的APPID&secret=自己的SECRET&js_code=',
        wx_url_2: '&grant_type=authorization_code'
    }
})

后端获取openid的方式

  • app.js
App({
  /**
   * 当小程序初始化完成时,会触发 onLaunch(全局只触发一次)
   */
  onLaunch: function () {
    var that = this;
    wx.login({
      success: res => {           每次用户登录都会拿到一个code
        console.log('用户code');
        console.log(res.code);
        wx.request({
          url: 'http://localhost:8082/UserCenter',
          method: 'POST',
          header: { "content-type": 'application/json' },
          data: {
            "head": {
              "appVerNo": "1.0.0",
              "functionNo": "WeChatLoginVerification"
            },
            "param": {
              "weChatCode": res.code
            }
          },
          dataType: 'json',
          responseType: 'text',
          success(res) {
            console.log('666');
            console.log(res);
            that.globalData.openid = res.data.data.openId;
          },
          fail(res) { console.log(res) },
        })
      }
    });
  },

  /**
   * 设置全局变量
   */
  globalData: {
    openid: null,
    userInfo:null
  }
})

  • 后台

在这里插入图片描述
在这里插入图片描述

/**
*@description:微信登录
*/
Public void weChatLoginVerificationRequestProcess(){
	String weChatCode=dataCenterService.getData("weChatCode");
	System.out.println("------weChatCode------"+weChatCode);
	
	//获取sessionKeyAndOpenId的api
	String getSesionKeyURL=getSessionKeyAPI+"?appid="+appId+"&secret="+appsecret+"&js_code="
	+weChatCode+"&grant_type=authorization_code";
	System.out.println("------getSesionKeyURL---------"+getSesionKeyURL);
	
	//获取到sessionKeyAndOpenId的json数据
	String returnSesionKeyAndOpendIdJson=CommonUtil.sendGetRequest(getSesionKeyURL);
	
	//连接超时
	if(returnSesionKeyAndOpendIdJson==null){
		ExceptionUtil.setFailureMsgAndThrow(cn.edu.fjnu.towide.ww.usercenter.enums.ReasonOfFailure.REQUEST_TIMED_OUT_CODE);
	}
	System.out.println("---------returnSesionKeyAndOpendIdJson--------"+returnSesionKeyAndOpendIdJson);
	JSONObject jsonObject=JSONObject.parseObject(returnSesionKeyAndOpendIdJson);
	String errcode=jsonObject.getString("errcode");
	if(WeChatReasonOfFailureConstant.ERRMSG_CODE.equals(errcode)){
		ExceptionUtil.setFailureMsgAndThrow(ReasonOfFailure.INVALID_CODE_CODE);
	}elseif(WeChatReasonOfFailureConstant.ERRMSG_CODE_BEEN_USED_CODE.equals(errcode)){
		ExceptionUtil.setFailureMsgAndThrow(ReasonOfFailure.INVALID_CODE_CODE);
	return;
	}
	String openId=jsonObject.getString("openid");
	String sessionKey=jsonObject.getString("session_key");
	//StringexpiresIn=jsonObject.getString("expires_in");//暂时未用到
	System.out.println("-----openId--------"+openId);
	ResponseData responseData=dataCenterService.getData("responseData");
	ResponseDataUtil.setHeadOfResponseDataWithSuccessInfo(responseData);
	ResponseDataUtil.putValueToData(responseData,"openId",openId);
}

  • yml
wechat:
	app_id:
	app_secret:
	get_session_key_api:
  • 如何向第三方发送get请求:

https://blog.csdn.net/weixin_44308214/article/details/109724173

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
微信小程序中的全局变量是在App.js文件中设置的,通过globalData对象来存储全局变量的值。在这个对象中,可以定义和存储需要在整个小程序中使用的变量。例如,可以定义一个名为hasLogin的全局变量,并设置初始值为false,还可以定义一个名为openid的全局变量,并初始化为null。 全局变量的使用可以在小程序的任何页面中进行。通过在页面中引入App.js文件,并使用`getApp()`方法获取到App实例,就可以访问和使用全局变量了。例如,可以通过`getApp().globalData.hasLogin`来获取或修改全局变量的值。 除了使用微信小程序原生的方式设置和使用全局变量外,还可以使用其他框架或工具来实现全局状态管理,如uni-app可以使用Vuex来定义和管理全局变量。通过在Vuex中定义全局变量的状态,并在需要使用的页面中引入并使用对应的状态值,可以实现全局变量的共享和修改。 总结起来,微信小程序的全局变量是通过在App.js文件中设置globalData对象来存储的,可以在整个小程序中共享和使用。具体的使用方式可以根据需求选择原生方式或使用框架提供的方法来实现。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [微信小程序 全局变量](https://blog.csdn.net/JxufeCarol/article/details/117735950)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [wx小程序、uni-app全局变量](https://blog.csdn.net/hbiao68/article/details/102898031)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值