ThinkPHP接入EasyWechat

使用EasyWechat接入用户登录,获取用户信息

官方文档

<?php

namespace app\index\controller;

use EasyWeChat\Factory;
use think\Controller;

class EasyWechat extends Controller
{
    protected $app;
    public function _initialize()
    {
        $config = [
            'app_id'        => 'wx5d2f01e8ab9532dc',
            'secret'        => 'f36d7f5c26d76662d533c29072a4f5e5',
            'token'         => 'JOfggDDrVhODrrGqnfRUvTGvthXdvtzV',
            'aes_key'       => '', // EncodingAESKey,兼容与安全模式下请一定要填写!!!
            // 指定 API 调用返回结果的类型:array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',

            'log'           => [
                'level' => 'debug',
                'file'  => __DIR__ . '/wechat.log',
            ],
            /**
             * OAuth 配置
             *
             * scopes:公众平台(snsapi_userinfo / snsapi_base),开放平台:snsapi_login
             * callback:OAuth授权完成后的回调页地址
             */
            'oauth'         => [
                'scopes'   => ['snsapi_userinfo'],
                'callback' => 'http://lj.lxx123.club/index/Easy_Wechat/oauth_callback',
            ],
        ];

        $this->app = Factory::officialAccount($config);
    }
    /**
     * 微信接入地址,验证echostr
     * @return [type] [description]
     */
    public function response_echostr()
    {
        $this->app->server->serve()->send();
        die;
    }
    /**
     * 授权地址
     * @return [type] [description]
     */
    public function index()
    {
        $response = $this->app->oauth->scopes(['snsapi_userinfo'])->redirect();
        $response->send();
    }
    /**
     * 授权成功跳转地址,获得用户信息
     * @return [type] [description]
     */
    public function oauth_callback()
    {
        $user = $this->app->oauth->user();
        // $user 可以用的方法:
        // $user->getId();  // 对应微信的 OPENID
        // $user->getNickname(); // 对应微信的 nickname
        // $user->getName(); // 对应微信的 nickname
        // $user->getAvatar(); // 头像网址
        // $user->getOriginal(); // 原始API返回的结果
        // $user->getToken(); // access_token, 比如用于地址共享时使用
    }
}

使用例子

<?php

namespace app\index\controller;

use EasyWeChat\Factory;
use EasyWeChat\Kernel\Messages\Image;
use Grafika\Color;
use Grafika\Grafika;
use think\Controller;
use think\Db;

