微信公众号开发之授权

微信公众号开发之授权

开发前准备

首先准备自己的服务器资源,已有服务器的请忽略服务器资源。
我这里演示新浪云服务器环境搭建:(新注册号有免费云豆可用)

服务器资源(https://sae.sina.com.cn)

微信公众号开发之授权_第1张图片

access_token与服务器接入在这里插入图片描述

![在这里插入图片描述](https://img-blog.csdnimg.cn/20181128100456310.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzIxNDI5Mzk1,size_16,color_FFFFFF,t_70

access_token与服务器接入

微信公众号开发之授权_第2张图片

微信公众号开发之授权_第3张图片

微信公众号开发之授权_第4张图片

微信公众号开发之授权_第5张图片

微信授权登录,获取登录信息

微信公众号开发之授权_第6张图片

微信公众号开发之授权_第7张图片

微信公众号开发之授权_第8张图片

微信公众号开发之授权_第9张图片

微信公众号开发之授权_第10张图片

微信公众号开发之授权_第11张图片
微信公众号开发之授权_第12张图片

##费话不多说,直接上代码(php TP框架),第一个文件WechatController.php

<?php
namespace Home\Controller;
use Think\Controller;
use Common\Model\UserModel as UserModel;

class WechatController extends Controller{

    private $appid;
    private $appkey;
    private $baseurl ;

    //微信公众号授权
    public function __construct(){
        parent::__construct();
        $this->appid = C("WEIXIN_INFO.AppID");
        $this->appkey = C("WEIXIN_INFO.AppSecret");
        $this->baseurl = "https://api.weixin.qq.com/";
    }


    //第一步:用户同意授权,获取code
    public function index(){
        $scope = "snsapi_userinfo";
        $callback = urlencode(C('SITE_URL')."Home/Wechat/callback");
        $state = time();

        $URL_GET_CODE = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$this->appid&redirect_uri=$callback&response_type=code&scope=$scope&state=$state#wechat_redirect";
        //echo $URL_GET_CODE;
        header("Location: $URL_GET_CODE");
        exit();
    }

    //回调
    public function callback(){
        header("content-type:text/html; charset=utf-8");
        $code = I("get.code");
        $state = I("get.state");
        if($code && $state){
            $data = $this->access_token($code);
            if($data){
                $access_token = $data['access_token'];
                $openid = $data['openid'];
                $userinfo = $this->userinfo($access_token,$openid);
                if($this->login_sccess($userinfo)){
                    $ref = session("ref");
                    if(!$ref){
                        header('Location:/Home/Index/index');
                    }else{
                        header("Location:$ref");
                        session("ref",null);
                    }
                    exit();
                }
            }
        }
        header('Location:/Home/Wechat/login_failure');
    }
    //第二步:通过code换取网页授权access_token
    private function access_token($code){
        $URL_GET_ACCESS_TOKEN ="sns/oauth2/access_token?appid=$this->appid&secret=$this->appkey&code=$code&grant_type=authorization_code";

        $content = https_get($this->baseurl.$URL_GET_ACCESS_TOKEN);
        if($content){
            $data = json_decode($content,true);
            return $data;
        }else{
            return false;
        }

    }
    //第三步:刷新access_token(如果需要)
    public function refresh_token($access_token){
        $URL_REFRESH_TOKEN = "sns/oauth2/refresh_token?appid=$this->appid&grant_type=refresh_token&refresh_token=$access_token ";
        $content = https_get($this->baseurl.$URL_REFRESH_TOKEN);
    }

    //第四步:拉取用户信息(需scope为 snsapi_userinfo)
    private function userinfo($access_token,$openid){

        $URL_GET_USER_INFO = "sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN";
        $content = https_get($this->baseurl.$URL_GET_USER_INFO);
        if($content)
        {
            $json = json_decode($content,true);
            return $json;
        }else{
            return false;
        }
    }

    private function login_sccess( $userinfo){

        if($userinfo && $userinfo['errcode']){
            echo $userinfo['errmsg'];
            exit();
        }

        $userModel = new UserModel();

        if($userinfo && $userinfo['openid'])
        {
            $user = $userModel->where(array('openid' =>$userinfo['openid']))->find();
            if(!$user){
                $data['openid'] = $userinfo['openid'];
                $data['nickname'] = filterEmoji($userinfo['nickname']);
                $data['sex'] = $userinfo['sex'];
                $data['headimg'] = $userinfo['headimgurl'];
				
                //$userModel->data($data)->add();
                $userModel -> addUser($data['openid'], $data['nickname'], $data['headimg'],$data['sex']);
                $userid = $userModel->getLastInsID();
                $user = $userModel->where(array('user_id' =>$userid))->find();
            }
            session('user', $user);
            return true;
        }
        return false;

    }
    public function login_failure()
    {
        header("content-type:text/html; charset=utf-8");
        echo "登陆失败";
    } 
}

##费话不多说,直接上代码(php TP框架),第二个文件WechatController中要用到的function function.php

<?php

/**
 * 手机号正则
 */
function is_mobile($telphone) {
    if (preg_match("/^1[34578]{1}\d{9}$/", $telphone)) {
        return true;
    }
    return false;
}
/**
 * 邮箱正则
 */
function is_email($email) {
    if (preg_match("/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/", $email)) {
        return true;
    }
    return false;
}
/**
 * 身份证号正则
 */
function is_id_number($id_number) {
    if (preg_match("/^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/", $id_number)) {
        return true;
    }
    return false;
}
//HTTPS GET
function https_get($url) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($curl, CURLOPT_SSLVERSION, 1); // CURL_SSLVERSION_TLSv1

    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $content = curl_exec($curl);
    $status = curl_getinfo($curl);
    
    curl_close($curl);
    if (intval($status["http_code"]) == 200) {
        return $content;
    } else {
        return false;
    }
}

//HTTPS POST
function https_post($url, $data = null) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    if (!empty($data)) {
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $content = curl_exec($curl);
    $status = curl_getinfo($curl);
    curl_close($curl);
    if (intval($aStatus["http_code"]) == 200) {
        return $content;
    } else {
        return false;
    }
}

/**
 * 返回固定长度的随机字符串,组成:a-z,A-Z,0-9
 * @param type $length 随机字符总长度
 */
function createNonceStr($length = 16) {
    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    $str = "";
    for ($i = 0; $i < $length; $i++) {
        $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
    }
    return $str;
}

function getIP() {
    global $ip;
    if (getenv("HTTP_CLIENT_IP")) {
        $ip = getenv("HTTP_CLIENT_IP");
    } else if (getenv("HTTP_X_FORWARDED_FOR")) {
        $ip = getenv("HTTP_X_FORWARDED_FOR");
    } else if (getenv("REMOTE_ADDR")) {
        $ip = getenv("REMOTE_ADDR");
    } else {
        $ip = "Unknow";
    }
    return $ip;
}

/**
 * 字体库
 * 生成证书时用到
 */
function fontFamily() {
    $array = array(
        "1" => array('name' => "默认字体", 'file' => ROOT_PATH . "/Public/css/ttfs/simsun.ttf"),
        "2" => array('name' => "Calibri", 'file' => ROOT_PATH . "/Public/css/ttfs/calibri.ttf"),
        "3" => array('name' => "超黑粗体", 'file' => ROOT_PATH . "/Public/css/ttfs/hanyi_chaochu_hei.ttf"),
        "4" => array('name' => "斜体", 'file' => ROOT_PATH . "/Public/css/ttfs/yun_xieti.ttf"), //云字体
        "5" => array('name' => "Georgia Bold", 'file' => ROOT_PATH . "/Public/css/ttfs/georgiab.ttf"), //
        "6" => array('name' => "constantia", 'file' => ROOT_PATH . "/Public/css/ttfs/constantia.ttf"),
        "7" => array('name' => "Arial", 'file' => ROOT_PATH . "/Public/css/ttfs/Arial.ttf"), //
        "8" => array('name' => "arialbd", 'file' => ROOT_PATH . "/Public/css/ttfs/arialbd.ttf"), //
        "9" => array('name' => "HelveticaLT", 'file' => ROOT_PATH . "/Public/css/ttfs/Helvetica LT 33 Thin Extended.ttf"), //
        "10" => array('name' => "Helvetica Narrow Bold", 'file' => ROOT_PATH . "/Public/css/ttfs/Helvetica Narrow Bold.ttf"), //
        "11" => array('name' => "Helvetica Bold", 'file' => ROOT_PATH . "/Public/css/ttfs/Helvetica Bold.ttf"), //
        "12" => array('name' => "Helvetica", 'file' => ROOT_PATH . "/Public/css/ttfs/Helvetica.ttf"), //
    );
    return $array;
}

/**
 * 日期格式库
 * 生成证书时用到
 */
function dateFormat() {
//    $format1 = "F d,Y";
//    $format2 = "jS F Y";
//    $array = array(
//     '1' => array("name" => date($format1, $time), 'format' => $format1, 'formatM' => array("F d", "F d Y"), 'formatD' => array('F d', 'd Y')),
//     '2' => array("name" => date($format2, $time), 'format' => $format2, 'formatM' => array("jS F", "jS F Y"), 'formatD' => array('jS', 'jS F Y')),
//    );
    $format1 = "F d,Y";
    $format2 = "jS F Y";
    $format3 = "F jS,Y";
    $format4 = "jS/F/Y";
    $format5 = "F j Y";
    $format6 = "m.d.Y";
    $format7 = "m/d/y";
    $format8 = "jS                       F             Y";

    $time = 1488507632;
    $array = array(
        '1' => array("name" => date($format1, $time), 'format' => $format1, 'formatM' => array("F d", "d, Y"), 'formatD' => array('F d', 'd, Y')),
        '2' => array("name" => date($format2, $time), 'format' => $format2, 'formatM' => array("jS F", "jS F Y"), 'formatD' => array('jS', 'jS F Y')),
        '3' => array("name" => date($format3, $time), 'format' => $format3, 'formatM' => array("F jS ", " F jS Y"), 'formatD' => array('F jS ', ' jS,Y')),
        '4' => array("name" => date($format4, $time), 'format' => $format4, 'formatM' => array("jS/F/Y", "jS/F/Y"), 'formatD' => array('jS/F/Y', 'jS/F/Y')),
        '5' => array("name" => date($format5, $time), 'format' => $format5, 'formatM' => array("F j", "j,Y"), 'formatD' => array("F j", "j,Y")),
        '6' => array("name" => date($format6, $time), 'format' => $format6, 'formatM' => array("m.d", "d.Y"), 'formatD' => array("m.d", "d.Y")),
        '7' => array("name" => date($format7, $time), 'format' => $format7, 'formatM' => array("m/d/y", "m/d/y"), 'formatD' => array('m/d/y', 'm/d/y')),
        '8' => array("name" => date($format8, $time), 'format' => $format8), //十字星证书专用
    );
    return $array;
}

/**
 * 删除给定的文件
 */
function delFile($filename) {
    @unlink($filename);
}

/**
 * 获得名称的拼音
 */
function getPinYin($title) {
    $title = trim($title);
    vendor("pinyin");
    $pinyin = new pinyin();
    if (preg_match_all('/^[0-9a-zA-Z]{1,}$/', $title, $match)) {
        $pinyinString = $title;
    } else {
        $data = $pinyin->get($title, 'utf8');
        $pinyinString = $data['res'];
        //$short_py = $this->data['short_res'];
    }
    return $pinyinString;
}

/**
 * json格式验证
 */
function analyJson($json_str) {
    $json_str = str_replace('\\', '', $json_str);
    $out_arr = array();
    preg_match('/{.*}/', $json_str, $out_arr);
    if (!empty($out_arr)) {
        $result = json_decode($out_arr[0], TRUE);
        return $result;
    }
    return false;
}
/**
 * 过滤掉emoji表情
 */
function filterEmoji($str) {
    $str = preg_replace_callback(
            '/./u', function (array $match) {
        return strlen($match[0]) >= 4 ? '' : $match[0];
    }, $str);

    return $str;
}

/**
 * 判断字符串是否为英文、空格、下划线组成
 */
function judge_eng_str($str) {
    if (preg_match('/^[a-zA-Z_\s]+$/', $str)) {
        return true;
    }
    return false;
}

/**
 * 返回日期连接符(生成证书时)
 */
function date_connector_sel($date_connector) {
    $date_connector_arr = array(
        '1' => '-',
        '2' => '&',
    );
    if (array_key_exists($date_connector, $date_connector_arr)) {
        return $date_connector_arr[$date_connector];
    } else {
        return '-';
    }
}

你可能感兴趣的:(微信公众号开发)