Wechat.php
3.0 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
<?php
namespace app\api\controller\v1;
use app\server\Wechat as WehcatModule;
use app\common\controller\Api;
use think\Cache;
use think\Config;
use think\Db;
use think\Response;
use think\Validate;
/**
* 首页公共
*/
class Wechat extends Api
{
protected $noNeedLogin = ["*"];
protected $noNeedRight = '*';
public function _initialize()
{
parent::_initialize();
}
/*
1.前端获取jsjdk的配置
*/
public function get_jsjdk_config(){
try{
$app = WehcatModule::getInstance()->initWechat();
$APIs = ['updateAppMessageShareData','updateTimelineShareData','onMenuShareTimeline','onMenuShareAppMessage','onMenuShareQQ','onMenuShareWeibo','onMenuShareQZone','chooseWXPay'];
$config = $app->jssdk->buildConfig($APIs, true);
}catch(\Exception $e){
$this->error($e->getMessage());
}
$this->success('配置获取成功', json_decode($config,true));
}
/*
服务器跳转授权code测试
https://coupon.xp.yn.cn/index.php/api/v1/Wechat/test_code
*/
public function test_code(){
$code = request()->param('code');
$app = WehcatModule::getInstance()->initWechat();
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";
$curUrl = request()->url(true);
$response = $app->oauth->scopes(['snsapi_userinfo']) ->redirect($curUrl);
return $response;
}else{
//解析code
$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));
}
}