class EasyWechat extends Controller
{
    protected $app;
    protected $app_pay;
    public function _initialize()
    {
        $config = [
            'app_id'        => 'wx5d2f01e8ab9532dc',
            'secret'        => 'f36d7f5c26d76662d533c29072a4f5e5',
            'token'         => 'JOfggDDrVhODrrGqnfRUvTGvthXdvtzV',
            'aes_key'       => '', // EncodingAESKey,兼容与安全模式下请一定要填写!!!
            // 指定 API 调用返回结果的类型:array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',

            'log'           => [
                'level' => 'debug',
                'file'  => __DIR__ . '/wechat.log',
            ],
            /**
             * OAuth 配置
             *
             * scopes:公众平台(snsapi_userinfo / snsapi_base),开放平台:snsapi_login
             * callback:OAuth授权完成后的回调页地址
             */
            'oauth'         => [
                'scopes'   => ['snsapi_userinfo'],
                'callback' => 'http://lj.lxx123.club/index/Easy_Wechat/oauth_callback',
            ],
        ];
        $config_pay = [
            // 必要配置
            'app_id'     => '',
            'mch_id'     => '',
            'key'        => '', // API 密钥

            // 如需使用敏感接口(如退款、发送红包等)需要配置 API 证书路径(登录商户平台下载 API 证书)
            'cert_path'  => 'D:/lxx/qiangdan/extend/wxpay/cert/apiclient_cert.pem', // XXX: 绝对路径!!!!
            'key_path'   => 'D:/lxx/qiangdan/extend/wxpay/cert/apiclient_key.pem', // XXX: 绝对路径!!!!
            'notify_url' => 'http://lj.lxx123.club/index/Easy_Wechat/pay_callback', // 你也可以在下单时单独设置来想覆盖它
        ];
        $this->app     = Factory::officialAccount($config);
        $this->app_pay = Factory::payment($config_pay);
    }
    /**
     * 微信接入地址,验证echostr
     * @return [type] [description]
     */
    public function response_echostr()
    {
        // 验证echostr字符串
        if (input('?get.echostr')) {
            $this->app->server->serve()->send();
            die;
        }
        $this->app->server->push(function ($message) {
            switch ($message['MsgType']) {
                case 'event':
                    switch ($message['Event']) {
                        case 'SCAN':
                            $p_openid = Db::table('tp_lxx_users')->where('id', $message['EventKey'])->value('openid');
                            $this->send_template_new($p_openid);
                            return '扫码的ID是:' . $message['EventKey'] . ',Ticket是:' . $message['Ticket'] . ',ToUserName,FromUserName';
                            break;
                        case 'subscribe':
                            return '感谢关注!';
                            break;
                        case 'CLICK':
                            switch ($message['EventKey']) {
                                case 'qrcode':
                                    $data_user_info = Db::table('tp_lxx_users')->where('openid', $message['FromUserName'])->find();
                                    if (empty($data_user_info)) {
                                        $str = <<<string
需要先注册登录平台才能获取推广二维码哟!
???
??
?
string;
                                        return $str;
                                    }
                                    if (!empty($data_user_info['media_id'])) {
                                        return new Image($data_user_info['media_id']);
                                    }
                                    $ret       = $this->make_qrcode("{$data_user_info['id']}");
                                    $code_url  = $ret['qr_url'];
                                    $head_url  = $data_user_info['head_url'];
                                    $name      = base64_decode($data_user_info['nickname']);
                                    $base_path = $this->make_image("{$data_user_info['id']}", $name, $code_url, $head_url);
                                    trace(dump($base_path), 'error');
                                    $upload_ret = $this->upload_qrcode($base_path);
                                    Db::table('tp_lxx_users')->where('openid', $message['FromUserName'])->update(['media_id' => $upload_ret['media_id']]);
                                    return new Image($upload_ret['media_id']);
                                    break;

                                default:
                                    return '其他点击事件!';
                                    break;
                            }
                            break;

                        default:
                            return '收到event事件消息';
                            break;
                    }
                    return '收到事件消息' . $message['EventKey'];
                    break;
                case 'text':
                    return '收到文字消息' . $message['FromUserName'];
                    break;
                case 'image':
                    return '收到图片消息';
                    break;
                case 'voice':
                    return '收到语音消息';
                    break;
                case 'video':
                    return '收到视频消息';
                    break;
                case 'location':
                    return '收到坐标消息';
                    break;
                case 'link':
                    return '收到链接消息';
                    break;
                case 'file':
                    return '收到文件消息';
                default:
                    return '收到其它消息';
                    break;
            }
        });
        $this->app->server->serve()->send();
    }
    /**
     * 文件下载
     * @param  [type] $url  [带http的文件地址]
     * @param  [type] $absolute_path [保存的本地绝对路径带扩展名]
     * @return [type]       [description]
     */
    public function download($url, $absolute_path = '')
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        $file = curl_exec($ch);
        curl_close($ch);
        $resource = fopen($absolute_path, 'a');
        fwrite($resource, $file);
        fclose($resource);
    }
    /**
     * 获取用户的推广图片
     * @param  integer $uid      [UID]
     * @param  string  $text     [姓名]
     * @param  string  $code_url [带http的二维码地址]
     * @param  string  $head_url [带http的头像地址]
     * @return [str]             [本地保存绝对路径]
     */
    public function make_image($uid, $text, $code_url, $head_url)
    {
        $code_url  = $code_url;
        $code_path = ROOT_PATH . 'public/static/' . $uid . 'code . jpg';
        $this->download($code_url, $code_path);
        $head_url  = $head_url;
        $head_path = ROOT_PATH . 'public/static/' . $uid . 'head . jpg';
        $this->download($head_url, $head_path);
        $text   = $text;
        $base   = ROOT_PATH . 'public/static/base.jpg';
        $code   = $code_path;
        $head   = $head_path;
        $editor = Grafika::createEditor();
        $editor->open($image1, $base); // 背景
        $editor->open($image2, $code); // 二维码
        $editor->open($image3, $head); // 头像
        $editor->blend($image1, $image2, 'normal', 0.9, 'center', 0, 300);
        $editor->blend($image1, $image3, 'normal', 0.9, 'top-left', 80, 100);
        $ttf = ROOT_PATH . '/vendor/topthink/think-captcha/assets/zhttfs/1.ttf';
        $editor->text($image1, $text, 30, 250, 150, new Color("#000000"), $ttf, 0);
        $absolute_path = ROOT_PATH . 'public/static/' . $uid . 'shareimg.jpg';
        $editor->save($image1, $absolute_path);
        unlink($code);
        unlink($head);
        return $absolute_path;
    }
    /**
     * 上传图片到微信端
     * @return [array] [media_id,url]
     */
    public function upload_qrcode($absolute_path = '')
    {
        if (empty($absolute_path)) {
            return false;
        }
        $result = $this->app->material->uploadImage($absolute_path);
        return $result;
    }
    /**
     * 生成二维码
     * @param  integer $uid [description]
     * @return [array]       [qr_url,ticket]
     */
    public function make_qrcode($uid, $path = '')
    {
        $result           = $this->app->qrcode->forever($uid); // forever永久,temporary临时
        $result['qr_url'] = $this->app->qrcode->url($result['ticket']);
        if (!empty($path)) {
            $path          = ROOT_PATH . 'public/static/';
            $absolute_path = $path . $uid . ' . jpg';
            file_put_contents($absolute_path, $content);
            $result['absolute_path'] = $absolute_path;
        }
        return $result;
    }
    public function test($value='')
    {
        $xx = $this->app->auto_reply->current();
        dump($xx);
    }
    /**
     * 获取公众号目录
     * @return [type] [description]
     */
    public function get_menu_list()
    {
        $list = $this->app->menu->list();
        dump($list);
    }
    /**
     * 设置公众号目录
     */
    public function set_menu_list()
    {
        $buttons = [
            [
                "type" => "click",
                "name" => "qrcode",
                "key"  => "qrcode",
            ],
            [
                "name"       => "菜单",
                "sub_button" => [
                    [
                        "type" => "view",
                        "name" => "搜索",
                        "url"  => "http://www.soso.com/",
                    ],
                    [
                        "type" => "view",
                        "name" => "登录",
                        "url"  => "http://lj.lxx123.club/index/Easy_Wechat/wechat_login",
                    ],
                    [
                        "type" => "click",
                        "name" => "qrcode2",
                        "key"  => "qrcode2",
                    ],
                ],
            ],
        ];
        $result = $this->app->menu->create($buttons);
        if ($result['errcode'] == 0) {
            return true;
        } else {
            return false;
        }
    }
    /**
     * 授权地址
     * @return [type] [description]
     */
    public function wechat_login()
    {
        $response = $this->app->oauth->redirect();
        $response->send();
    }
    /**
     * 授权成功跳转地址,获得用户信息
     * @return [type] [description]
     */
    public function oauth_callback()
    {
        $user       = $this->app->oauth->user();
        $user_info  = $user->getOriginal();
        $check_user = Db::table('tp_lxx_users')->where('openid', $user_info['openid'])->count();
        if ($check_user == 0) {
            $data = [
                'openid'   => $user_info['openid'],
                'nickname' => base64_encode($user_info['nickname']),
                'head_url' => $user_info['headimgurl'],
            ];
            $is_insert = Db::table('tp_lxx_users')->insert($data);
        }
    }
    /**
     * 扫描二维码用户关注提醒
     * @param  [type] $openid [description]
     * @return [type]         [description]
     */
    public function send_template_new($openid)
    {
        $this->app->template_message->send([
            'touser'      => $openid,
            'template_id' => 'kXPYggX1fGDLDIuMypAc_nO5Wob684aWdazus6eQuLE',
            'url'         => 'https://easywechat.org',
            'data'        => [
                'name'     => 'name',
                'action'   => 'action',
                'num'      => 'num',
                'thistime' => 'thistime',
                'status'   => 'status',
            ],
        ]);
    }
    /**
     * 下单
     * @return [type] [description]
     */
    public function do_order()
    {
        $result = $this->app_pay->order->unify([
            'body'             => '腾讯充值中心 - QQ会员充值',
            'out_trade_no'     => '20150806125346',
            'total_fee'        => 88,
            'spbill_create_ip' => '123.12.12.123', // 可选,如不传该参数,SDK 将会自动获取相应 IP 地址
            'notify_url'       => '', // 支付结果通知网址,如果不设置则会使用配置里的默认地址
            'trade_type'       => 'JSAPI',
            'openid'           => 'oUpF8uMuAJO_M2pxb1Q9zNjWeS6o',
        ]);
        dump($result);
    }
    /**
     * 下单回调
     * @return [type] [description]
     */
    public function pay_callback()
    {
        $response = $this->app_pay->handlePaidNotify(function ($message, $fail) {
            // 你的逻辑
            return true;
            // 或者错误消息
            // $fail('Ordernotexists . ');
        });

        $response->send();
    }
}

猜你喜欢

转载自blog.csdn.net/hd2killers/article/details/80841368