Wechat.php 3.0 KB
<?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 = 'wxb9b259e7a17bda27';
			$REDIRECT_URI = urlencode('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);
			header("Location:".$redirect);
			$response = $app->oauth->scopes(['snsapi_userinfo']) ->redirect(urlencode($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));
	}


}