开始前,需要配置公众号网页授权

进入公众号开发-》接口权限-》网页服务-》网页授权-》网页授权域名-》www.bychem.com m.bychem.com

一、config wechat 配置文件

<?php    
    /*
     * This file is part of the overtrue/laravel-wechat.
     *
     * (c) overtrue <i@overtrue.me>
     *
     * This source file is subject to the MIT license that is bundled
     * with this source code in the file LICENSE.
     */
    return [
        /*
         * 默认配置,将会合并到各模块中
         */
        'defaults' => [
            /*
             * 指定 API 调用返回结果的类型:array(default)/collection/object/raw/自定义类名
             */
            'response_type' => 'array',
            /*
             * 使用 Laravel 的缓存系统
             */
            'use_laravel_cache' => true,
            /*
             * 日志配置
             *
             * level: 日志级别,可选为:
             *                 debug/info/notice/warning/error/critical/alert/emergency
             * file:日志文件位置(绝对路径!!!),要求可写权限
             */
            'log' => [
                'level' => env('WECHAT_LOG_LEVEL', 'debug'),
                'file' => env('WECHAT_LOG_FILE', storage_path('logs/wechat.log')),
            ],
        ],
        /*
         * 路由配置
         */
        'route' => [
            /*
             * 开放平台第三方平台路由配置
             */
            // 'open_platform' => [
            //     'uri' => 'serve',
            //     'action' => Overtrue\LaravelWeChat\Controllers\OpenPlatformController::class,
            //     'attributes' => [
            //         'prefix' => 'open-platform',
            //         'middleware' => null,
            //     ],
            // ],
        ],
        /*
         * 公众号
         */
        'official_account' => [
            'default' => [
                'app_id' => env('WECHAT_OFFICIAL_ACCOUNT_APPID', 'wxfab5781c50794b96'),         // AppID
                'secret' => env('WECHAT_OFFICIAL_ACCOUNT_SECRET', 'e627eb355d2ca4483d590402292bccfd'),    // AppSecret
                'token' => env('WECHAT_OFFICIAL_ACCOUNT_TOKEN', 'aschem2020'),           // Token
                'aes_key' => env('WECHAT_OFFICIAL_ACCOUNT_AES_KEY', 'V9DLLG5Z8VebIKCmpVXPHOoWhC84YTQFhOuROtzgo21'),                 // EncodingAESKey
                /*
                 * OAuth 配置
                 *
                 * scopes:公众平台(snsapi_userinfo / snsapi_base),开放平台:snsapi_login
                 * callback:OAuth授权完成后的回调页地址(如果使用中间件,则随便填写。。。)
                 */
                 'oauth' => [
                     'scopes'   => array_map('trim', explode(',', env('WECHAT_OFFICIAL_ACCOUNT_OAUTH_SCOPES', 'snsapi_userinfo'))),
                     'callback' => env('WECHAT_OFFICIAL_ACCOUNT_OAUTH_CALLBACK', '/wechat/callback'),
                 ],
            ],
        ],
        /*
         * 开放平台第三方平台
         */
        // 'open_platform' => [
        //     'default' => [
        //         'app_id'  => env('WECHAT_OPEN_PLATFORM_APPID', ''),
        //         'secret'  => env('WECHAT_OPEN_PLATFORM_SECRET', ''),
        //         'token'   => env('WECHAT_OPEN_PLATFORM_TOKEN', ''),
        //         'aes_key' => env('WECHAT_OPEN_PLATFORM_AES_KEY', ''),
        //     ],
        // ],
        /*
         * 小程序
         */
        // 'mini_program' => [
        //     'default' => [
        //         'app_id'  => env('WECHAT_MINI_PROGRAM_APPID', ''),
        //         'secret'  => env('WECHAT_MINI_PROGRAM_SECRET', ''),
        //         'token'   => env('WECHAT_MINI_PROGRAM_TOKEN', ''),
        //         'aes_key' => env('WECHAT_MINI_PROGRAM_AES_KEY', ''),
        //     ],
        // ],
        /*
         * 微信支付
         */
        // 'payment' => [
        //     'default' => [
        //         'sandbox'            => env('WECHAT_PAYMENT_SANDBOX', false),
        //         'app_id'             => env('WECHAT_PAYMENT_APPID', ''),
        //         'mch_id'             => env('WECHAT_PAYMENT_MCH_ID', 'your-mch-id'),
        //         'key'                => env('WECHAT_PAYMENT_KEY', 'key-for-signature'),
        //         'cert_path'          => env('WECHAT_PAYMENT_CERT_PATH', 'path/to/cert/apiclient_cert.pem'),    // XXX: 绝对路径!!!!
        //         'key_path'           => env('WECHAT_PAYMENT_KEY_PATH', 'path/to/cert/apiclient_key.pem'),      // XXX: 绝对路径!!!!
        //         'notify_url'         => 'http://example.com/payments/wechat-notify',                           // 默认支付结果通知地址
        //     ],
        //     // ...
        // ],
        /*
         * 企业微信
         */
        // 'work' => [
        //     'default' => [
        //         'corp_id' => 'xxxxxxxxxxxxxxxxx',
        //         'agent_id' => 100020,
        //         'secret'   => env('WECHAT_WORK_AGENT_CONTACTS_SECRET', ''),
        //          //...
        //      ],
        // ],
    ];

