Laravel front-end and back-end separate access to Wechat authorization, combined with laravel-wechat


1. Before you start, please read the Wechat Developer Document carefully.
There are several steps in the document:

  • 1. Request authorization through appId and routes requiring jumps
  • 2. Code returned from jump routing after authorizationNote:The front end only needs to know these two steps.
  • 3. Obtain access_token according to code
  • 4. Obtain user information according to access_token (snsapi_userinfo authorization)

2. The front end initiates authorization requests. This step requires a front-end patchwork routing and jumps pages to the patchwork routing with routing rules such as:Https:// public appId number&redirect_uri=your callback routing&response_type=code&scope=the way you choose&state=STATE#wechat_redirect
notesAuthorization options can be snsapi_userinfo or snsapi_base, see the documentation for differences

The authorization page after the jump is as follows (developer tool effect)

Laravel front-end and back-end separate access to Wechat authorization, combined with laravel-wechat

3. After clicking on the consent, the code will be returned according to your previously patched callback routing, as follows:


4. Pass the code in the route directly to the back end, let the back end do a series of logical processing to obtain user information.
Note:The following is the processing method in laravel middleware. Session is only used for this request. It can also put the user’s message in request to controller for logical processing, depending on personal preferences.

public function handle($request, Closure $next, $scopes = null)
         $wechatCacheKey = 'wechat.oauth_user.default';
            if (config("qa.mock_user") == 1){
                $user = new SocialiteUser(config('wechat.mock_user'));
            } else {
                $code = $request->get("code", "");
                if ($code === ""){
                    $appId = $this->config["app_id"];
                    Return Response:: toJson (["aid"=> $appId]), "Please retrieve the authorized CODE! "(10006);
                // Start pulling user information
                $app = Factory::officialAccount($this->config);
                $user = $app->oauth->user();
            session([$wechatCacheKey => $user]);
        return $next($request);

Note:This example just writes the authorization logic, token correlation validation I have removed.


1. The Vue routing splices the code between URL and #, such aswww.****.com/?code=XXXXX/#/indexThis code needs to be handled separately