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

    通过登录接口获取登录凭证,然后通过request请求后台获取openid,需要把后台域名放到小程序后台的request 合法域名内:

    1.wx.login  获取登录凭证

    2.wx.request 发起的是 HTTPS 请求

    3.后台处理请求并返回openid

    下面是实现代码:

    小程序代码:

    wx.login({

        success: function (res) {
            if (res.code) {
                console.log("我是登录凭证:"+res.code);
                var a = that.globalData;  //这里存储了appid、secret
     
                wx.request({
                     url: 'https://XXXXXXXXX/getopenid',  //后台获取openid的链接,该链接域名需要添加到小程序request 合法域名
                     header: { "Content-Type": "application/x-www-form-urlencoded" },
                     method: "POST",
                     data: {  code: res.code, appid: a.appid, appsecret:a.secret },  
                     success: function (res) {
                         that.globalData.openid = res.data.openid;
                         console.log("openid:"+that.globalData.openid);
                     }
               })
            } else {
               console.log('获取用户登录态失败!' + res.errMsg)
            }
        }
    });
    后台获取openid代码:

    public function getopenid(){
    $data = $_POST;
    //echo json_encode($data);
    $appid=$data['appid'];
    $appsecret=$data['appsecret'];
    $code=$data['code'];
    $get_url="https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=".$appsecret."&js_code=".$code."&grant_type=authorization_code";
    $get_return = file_get_contents($get_url);
    $get_return = (array)json_decode($get_return);
    //$openid=$get_return['openid'];
    echo json_encode($get_return);exit();

    }

    以上就是小程序获取openid的方法。

     
  • 相关阅读:
    开源协议的比较(BSD,Apache,GPL,LGPL,MIT)
    免费的DNS服务器
    网站运行时间代码
    Linux实用命令大合集(长期更新)
    Centos7基本设置
    java基础-异常
    Java基础-String
    00033-layui 自定义 字典模块 及 工具方法
    00032-layui 树形下拉选择 xmSelect(二):数据懒加载
    00031-layui 树形下拉选择 xmSelect(一):树数据一次加载
  • 原文地址:https://www.cnblogs.com/fortitude526/p/7760165.html
Copyright © 2011-2022 走看看