二、wechatController

<?php    
    namespace App\Http\Controllers\M;
    use App\Library\Common;
    use App\Models\Member\MemberConnect;
    use App\Services\Wechat\MenuService;
    use App\Services\Wechat\MessageService;
    use App\Services\Wechat\UserService;
    use Illuminate\Http\Request;
    use App\Http\Controllers\Controller;
    use Illuminate\Support\Facades\Auth;
    use Illuminate\Support\Facades\Log;
    class WeChatController extends Controller
    {
        //
         /**
          * 处理微信的请求消息
          *
          * @return string
          */
        /* public function serve()
         {
              Log::info('request arrived.'); # 注意:Log 为 Laravel 组件,所以它记的日志去 Laravel 日志看,而不是 EasyWeChat 日志
              $app = app('wechat.official_account');
              $app->server->push(function($message){
                   return "欢迎关注 一览商城!";
              });
              return $app->server->serve();
         }*/
         public function serve(MessageService $messageService)
         {
              Log::info('request arrived.'); # 注意:Log 为 Laravel 组件,所以它记的日志去 Laravel 日志看,而不是 EasyWeChat 日志
              $app = app('wechat.official_account');
              $app->server->push(function($message) use($messageService){
                   return $messageService->index($message);
              });
              return $app->server->serve();
         }
         /**
          * 发起授权
          * @return mixed
          */
         public function oauth(){
              Log::info('start', ['oauth']);
              $app = app('wechat.official_account');
              return $app->oauth->scopes(['snsapi_userinfo'])->redirect();
         }
         /**
          * 授权回调
          * @return mixed
          */
         public function callback(){
              Log::info('start', ['oauth_callback']);
              $app = app('wechat.official_account');
              // 获取 OAuth 授权结果用户信息
              $user = $app->oauth->user();
              if(!$user){
                   Log::info('oauth_callback_user_error', ['none user']);
              }
              //Log::info('oauth_callback_user', [$user]);
              $openid = $user->getId();
              $UserService = new UserService();
              $user_info =$UserService->getUserInfo($openid);
              //Log::info('user_info', $user_info);
              //查询openid 有没有绑定 member
              $memberConnect = MemberConnect::where('openid', '=', $openid)->first();
              $member_id = 0;
              if(!$memberConnect){
                  //没保存先保存memberConnect
                  Common::createMemberConnect($user_info, 3);
              }else{
                   $member_id = $memberConnect->member_id;
              }
              if($member_id > 0){
                 //openid 已经跟会员member绑定,则默认登录
                   Auth::guard('member')->loginUsingId($member_id);
                   Log::info('wechat login email', [auth('member')->user()->email]);
                   return redirect(route('m.member.index'));
              }
              if($member_id ==0 ){
                 //openid还没跟会员member绑定,提醒用户去设置绑定
                   return redirect(route('m.bind_account', array('openid'=>$openid)));
              }
         }
         /**
          * 获取openid
          * @param Request $request
          * @return array
          */
         public function getOpenid(Request $request){
             /* $member_id = Cache::get($request->get('access_token'));
              if($member_id && Cache::has('wx_openid_'.$member_id)){
                   $wx_Info = Cache::get('wx_openid_'.$member_id);
                   return Y::success('yes',$wx_Info);
              }elseif($member_id && !Cache::has('wx_openid_'.$member_id)){
                   return Y::error('no');
              }else{
                   return ['code'=>3,'msg'=>'非法操作'];
              }*/
              return 'open_id';
         }
         public function wxMenu(Request $request,MenuService $menuService){
              $buttons = [
                   [
                        "name" => "我要采购",
                        "sub_button" => [
                             [
                                  "type" => "view",
                                  "name" => "发布采购",
                                  "url"  => "http://m.bychem.com/inquiry/add"
                             ],
                             [
                                  "type" => "view",
                                  "name" => "采购管理",
                                  "url"  => "http://m.bychem.com/inquiry/lists?type=quote"
                             ],
                             [
                                  "type" => "view",
                                  "name" => "采购订单",
                                  "url"  => "http://m.bychem.com/order/lists?type=pay"
                             ],
                        ],
                   ],
                   [
                        "name" => "我要销售",
                        "sub_button" => [
                             [
                                  "type" => "view",
                                  "name" => "发布产品",
                                  "url"  => "http://m.bychem.com/sale/goods_add"
                             ],
                             [
                                  "type" => "view",
                                  "name" => "产品管理",
                                  "url"  => "http://m.bychem.com/sale/goods_list"
                             ],
                             [
                                  "type" => "view",
                                  "name" => "询盘管理",
                                  "url"  => "http://m.bychem.com/sale/lists"
                             ],
                             [
                                  "type" => "view",
                                  "name" => "销售订单",
                                  "url"  => "http://m.bychem.com/sale/order"
                             ],
                        ],
                   ],
                   [
                        "name" => "会员中心",
                        "sub_button" => [
                             [
                                  "type" => "view",
                                  "name" => "注册/登录",
                                  "url"  => "http://m.bychem.com/users/sign_in"
                             ],
                             [
                                  "type" => "view",
                                  "name" => "会员中心",
                                  "url"  => "http://m.bychem.com/member/index"
                             ],
                             [
                                 "type" => "click",
                                 "name" => "联系客服",
                                 "key" => "CONTACT_KEFU"
                            ],
                        ],
                   ],
              ];
              return $menuService->index($request,$buttons);
         }
    }

