search
HomeBackend DevelopmentPHP TutorialHow to log in using WeChat on PHP website

How to log in using WeChat on PHP website

May 12, 2018 pm 04:04 PM
phpmethodLog in


Recently, the website development on the PC side requires WeChat authorized login. Considering that the mobile phone side has already gained a large number of WeChat user groups in the early stage, we are now thinking about integrating resources to meet the same needs. Data synchronization of WeChat users.

1. Development instructions

1. Concept distinction

Because you are exposed to the knowledge of WeChat development, you will inevitably be exposed to the use of OpenID and UnionID. The following is the official document of WeChat Introduction, please pay attention to the distinction:

  • After the follower interacts with the official account, the official account can obtain the follower’s OpenID (encrypted WeChat ID, each user The OpenID of each official account is unique. The OpenID of the same user is different for different official accounts). Official accounts can obtain basic user information based on OpenID through corresponding interfaces, including nickname, avatar, gender, city, language and time of attention.

  • Please note that if developers need to unify user accounts between multiple public accounts, or between public accounts and mobile applications, they need to go to the WeChat open platform (open.weixin. qq.com) After binding the official account, the UnionID mechanism can be used to meet the above needs.

To put it simply:

  • OpenID is the identification of an ordinary user and is unique to the current developer account. An OpenID corresponds to an official account.

  • UnionID is the user’s unified identification. For applications under a WeChat open platform account, the UnionID of the same user is unique.

2. Summary

has gone around this circle, that is to say, there is a difference between WeChat public account development and WeChat development platform development. If the same WeChat user logs in to a website using different platforms (such as PC, app, WeChat applet, etc.), the account needs to be bound, and the bound account cannot be distinguished by OpenID, but needs to be distinguished by UnionID.

3. Typical problems

Appendix A common design problem is mainly that the knowledge used before development is not comprehensive enough, which will have an impact on subsequent expansion. Of course, this is also a problem I encountered. I hope this can be a wake-up call for you.

2. WeChat Open Platform Operation

1. Brief Guide

According to the following needs, I chose "Website Application Development" Create and then apply for materials according to official instructions, which generally takes more than three days.
How to log in using WeChat on PHP website

After the application is created, it must also meet the requirements for obtaining interface permissions. Staff will proactively contact you, and it can usually be completed in one day.
How to log in using WeChat on PHP website

2. Official scene reference provided

How to log in using WeChat on PHP website

3. Bind public account/mini program

For To ensure that the UnionID corresponding to the WeChat user under the same development account is bound and used, the corresponding official account/service account needs to be bound in the list below. The document introduces that it generally must meet the WeChat payment function

How to log in using WeChat on PHP website

4. Authorization to obtain access_token sequence diagram

How to log in using WeChat on PHP website

3. Code implementation

In fact, the main time is spent on the early application operation above, but the actual code implementation is extremely simple. The following is my implementation method, please give me your feedback.

1. Public file configuration

It is customary to place the main configuration information in the configuration file, ‘\Application\Common\Conf\config.php’.

'WEIXIN_LOGIN' => array(        // 微信开放平台 使用微信帐号登录App或者网站 配置信息
        'OPEN_APPID' => 'wxbd961b2a6b7b2963', //应用 AppID
        'OPEN_APPSECRET' => 'e6xxxxxxxxxxxxxxxxxxxxe90',//应用 AppSecret
        'OPEN_CALLBACKURL' => 'http://www.52zhenmi.com/Home/Login/wxBack', //微信用户使用微信扫描二维码并且确认登录后,PC端跳转路径
    ),
2. Core code
public function wxIndex(){
        //--微信登录-----生成唯一随机串防CSRF攻击
        $state  = md5(uniqid(rand(), TRUE));        $_SESSION["wx_state"]    =   $state; //存到SESSION
        $callback = urlencode($this->callBackUrl);        'https://open.weixin.qq.com/connect/qrconnect?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect';        $wxurl = "https://open.weixin.qq.com/connect/qrconnect?appid="
                .$this->appID."&redirect_uri="
                .$callback."&response_type=code&scope=snsapi_login&state="
                .$state."#wechat_redirect";
        header("Location: $wxurl");
    }    public function wxBack(){
        if($_GET['state']!=$_SESSION["wx_state"]){            echo 'sorry,网络请求失败...';            exit("5001");
        }        $url='https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$this->appID.'&secret='.$this->appSecret.'&code='.$_GET['code'].'&grant_type=authorization_code';        $arr = curl_get_contents($url);        //得到 access_token 与 openid
        $url='https://api.weixin.qq.com/sns/userinfo?access_token='.$arr['access_token'].'&openid='.$arr['openid'].'&lang=zh_CN';        $user_info = curl_get_contents($url);        $this->dealWithWxLogin($user_info);
    }    /**
     * 根据微信授权用户的信息 进行下一步的梳理
     * @param $user_info
     */
    public function dealWithWxLogin($user_info){
        //TODO 数据处理
        var_dump($user_info);        die;
    }
3. Front-end display

According to the introduction of the official document, you can either directly access the authorized scanning interface or perform customized design. I guess I'm out of my mind, and the function of nested login and QR code has not been implemented for a long time, so I have to use the default jump here.

How to log in using WeChat on PHP website

The display effect is as follows:

How to log in using WeChat on PHP website

Page jump after successful scanning and login
How to log in using WeChat on PHP website

4. Summary

  • 1. According to the final implementation of the above function, the information of the logged-in user can be obtained, and the openID and UnionID can be stored in the database for later business Processing.

  • 2. My ability to explain below is limited. It is recommended to refer to the official development documents and the practical experience of Google seniors...

  • 3. I saw a good article online Article, recommended reference: Binding scheme for WeChat public account users and website users

Related recommendations:

Customize WeChat login code scanning style Solution

WeChat open platform development website application WeChat login introduction

How to quickly integrate WeChat login with PHP's laravel framework

The above is the detailed content of How to log in using WeChat on PHP website. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

PHP Email Security: Best Practices for Sending EmailsPHP Email Security: Best Practices for Sending EmailsMay 08, 2025 am 12:16 AM

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version