昨天上午突然想把自己公众号上的一些小应用移植到其他公众号,最好的方法肯定是第三方了。 然而easywechat4.0文档中是没有针对thinkphp的,在搞了一天尝试和改动之后,终于完成了第三方授权的开发。 当然,本篇同样是根据网友Nixus的那一片文章收到的启发,并做了一些小调整:https://www.easywechat.com/discussions/153 因为是才通过检测,到底对不对也只有上线了才知道。如果哪位大神能够在文末给出简洁操作的话,小人不胜感激!
1. 第三方平台授权
$openPlatform = Factory::openPlatform($config);
$server = $openPlatform->server;
$message = $server->getMessage();
switch ($message['InfoType']) {
case Guard::EVENT_AUTHORIZED:
// 处理授权成功事件
$server->push(function ($message) {
// ...
}, Guard::EVENT_AUTHORIZED);
break;
case Guard::EVENT_UPDATE_AUTHORIZED:
// 处理授权更新事件
$server->push(function ($message) {
// ...
}, Guard::EVENT_UPDATE_AUTHORIZED);
break;
case Guard::EVENT_UNAUTHORIZED:
// 处理授权取消事件
$server->push(function ($message) {
// ...
}, Guard::EVENT_UNAUTHORIZED);
break;
}
$server->serve()->send();
2. 第三方平台上线前的检查代码 // 1.准备所有需要配置的东西
$openPlatform = Factory::openPlatform($config);
$server = $openPlatform->server;
$msg = $server->getMessage();
// 2.获取公众号信息所需要的信息
$gh_id = $msg['ToUserName'];
$openid = $msg['FromUserName'];
$app = Db::name('op_app')->where('username', $gh_id)->find();
// 3.通过接口把公众号的所有信息搞下来
$authinfo = $openPlatform->getAuthorizer($app['appid'])['authorization_info'];
$authappid = $authinfo['authorizer_appid'];
$authtoken = $authinfo['authorizer_refresh_token'];
// 第三方测试用的
switch ($msg['MsgType']) {
case 'event':
$cuservice = $openPlatform->officialAccount($authappid, $authtoken)->customer_service;
$cuservice->message($msg['Event'] . 'from_callback')
->from($gh_id)
->to($openid)
->send();
case 'text':
$cuservice = $openPlatform->officialAccount($authappid, $authtoken)->customer_service;
$word = $msg['Content'];
if ($word == 'TESTCOMPONENT_MSG_TYPE_TEXT') {
$cuservice->message($word . '_callback')
->from($gh_id)
->to($openid)
->send();
} elseif (strpos($word, 'QUERY_AUTH_CODE') == 0) {
echo '';
$code = substr($word, 16);
$authorizerInfo = $openPlatform->handleAuthorize($code)['authorization_info'];
$cuservice = $openPlatform->officialAccount($authorizerInfo['authorizer_appid'], $authorizerInfo['authorizer_refresh_token']);
$cuservice->customer_service->message($code . "_from_api")
->from($gh_id)
->to($openid)
->send();
}
}