标签归档:微信

laravel 社会化登录简介

socialite作为官方包使用起来非常方便,目前支持大多数的社会化登录网站,比如微信,微博,Github等等。

具体支持哪些网站,参见列表:https://socialiteproviders.github.io/about.html

比如网站需要对接微信web授权登录,使用https://socialiteproviders.github.io/providers/weixin.html即可,文档已经写的比较完善,这里不再赘述。

举个微信实际例子:

<?php

namespace App\Http\Controllers\WeChat;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Laravel\Socialite\Facades\Socialite;


class WeChatController extends Controller
{
    public function oauth(Request $request)
    {
        $url = $request->input('url', ''); // 来源url
        return Socialite::with('weixin')->redirectUrl(url("wechat/auth/callback?url=".urlencode($url)))->redirect();
    }

    public function callback(Request $request)
    {
        $oauthUser = Socialite::with('weixin')->user();
        $request->session()->put('user_wechat', $oauthUser->user);
        return redirect($request->input('url'));
    }
}

在中间件中判断session是否存在,不存在调用oauth接口即可。可以说灰常方便了😀

php微信网页授权demo

最近在做微信网页授权相关功能,以下整理简单的授权demo,在开始做之前认真看下微信的开发文档:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842 讲解的十分详细。

没有公共账号的话可以到这里申请一个测试账号: https://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index

以下代码auth()方法为入口,路由上直接绑定这个方法即可,如果是Laravel建议使用:https://www.easywechat.com/docs/master/zh-CN/official-account/oauth

<?php

namespace App\Http\Controllers\WeChat;

class WeChatController
{
    private $app_id = 'wx107********'; // 替换为自己的app_id
    private $app_secret = '7d29151e****'; // 替换为自己的app_secret


    public function auth()
    {
        $redirect_uri = "https://mango/wechat/auth"; // 请替换成自己的url
        if (!isset($_GET['code'])) {
            $authorizationUrl = $this->get_authorize_url($redirect_uri, "test");
			header('Location: ' . $authorizationUrl);
            exit;
            
        } else {
            $accessToken = $this->get_access_token($this->app_id, $this->app_secret, $_GET['code']);
            var_dump($accessToken);
            if (!empty($accessToken)) {
                $userInfo = $this->get_user_info($accessToken['access_token'], $accessToken['openid']);
                var_dump($userInfo);
            }

        }

    }


    /**

    获取微信授权链接

    @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_userinfo&state={$state}#wechat_redirect";
    }


    /**

    获取授权token

    @param string $code 通过get_authorize_url获取到的code
     */

    public function get_access_token($app_id = '', $app_secret = '', $code = '')
    {

        $token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->app_id}&secret={$this->app_secret}&code={$code}&grant_type=authorization_code";
        $token_data = $this->http($token_url, "GET");

        if($token_data[0] == 200)
        {
            return json_decode($token_data[1], TRUE);
        }

        return FALSE;
    }

    /**

    获取授权后的微信用户信息

    @param string $access_token

    @param string $open_id
     */

    public function get_user_info($access_token = '', $open_id = '')
    {

        if($access_token && $open_id)
        {
            $info_url = "https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$open_id}&lang=zh_CN";
            $info_data = $this->http($info_url, 'GET');

            if($info_data[0] == 200)
            {
                return json_decode($info_data[1], TRUE);
            }
        }

        return FALSE;
    }

    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);
    }
}