三、MessageService

<?php    
    /**
     * Created by PhpStorm.
     * User: Lenovo
     * Date: 26/4/2020
     * Time: 上午10:50
     */
    namespace App\Services\Wechat;
    use App\Models\Member\MemberConnect;
    use EasyWeChat\Kernel\Messages\Text;
    use Illuminate\Support\Facades\Log;
    class MessageService
    {
         protected $UserService;
         public function __construct(UserService $UserService)
         {
              $this->UserService = $UserService;
         }
         public function index($message){
              $MsgType = $message['MsgType'];
              try{
                   if(method_exists($this,$MsgType)){
                        return $this->$MsgType($message);
                        exit();
                   }
                   return $this->otherType($message);
              }catch (\Exception $e){
                   return 'Sorry,系统异常!';
              }
         }
         /**
          * 公众号事件
          * @param $message
          * @return string
          */
         public function event($message){
              //关注公众号
              if($message['Event']=='subscribe'){
                   $userInfo = $this->UserService->getUserInfo($message['FromUserName']);
                   $app = app('wechat.official_account');
                   Log::info("=======subscribe userinfo=====");
                   Log::info($userInfo);
                   //保存用户信息
                   if($userInfo['openid']){
                        $memberConnect = MemberConnect::where('type','=',3)->where('openid','=',$userInfo['openid'])->first();
                        if(!$memberConnect){
                             MemberConnect::insert([
                                  'member_id'=>0,
                                  'type'=>3,
                                  'openid'=>$userInfo['openid'],
                                  'nickname'=>$userInfo['nickname'],
                                  'headimgurl'=>$userInfo['headimgurl'],
                                  'sex'=>$userInfo['sex'],
                                  'country'=>$userInfo['country'],
                                  'province'=>$userInfo['province'],
                                  'city'=>$userInfo['city'],
                                  'created_at'=>date('Y-m-d H:i:s', time()),
                             ]);
                        }
                   }
                   $msg1= $userInfo['nickname'].",欢迎您关注**商城!".PHP_EOL.PHP_EOL
                        .'点开底部三个按钮可操作更多!'.PHP_EOL
                        .'→<a href="http://m.bychem.com/inquiry/index">采购中心</a>:在线询单、采购管理、订单管理等,您都可以在这里进行,无比方便快捷!'.PHP_EOL
                        .'→<a href="http://m.bychem.com/sale/index">销售中心</a>:发布产品、产品管理、询盘管理、销售订单等,更多订单不容错过!'.PHP_EOL
                        .'→<a href="http://m.bychem.com/member/index">会员中心</a>:注册、登录、联系客服,贴心维护,让您毫无后顾之忧!'.PHP_EOL.PHP_EOL
                        .'更多详情请您登陆官网:'.PHP_EOL
                        .'www.bychem.com'  ;
                   $text1=new Text($msg1);
                   $app->customer_service->message($text1)->to($userInfo['openid'])->send();
                   return 'success';
              }
              //点击联系客服
              elseif($message['Event']=='CLICK'){
                   if($message['EventKey']=='CONTACT_KEFU'){
                        return '欢迎联系**商城客服!您可以在文字输入框内直接向客服发起询问,也可任选以下任一联系方式联系客服!祝您在一览商城获得满意的体验!'.PHP_EOL
                        .'客服电话:17068835637'.PHP_EOL
                        .'客服QQ:4850381607';
                   }
              }
         }
    }

