search
HomePHP FrameworkThinkPHPIntroducing thinkphp5.1 easywechat4 WeChat third-party open platform

Todaythinkphp frameworkThe theme brought to you by the column is "thinkphp5.1 easywechat4 WeChat third-party open platform". Let's introduce it in detail~

thinkphp5.1 easywechat4 WeChat third-party open platform

Requirement description

  1. The current mall (uid identification) authorizes the third-party development platform.
  2. Web page authorization successful Then jump to another mall project link and bring the current WeChat user information and WeChat initialization verification signature.

Third-party platform authorization

Install easywechat4
$ composer require overtrue/wechat:~4.0 -vvv
Quote
use EasyWeChat\Factory;
Create a jump to WeChat scan QR code authorization page
/**
 * 开发平台授权跳转
 *
 * @return void
 */
public function accessView(){
    // 
    $uid = Request()->route('uid' , 0);
    $url = 'http://qgcloud.capsui.com/public/index/wxopen/config?uid=' . $uid;
    $this->assign('url' , $url);
    return $this->fetch();
}
Jump method (why don’t I write the previous method? Because WeChat requires the same An address)
/**
 * 开发平台跳转授权扫码页
 *
 * @return void
 */
public function config(){
    $uid = Request()->get('uid' , 0);
    $config = [
        'app_id'   => '开放平台第三方平台 APPID',
        'secret'   => '开放平台第三方平台 Secret',
        'token'    => '开放平台第三方平台 Token',
        'aes_key'  => '开放平台第三方平台 AES Key'
    ];
    $openPlatform = Factory::openPlatform($config);
    
    $url = $openPlatform->getPreAuthorizationUrl('http://qgcloud.capsui.com/public/index/wxopen/wxcallback?uid=' . $uid);

    $this->redirect($url);
}
Authorization callback (note: the first callback after scanning the code to confirm authorization will not take the uid parameter,)
引入 
use EasyWeChat\OpenPlatform\Server\Guard;
/**
 * 开发平台授权回调
 *
 * @return void
 */
public function wxcallback(){
    // 这个表是记录授权成功的
    //$Wxpublic   = new Wxpublic;
    // 这个表是记录授权成功后传过来所属uid商城绑定appid
    //$ShopConfig = new ShopConfig;

    $get = Request()->param();
    
    $config = [
        'app_id'   => '开放平台第三方平台 APPID',
        'secret'   => '开放平台第三方平台 Secret',
        'token'    => '开放平台第三方平台 Token',
        'aes_key'  => '开放平台第三方平台 AES Key'
    ];
    $openPlatform = Factory::openPlatform($config);
    $server       = $openPlatform->server;

    
    // 处理授权成功事件-第一次回调
    // 闭包方法!里面调用外面的方法请在use里面填写
    $server->push(function ($message) use ($openPlatform /*, $Wxpublic*/) {
        
        $authCode = $message['AuthorizationCode'];
        $res      = $openPlatform->handleAuthorize($authCode);

        if($res['authorization_info']['authorizer_refresh_token']){
            //授权成功记录到数据库
            //$Wxpublic->insert(['appid' => $res['authorization_info']['authorizer_appid'] , 'createtime' => time()]);
        }

    }, Guard::EVENT_AUTHORIZED);

    // 处理授权取消事件-第一次回调
    // 闭包方法!里面调用外面的方法请在use里面填写
    $server->push(function ($message) use(/*$Wxpublic , $ShopConfig*/) {
        //处理数据库逻辑
        //$Wxpublic::appid($message['AppId'])->delete();
        //$ShopConfig::appid($message['AppId'])->update(['token' => '']);
    }, Guard::EVENT_UNAUTHORIZED);
    
    // 第二次回调会带一个授权code和自定义参数商城id(uid)
    if(isset($get['auth_code']) && isset($get['uid'])){
        
        $res      = $openPlatform->handleAuthorize($get['auth_code']);
        $appid    = $res['authorization_info']['authorizer_appid'];
        //数据库逻辑
        //$isConfig = $Wxpublic::appid($appid)->count();
        
        //if($isConfig){
        //$add = $ShopConfig->where('uid' , $get['uid'])->update(['token' => $appid]);
        //}
    }

    return $server->serve();
}

Third-party platform web page authorization & WeChat JSSDK initialization signature generation

/**
 * 网页授权调起
 *
 * @return void
 */
public function htmlAccess(){
    $appid = Request()->get('appid' , 0);
    
    $config = [
        'app_id'   => '开放平台第三方平台 APPID',
        'secret'   => '开放平台第三方平台 Secret',
        'token'    => '开放平台第三方平台 Token',
        'aes_key'  => '开放平台第三方平台 AES Key'
    ];
    $openPlatform = Factory::openPlatform($config);
    $data         = $openPlatform->getAuthorizer($appid);
    $appid        = $data['authorization_info']['authorizer_appid'];
    $refreshToken = $data['authorization_info']['authorizer_refresh_token'];

    $officialAccount = $openPlatform->officialAccount($appid , $refreshToken);
    $oauth           = $officialAccount->oauth;
    
    // 回调授权地址
    $url      = "http://qgcloud.capsui.com/public/index/wxopen/callbackOpenid";
    $response = $officialAccount->oauth->scopes(['snsapi_userinfo'])->redirect($url)->send();

}
Web page authorization callback method
/**
 * 网页授权回调
 *
 * @return void
 */
