微信小程序获取openid

微信开发JS代码

    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        var that =this;
        wx.request({
          url:that.globalData.url+'/api.openid/getOpenid',
          method:"post",
          data:{code:res.code},
          success:res=>{
            console.log(res.data);
          }
        })
      }
    })

下面是服务器端口的代码

    protected $appid      = "1";
    protected $secret     = "2";
    protected $grant_type = "authorization_code";

   
	public function getOpenid(){
            
        $res   = request()->param();
        $url   = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $this->appid . '&secret=' . $this->secret . '&js_code=' . $res['code'] . '&grant_type=' . $this->grant_type;
        $result=$this->http_curl_get($url);
        
       //数据就这这里了[2023-05-16T12:00:07+08:00][info] {"session_key":"R+WxJUIZclFujKdbIkpr6w==","openid":"oSvY85S3DdIx2JfX-aEg_ffmkjDw"}

		    
	}
	


	

	
	public function http_curl_get($url,$type=1) {
        	$curl = curl_init();
        	curl_setopt($curl,CURLOPT_TIMEOUT,5000);
        	curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false);
        	curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,false);
        	curl_setopt($curl,CURLOPT_USERAGENT,$_SERVER['HTTP_USER_AGENT']);
        	curl_setopt($curl,CURLOPT_URL,$url);
        	if($type == 1){
        		curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
        	}
        	$res = curl_exec($curl);
        	if($res){
        		curl_close($curl);
        			return json_decode($res,true);
        	}else {
        		$error = curl_errno($curl);
        		curl_close($curl);
        		return $error;
        	}
        }

如果出现报错:

 {"errcode":40029,"errmsg":"invalid code, rid: 6462ff8e-7f84dae1-58556329"}

检查3个步骤:

1:检查小程序内部设置请求域名是否填写

2:检查appid、AppSecret等参数密码是否正确

3:再调试微信里检查自己的APPid 是否和请求appid一致

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值