php - 微信小程序获取不到openid?

查看:286
本文介绍了php - 微信小程序获取不到openid?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

<?php

public $appid = 'wx5qweqweqweqdd4d43fcb3';
public $secret = '2c8d06fsadasfgssdfhdfgsdca43e2fd43029f6';
public $sessionKey = '';
// 小程序登录
public function loginAction(){
    $code = I('get.code');
    $loginUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=".$this->appid."&secret=".$this->secret."&js_code=".$code."&grant_type=authorization_code";
    $res = file_get_contents($loginUrl);
    $wxres = json_decode($res,true);
    $user = M('user');
    $data = $user->where(array('openid'=>$wxres['openid']))->find();
    if(!$data){
        $res = $user->add(array('openid'=>$wxres['openid']));
    }
    session("wxopenid",$wxres['openid']);
    $session_id = session_id();
    $wxres['session_id'] = $session_id;
    $wxres['creattime'] = (string)time();
    $this->sessionKey = $wxres['session_key'] ;
    $this->ajaxReturn($wxres);
}

解决方案

我的openid在小程序里是这样拿的。。所以我觉得你应该需要先请求wxLogin,要把返回的code传给js_code才可以。。而不是用一个固定的字符串‘authorization_code’。。

wx.login({
    success: function (loginCode) {
      var appid = 'appid';
      var secret = 'secret ';
      
      //调用request请求api转换登录凭证  
      wx.request({
        url: 'https://api.weixin.qq.com/sns/jscode2session?appid='+appid+'&secret='+secret+'&grant_type=authorization_code&js_code=' + loginCode.code,
        header: {
          'content-type': 'application/json'
        },
        success: function (res) {
          // console.log(res.data.openid) //获取openid
          that.globalData.openid = res.data.openid
        }
      })
    }
  })

这篇关于php - 微信小程序获取不到openid?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