作者 chencheng

0529-test-1

... ... @@ -35,7 +35,57 @@ class Wechat extends Api
}catch(\Exception $e){
$this->error($e->getMessage());
}
$this->success('活动获取成功', $config);
$this->success('配置获取成功', json_decode($config,true));
}
/*
服务器跳转授权code测试
*/
public function test_code(){
$code = request()->param('code');
if(!empty($code)){
//跳转官方
$APPID = config('site.appid');
$REDIRECT_URI = 'https://coupon.xp.yn.cn/index.php/api/v1/Wechat/test_code';
$SCOPE = 'snsapi_base';
$redirect = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$APPID&redirect_uri=$REDIRECT_URI&response_type=code&scope=$SCOPE&state=STATE#wechat_redirect";
}else{
//解析code
$app = WehcatModule::getInstance()->initWechat();
$user = $app->oauth->user();
var_dump(json_encode($user));
// $user 可以用的方法:
// $user->getId(); // 对应微信的 OPENID
// $user->getNickname(); // 对应微信的 nickname
// $user->getName(); // 对应微信的 nickname
// $user->getAvatar(); // 头像网址
// $user->getOriginal(); // 原始API返回的结果
// $user->getToken(); // access_token, 比如用于地址共享时使用
}
}
/*
2.网页授权
2.1前端打开则跳转到授权页 由前端自行配置
appid
redirect_uri前端的路由首位,
scope=snsapi_base 静默只能获取openid,
=snsapi_userinfo (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且, 即使在未关注的情况下,只要用户授权,也能获取其信息 )
https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
2.2 由微信回跳后,获取code 和 state 参数,由前端post code给后台
*/
public function get_user_info_by_code (){
try{
$app = WehcatModule::getInstance()->initWechat();
$oauth = $app->oauth;
// 获取 OAuth 授权结果用户信息
$user = $oauth->user();
}catch(\Exception $e){
$this->error($e->getMessage());
}
$this->success('配置获取成功', json_decode($config,true));
}
}
... ...
... ... @@ -6,6 +6,9 @@ use EasyWeChat\Factory;
/**
* easyWechat 插件
使用
$app = app\server\Wechat::getInstance()->initWechat();
$app 为 easyWechat的对象 根据官网接口调用或二开
*/
class Wechat {
static public $app = null;
... ... @@ -15,8 +18,12 @@ class Wechat {
static private $inc = null;
function __construct(){
self::$appid= config("site.appid");
self::$appsecret= config("site.appsecret");
//self::$appid= config("site.appid");
//self::$appsecret= config("site.appsecret");
//测试公众号
self::$appid= 'wxb9b259e7a17bda27';
self::$appsecret= '2af20d18bf969d8a26691dfd54cc6380';
//easyWechat配置
self::$config = [
'app_id' => self::$appid,
'secret' => self::$appsecret,
... ... @@ -52,6 +59,7 @@ class Wechat {
];
}
//静态函数
static public function getInstance(){
if(self::$inc == null){
self::$inc = new self();
... ... @@ -59,8 +67,9 @@ class Wechat {
return self::$inc;
}
static public function initWechat(){
//初始化 easywechat app
static public function initWechat(){
self::$app = Factory::officialAccount(self::$config);
return self::$app;
}
... ...