PHP code example of fmwww / passport-wechat-oauth-grant

1. Go to this page and download the library: Download fmwww/passport-wechat-oauth-grant library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

fmwww / passport-wechat-oauth-grant example snippets


Fmwww\PassportWechatOauthGrant\WechatOauthGrantServiceProvider::class,

return [
    /*
     * 微信app_id
     */
    'app_id' => env('WECHAT_OAUTH_GRANT_APP_ID', ''),
    /*
     * 微信app_secret
     */
    'app_secret' => env('WECHAT_OAUTH_GRANT_APP_SECRET', ''),
];

$http = new GuzzleHttp\Client;

$response = $http->post('http://your-app.com/oauth/token', [
    'form_params' => [
        'grant_type' => 'wechat_oauth',
        'client_id' => 'client-id',
        'client_secret' => 'client-secret',
        'code' => '001qJKS42a3r3N0wrDU42IHrS42qJKSN', #微信的授权code
        'scope' => '',
    ],
]);

return json_decode((string) $response->getBody(), true);

public function findForWechatOauth($tokens)
    {
        // 获取openid
        $openid = $tokens->openid;
        
        // 获取access_token
        $access_token = $tokens->access_token;
        
        // 获取expires_in
        $expires_in = $tokens->expires_in;
        
        // 获取refresh_token
        $refresh_token = $tokens->refresh_token;
        
        // 获取scope
        $scope = $tokens->scope;

        // 通过openid查找,如果这个方法没有定义,默认就是这样查找
        $user = $this->where('openid', $openid)->first();
        
        // 你也可以自己创建用户然后返回
        if (empty($user)) {
            $this->openid = $openid;
            $this->save();
        }
        // 返回用户
        return $user ?: $this;
    }