四、MemberConnect表结构

/*    
     Navicat Premium Data Transfer
     Source Server         : buysellchem
     Source Server Type    : MySQL
     Source Server Version : 50729
     Source Host           : 106.15.38.61:3308
     Source Schema         : whmall
     Target Server Type    : MySQL
     Target Server Version : 50729
     File Encoding         : 65001
     Date: 26/04/2020 15:36:01
    */
    SET NAMES utf8mb4;
    SET FOREIGN_KEY_CHECKS = 0;
    -- ----------------------------
    -- Table structure for c_member_connects
    -- ----------------------------
    DROP TABLE IF EXISTS `c_member_connects`;
    CREATE TABLE `c_member_connects`  (
      `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
      `member_id` int(10) UNSIGNED NOT NULL DEFAULT 0,
      `type` tinyint(2) NOT NULL DEFAULT 1 COMMENT '1.qq登录,2.微信登录,3公众号',
      `openid` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL COMMENT '第三方登录id',
      `nickname` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL COMMENT '第三方昵称',
      `sex` tinyint(4) NULL DEFAULT 0 COMMENT '性别 1男',
      `headimgurl` varchar(250) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL COMMENT '头像',
      `country` varchar(50) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT '' COMMENT '国家',
      `province` varchar(50) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT '' COMMENT '省份',
      `city` varchar(50) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT '' COMMENT '城市',
      `created_at` timestamp(0) NULL DEFAULT NULL,
      `updated_at` timestamp(0) NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP(0),
      PRIMARY KEY (`id`) USING BTREE,
      UNIQUE INDEX `unq_openid`(`openid`) USING BTREE
    ) ENGINE = MyISAM AUTO_INCREMENT = 4 CHARACTER SET = utf8 COLLATE = utf8_bin COMMENT = '用户公众号,微信,qq 关联信息表' ROW_FORMAT = Dynamic;
    SET FOREIGN_KEY_CHECKS = 1;