微信开放平台搭建

背景

  公司有一个产品,需要用到微信授权登录及微信消息推送等功能。本来能够简单的使用公众号的接口将appid和appsecrect等信息写到配置文件里,但是作为一个产品化的东西,从体验等各方面来讲都不能那么的顺畅。于是打算对接微信开放平台。本文是基于Laravel的一次微信开放平台整合记录,如果能够帮到一些朋友,自然是非常高兴的事情。

平台账号申请

  网址是https://open.weixin.qq.com/  进入后选择第三方平台,点击创建第三方平台按钮。如下图。

填完基础的信息后。下一步,选择必须的服务,此处省略图,选择你要用到的服务就行了。下图是最后一步需要填写的相关参数信息。登录授权的发起页域名为业务系统部署域名;授权测试公众号列表是用于测试的公众号的原始id,用分号隔开;授权事件接收URL是用于接收component_verify_ticket等公众号授权信息的接口地址,此处先在laravel中写了个接口地址/notification/openPlatform;公众号消息校验Token随便填一个就可以了;解密Key填一个在代替公众号收发消息过程中使用。必须是长度为43位的字符串,只能是字母和数字;消息与事件URL这个厉害了,所有公众号的消息和事件到时候都会转发到这个接口里来的,我这边填/notification/openIndex/$APPID$,后面的$APPID$这个参数到时候会替换成对应公众号的appid,这里只是个占位符,当然路由里必须得有这个参数。如果是没有路由系统的一些框架,可能需要通过pathinfo的方式进行传递了,这里不允许使用?appid=1234这种方式进行传递;开发域名就是系统部署域名,一般小系统跟登录授权域名保持一致,分布式的可能会有多个服务器或者站点来部署;ip地址白名单就不用多说了,就是服务器的ip地址,除了这个ip,其他的都无法访问。

填完上述信息进行保存就OK了。到此整个申请开放平台的第一步过程就结束了。接下来我们就要取写程序,进行测试,腾讯有一套自动化测试系统,通过自动化测试系统才能够进行全网发布,下面要开始Coding了,会贴一些关键代码。

Coding

  编码前先到应用的详情中把AppId和AppSecret拿过来,找个地方先保存起来。

  编码这边用到了一个第三方微信类库,还是比较推荐使用的。叫EasyWechat,通过composer把它添加到项目中去。在config文件中先配置下appid和appsecret等信息。

'open_platform' => [
        'app_id'   => 'wxc9c43170xxxx791',
        'secret'   => '6d36b19b6xxxxxxxxxf531be47f6235a',
        'token'    => 'kftcvr1436942017',
        'aes_key'  => 'ZQnZsLxxxxxxxxxwmmBSTofPzauHBhCIgsVgLGVwncNA'
    ],

  

   先写几个路由。

Route::any('/notification/openPlatform','ServiceOpenPlatformController@notify')->name('notification.openPlatformNotify');    //微信通知,主要是component_verify_ticket等信息
Route::any('/notification/openIndex/{appid}','ServiceOpenPlatformController@index')->name('notification.openPlatformIndex');  //所有微信公众号消息入口,包括文本、图文、语音、地理位置等各种信息,这个具体实现就相当于做一个公众号平台了。
Route::any('/wxcallback','ServiceOpenPlatformController@wxcallback')->name('notification.openPlatformCallback');          //授权回调方法,用于保存appid和refresh_token
Route::any('/wxauth','ServiceOpenPlatformController@auth')->name('notification.openPlatformAuth');              //预授权页面
Route::any('/wxtest','ServiceOpenPlatformController@test')->name('notification.openPlatformTest');              //测试页

  编写notify方法。SDK 内部已实现缓存 component_veirfy_ticket,开发者无需另行处理该事件。使用 doctrine/cache 来完成缓存工作,它支持基本目前所有的缓存引擎。默认使用文件缓存,如果要用redis等其他缓存方式,比如多台服务器这种情况。请查阅easywechat官方文档缓存那部分。

use AppHttpControllersController;
use EasyWeChatCoreException;
use EasyWeChatFoundationApplication;
use EasyWeChatOpenPlatformGuard;
use IlluminateSupportFacadesDB;
use SymfonyComponentHttpFoundationResponse;

public function notify(){
        $options = ['open_platform' => config('wechat.open_platform')];
        $app = new Application($options);
        $openPlatform = $app->open_platform;

        $server = $openPlatform->server;

        $server->setMessageHandler(function($event) use($openPlatform){
            switch ($event->InfoType) {
                case Guard::EVENT_AUTHORIZED: // 授权成功
                    $res = $openPlatform->getAuthorizationInfo($event->AuthorizationCode);
                    //@TODO 此处需要检查res是否正常
                    //Save to DB
                    $appid = $res->authorization_info['authorizer_appid'];
                    $refresh_token = $res->authorization_info['authorizer_refresh_token'];
                    DB::table("wechat_platform")->where('app','hr')->update(['appid' => $appid,'refresh_token' => $refresh_token]);

                    break;
                case Guard::EVENT_UPDATE_AUTHORIZED:    // 更新授权
                    //
                    break;
                case Guard::EVENT_UNAUTHORIZED: // 取消授权
                    //
                    break;

            }
        });

        $response = $server->serve();
        return $response;
    }

  编写预授权页面。这里前端要写个页面,在页面中加上超链接,必须在同一个域名下。链接到auth方法。

                                    <a style="color: inherit" href="http://hr.hackcat.com/wxauth"><p>微信平台绑定</p></a>

这边会跳转到微信的授权页。弹出一个授权二维码,公众号账号的主人扫一下授权一下会跳回到下面的回调页面。

public function auth(){
        $options = ['open_platform' => config('wechat.open_platform')];
        $app = new Application($options);
        $openPlatform = $app->open_platform;
        $response = $openPlatform->pre_auth->redirect('http://hr.hackcat.com/wxcallback');
        return $response;
    }

 

  编写授权回调页面。这里主要是保存 authorizer_appid和authorizer_refresh_token信息,用于今后api的调用。

public function wxcallback(){
        $options = ['open_platform' => config('wechat.open_platform')];
        $app = new Application($options);
        $openPlatform = $app->open_platform;


        try{
            $res = $openPlatform->getAuthorizationInfo($authorizationCode = null);
            $appid = $res->authorization_info['authorizer_appid'];
            $refresh_token = $res->authorization_info['authorizer_refresh_token'];

            DB::table("wechat_platform")->where('app','hr')->update(['appid' => $appid,'refresh_token' => $refresh_token]);

            return 'Success';
        }catch (Exception $ex){
            abort(404,$ex->getMessage());
        }
    }
 public function test(){
        $options = ['open_platform' => config('wechat.open_platform')];
        $app = new Application($options);
        $openPlatform = $app->open_platform;
        $authInfo = DB::table("wechat_platform")->where('app','hr')->first();

        $app = $openPlatform->createAuthorizerApplication($authInfo->appid, $authInfo->refresh_token);
        $userService = $app->user;
        $user = $userService->get("oSQ2Ks_6ns0ahqKvzO_voIzbMdjI");
        dd($user);

    }

上面的是测试方法,用于测试保存的appid和refresh_token是否工作。

这一篇就到此为止吧,期间mac的chrome奔溃了N次,重复写了好几遍,都快怒了。

 PS: 这个系统由于用不到消息管理,所以去掉了权限的消息管理功能,全网发布的时候就不用写消息管理的测试了。如果有朋友遇到了全网发布时候测试问题,欢迎留言。

原文地址:https://www.cnblogs.com/hackcat/p/7089318.html