在小程序中获取openId,附加具体代码

1.客户端代码

 // 获取 code
  getLogin: function () {
    var that = this;
    wx.login({
      success: function (res) {
        that.getOpenId(res.code);
        console.log(res);
      }
    });
  },
  //获取openid
  getOpenId: function (code) {
    var that = this;
    wx.request({
      url: that.url.openId,
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: { 'code': code },
      success: function (res) {
        var openId = res.data.openid;
        console.log(res.data.openid);
        // that.xiadan(openId);
      }
    })
  },

2.后台 php端 代码:

//    获取openId
    function getOpenId($code)
    {
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='
               . $this->appid . '&secret=' 
              . $this->secret . '&js_code=' 
             . $code . '&grant_type=authorization_code';
        return $this->getHTTPS($url);
    }

    //获取https页面信息
    function getHTTPS($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_REFERER, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

//  封装到公共的方法之后  在其它php中调用,并返回
  public function openId()
    {
        $code = $this->request->post('code');
        echo $this->getOpenId($code);
    }

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 137,063评论 19 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 180,127评论 25 708
  • 从小学一年级我们就接触英语一直学习到大学,可是大多数人都无法与老外应答如流。我们花在英语学习上的时间不算少,但为何...
    周子鱼Jo阅读 1,156评论 1 7
  • 想骂人 对镜子吐痰 想骂人 翻乱门前的花园 想骂人 想惹人嫌讨人烦 想骂人 蹲在房檐把写给你的歌再唱十遍二十遍 想...
    撸串儿评论员阅读 137评论 2 1
  • # 联系方式 - 手机:18059291620 - Email:chenwentao9562@gmail.com ...
    沧溟宗主阅读 781评论 0 0

友情链接更多精彩内容