一、前期准备:

(1)公众号需要是服务号。

(2)在公众号获取appid 和secret 并把服务器的ip地址设置在IP白名单中(位置在:开发->基本配置)

(3)在公众号配置网页授权的域名

官方文档
https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Web_Developer_Tools.html#1

二、代码示例

先封装一个Wchat类:

/**
 * 微信授权相关接口
 *
 */
class Wchat
{
    private $app_id = '从公众号拿appid';
    private $app_secret = '从公众号拿secret';
    private $state = '940d26dcb';
    /**
     * 获取微信授权链接
     *
     * @param string $redirect_uri 跳转地址
     * @param mixed $state 参数
     */
    public function get_authorize_url($redirect_uri = '', $state = '')
    {
        $redirect_uri = urlencode($redirect_uri);
        return "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->app_id}&redirect_uri={$redirect_uri}&response_type=code&scope=snsapi_base&state={$state}#wechat_redirect";
    }
    /**
     * 获取微信openid
     */
    public function getOpenid($turl)
    {
        if (!isset($_GET['code'])) {
            //触发微信返回code码
            $url = $this->get_authorize_url($turl, $this->state);
            Header("Location: $url");
            exit();
        } else {
            //获取code码,以获取openid
            $code = $_GET['code'];
            $access_info = $this->get_access_token($code);
            return $access_info;
        }
    }
    /**
     * 获取授权token网页授权
     *
     * @param string $code 通过get_authorize_url获取到的code
     */
    public function get_access_token($code = '')
    {
        $appid = $this->app_id;
        $appsecret = $this->app_secret;
        $token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $appid . "&secret=" . $appsecret . "&code=" . $code . "&grant_type=authorization_code";
        //echo $token_url;
        $token_data = $this->http($token_url);
        // var_dump( $token_data);
        if ($token_data[0] == 200) {
            $ar = json_decode($token_data[1], TRUE);
            return $ar;
        }
        return $token_data[1];
    }
    
    public function http($url, $method = '', $postfields = null, $headers = array(), $debug = false)
    {
        $ci = curl_init();
        /* Curl settings */
        curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ci, CURLOPT_TIMEOUT, 30);
        curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
        switch ($method) {
            case 'POST':
                curl_setopt($ci, CURLOPT_POST, true);
                if (!empty($postfields)) {
                    curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields);
                    $this->postdata = $postfields;
                }
                break;
        }
        curl_setopt($ci, CURLOPT_URL, $url);
        curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ci, CURLINFO_HEADER_OUT, true);
        $response = curl_exec($ci);
        $http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
        if ($debug) {
            echo "=====post data======\r\n";
            var_dump($postfields);
            echo '=====info=====' . "\r\n";
            print_r(curl_getinfo($ci));
            echo '=====$response=====' . "\r\n";
            print_r($response);
        }
        curl_close($ci);
        return array($http_code, $response);
    }
    
    //判断是否是微信端
    public function isWeixin() { 
      if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) { 
        return true; 
      } else {
        return false; 
      }
    }
}

调用方法:

//前端调用代码如下:
$wchat = new wchat(); $openid = isset($_COOKIE['openid'])?$_COOKIE['openid']:'';
$isWeixin = $wchat->isWeixin();//这步判断是否在微信端 if(empty($openid) && $isWeixin) { $t_url = 'http://'.$_SERVER['HTTP_HOST'].'/当前地址?act=register'; $info = $wchat->getOpenid($t_url); if($info) { $openid = $info['openid']; setcookie('openid',$openid,time()+86400*30);
} else { $openid = ''; } } echo $openid;


点赞(2) 打赏

评论列表 共有 2 条评论

令狐冲 4年前 回复TA

@令狐冲 openid

令狐冲 4年前 回复TA

PHP博客

意见
建议
发表
评论
返回
顶部