public function callbackOpenid(){
    $appid = Request()->get('appid' , null);
    
    $config = [
        'app_id'   => '开放平台第三方平台 APPID',
        'secret'   => '开放平台第三方平台 Secret',
        'token'    => '开放平台第三方平台 Token',
        'aes_key'  => '开放平台第三方平台 AES Key'
    ];
    $openPlatform = Factory::openPlatform($config);
    $data         = $openPlatform->getAuthorizer($appid);
    
    $appid        = $data['authorization_info']['authorizer_appid'];
    $refreshToken = $data['authorization_info']['authorizer_refresh_token'];
    
    // 获取微信用户信息 如openid nickname等信息
    $officialAccount = $openPlatform->officialAccount($appid , $refreshToken);
    $oauth           = $officialAccount->oauth;
    $user            = $oauth->user();
    
    // 处理wxconfig初始化JSSDK
    $officialAccount->jssdk->setUrl('http://quguoshop.capsui.com/');
    $wxconfig = $officialAccount->jssdk->buildConfig(['chooseWXPay'], $debug = true, $beta = false, $json = true);

    $ShopConfig = new ShopConfig;
    $shopInfo   = $ShopConfig::appid($appid)->find();
    
    // 注意 这里我是带参数跳转到其他TP5项目里面再用缓存处理一下
    $url = 'http://quguoshop.capsui.com/public/wxoauthCallback?data=' . json_encode($user->toArray()) . '&token=' . $shopInfo['id'] . '&wxconfig=' . $wxconfig;
    $this->redirect($url);
}

《Related recommendations: The latest 10 thinkphp video tutorials

The above is the detailed content of Introducing thinkphp5.1 easywechat4 WeChat third-party open platform. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
What is the difference between think book and thinkpadWhat is the difference between think book and thinkpadMar 06, 2025 pm 02:16 PM

This article compares Lenovo's ThinkBook and ThinkPad laptop lines. ThinkPads prioritize durability and performance for professionals, while ThinkBooks offer a stylish, affordable option for everyday use. The key differences lie in build quality, p

How can I use ThinkPHP to build command-line applications?How can I use ThinkPHP to build command-line applications?Mar 12, 2025 pm 05:48 PM

This article demonstrates building command-line applications (CLIs) using ThinkPHP's CLI capabilities. It emphasizes best practices like modular design, dependency injection, and robust error handling, while highlighting common pitfalls such as insu

How to prevent SQL injection tutorialHow to prevent SQL injection tutorialMar 06, 2025 pm 02:10 PM

This article explains how to prevent SQL injection in ThinkPHP applications. It emphasizes using parameterized queries via ThinkPHP's query builder, avoiding direct SQL concatenation, and implementing robust input validation & sanitization. Ad

How to install the software developed by thinkphp How to install the tutorialHow to install the software developed by thinkphp How to install the tutorialMar 06, 2025 pm 02:09 PM

This article details ThinkPHP software installation, covering steps like downloading, extraction, database configuration, and permission verification. It addresses system requirements (PHP version, web server, database, extensions), common installat

How to deal with thinkphp vulnerability? How to deal with thinkphp vulnerabilityHow to deal with thinkphp vulnerability? How to deal with thinkphp vulnerabilityMar 06, 2025 pm 02:08 PM

This article addresses ThinkPHP vulnerabilities, emphasizing patching, prevention, and monitoring. It details handling specific vulnerabilities via updates, security patches, and code remediation. Proactive measures like secure configuration, input

What Are the Key Considerations for Using ThinkPHP in a Serverless Architecture?What Are the Key Considerations for Using ThinkPHP in a Serverless Architecture?Mar 18, 2025 pm 04:54 PM

The article discusses key considerations for using ThinkPHP in serverless architectures, focusing on performance optimization, stateless design, and security. It highlights benefits like cost efficiency and scalability, but also addresses challenges

How to fix thinkphp vulnerability How to deal with thinkphp vulnerabilityHow to fix thinkphp vulnerability How to deal with thinkphp vulnerabilityMar 06, 2025 pm 02:04 PM

This tutorial addresses common ThinkPHP vulnerabilities. It emphasizes regular updates, security scanners (RIPS, SonarQube, Snyk), manual code review, and penetration testing for identification and remediation. Preventative measures include secure

How to use thinkphp tutorialHow to use thinkphp tutorialMar 06, 2025 pm 02:11 PM

This article introduces ThinkPHP, a free, open-source PHP framework. It details ThinkPHP's MVC architecture, features (routing, database interaction), advantages (rapid development, ease of use), and disadvantages (potential over-engineering, commun

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.