微信小程序2019年最新服务端获取openid详解(附源码)

服务器获取原因
  1. 因为微信不允许把官方域名放到合法请求域名中, 所以官方规定必须在服务端请求openid返回给你本地
  2. 把APPID和秘钥放在小程序本地不安全
    在这里插入图片描述
  3. 请求链接
https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code

官方文档地址
在这里插入图片描述

实现
  1. 本地通过开放接口wx.login() 获取code码, 主要参照官方实例避免后期更新。
 wx.login({
      success: res => {
        if (res.code) {
          console.log('code:', res.code)
          var loginUrl = 'getOpenidSever.php' //服务端的接口地址
          wx.request({
            url: loginUrl,
            method: 'GET',
            dataType: 'json',
            data: {
              jscode: res.code //发送的code码
            },	
            success: function(res) {
               console.log('data:', res.data)
            },
            fail: function(res) {},
            complete: function(res) {},
          })
        }
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
      }
    })

在这里插入图片描述

  1. 服务端实现

getOpenidSever.php:

/**
 * 请求接口返回内容
 * @param  string $url [请求的URL地址]
 * @param  string $params [请求的参数]
 * @param  int $ipost [是否采用POST形式]
 * @return  string
 */
class getOpenid
{
    private $url;
    private $jscode;
    private $params;
    
	/**
	 * 配置URL请求参数
	 */
    function __construct($jscode)
    {
        $this->jscode = $jscode;
        $this->url = 'https://api.weixin.qq.com/sns/jscode2session';//请求地址
        $paramsArray = array(
            'appid' => 'wxfddfkjs54g5r5d5sdsf',//你的appid
            'secret' => 'krj9er9df883kjd4j5k435jk34fddf',//你的秘钥
            'js_code' => $this->jscode,//发送过来的code码
            'grant_type' => 'authorization_code'//授权类型参照官方文档 : authorization_code
        );
        $this->params = http_build_query($paramsArray);//生成URL参数字符串

    }
    
	/**
	 * 请求URL方法, 一些参数没必要理解知道就行
	 */
    public function getCurl($ispost = 0)
    {
        $httpInfo = array();
        $ch = curl_init();

        //CURL_HTTP_VERSION_NONE (默认值,让 cURL 自己判断使用哪个版本),CURL_HTTP_VERSION_1_0 (强制使用 HTTP/1.0)或CURL_HTTP_VERSION_1_1 (强制使用 HTTP/1.1)。
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        //在HTTP请求中包含一个"User-Agent: "头的字符串。
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36');
        //在尝试连接时等待的秒数。设置为0,则无限等待。
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        //允许 cURL 函数执行的最长秒数。
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        //TRUE 将curl_exec()获取的信息以字符串返回,而不是直接输出。
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if ($ispost) {
            //TRUE 时会发送 POST 请求,类型为:application/x-www-form-urlencoded,是 HTML 表单提交时最常见的一种。
            curl_setopt($ch, CURLOPT_POST, true);
            //全部数据使用HTTP协议中的 "POST" 操作来发送
            curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
            //需要获取的 URL 地址,也可以在curl_init() 初始化会话的时候
            curl_setopt($ch, CURLOPT_URL, $this->url);
        } else {
            if ($this->params) {
                //需要获取的 URL 地址,也可以在curl_init() 初始化会话的时候。
                curl_setopt($ch, CURLOPT_URL, $this->url . '?' . $this->params);
            } else {
                curl_setopt($ch, CURLOPT_URL, $this->url);
            }
        }
        $response = curl_exec($ch);
        if ($response === FALSE) {
            //echo "cURL Error: " . curl_error($ch);
            return false;
        }
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $httpInfo = array_merge($httpInfo, curl_getinfo($ch));
        curl_close($ch);
        return $response;
    }
}
//入口
$jscode = isset($_GET['jscode']) ? $_GET['jscode'] : '';
if ($jscode != '') {
    $getOpenid = new getOpenid($jscode);
    $res = $getOpenid->getCurl();
    echo $res;
}

猜你喜欢

转载自blog.csdn.net/qq_39043923/article/details/89336237