The article directories

    • Environment to prepare
      • 1. Apply for an official test account
      • 2. Prepare and configure extranet services
      • 3. Common development tools and websites
    • Quick start
      • Rely on the import
      • The configuration file
      • Service Access Authentication
    • Commonly used functions
      • Get a list of concerned users
      • Obtaining User information
      • Wechat web page authorization
      • Updated the user remarks
      • Create a custom menu
      • Delete a custom menu
      • Get custom menus
      • Other features
    • conclusion

Environment to prepare

1. Apply for an official test account

Address: mp.weixin.qq.com/debug/cgi-b…

The application and authentication process is slow and tedious. You can experience and test all advanced functions of wechat official account in the test account.

Direct wechat scan can apply for a public test account, very convenient and fast.

2. Prepare and configure extranet services

Configuration:

Note: THE URL configuration and the mapping in RequestMapping in the code.

Service interface development:

Used to validate service access and interface callbacks.

See the quick Start – Service Access Authentication section

3. Common development tools and websites

  • Official website document
  • Wechat public platform interface debugging tool
  • Web Developer Tools
  • Test Account Application
  • Official wechat document

Quick start

Use WxJava to rapid development, it is wechat development Java SDK, support wechat payment, open platform, public number, enterprise number/enterprise wechat, small programs and other back-end development.

  • Github:github.com/Wechat-Grou…
  • Gitee:gitee.com/binary/weix…

Rely on the import

The Spring the Boot:

<dependency>
  <groupId>com.github.binarywang</groupId>
  <artifactId>weixin-java-mp</artifactId>
  <version>4.0.0</version>
</dependency>
Copy the code

Spring the Boot:

<dependency>
   <groupId>com.github.binarywang</groupId>
   <artifactId>wx-java-mp-spring-boot-starter</artifactId>
   <version>4.0.0</version>
</dependency>
Copy the code
  • Wechat applets:weixin-java-miniapp
  • Wechat Pay:weixin-java-pay
  • Wechat Open Platform:weixin-java-open
  • Public account (including subscription account and service account) :weixin-java-mp
  • Enterprise Id/Wechat account:weixin-java-cp

The configuration file

# Public id configuration (required)
wx.mp.appId = appId
wx.mp.secret = @secret
wx.mp.token = @token
wx.mp.aesKey = @aesKey
Storage configuration Redis (optional)
wx.mp.config-storage.type = Jedis                     # 配置类型: Memory(默认), Jedis, RedisTemplate
wx.mp.config-storage.key-prefix = Wx # Redis prefix configuration: wx(default)
wx.mp.config-storage.redis.host = 127.0.0.1
wx.mp.config-storage.redis.port = 6379
The sentinel configuration is preferred when both stand-alone and sentinel exist
# wx. Mp. Config - storage. Redis. Sentinel - ips = 127.0.0.1:16379127.00 0.1:26379
#wx.mp.config-storage.redis.sentinel-name=mymaster
# HTTP client configuration
wx.mp.config-storage.http-client-type=HTTP client types: httpClient (default), OkHttp, JoddHttp
wx.mp.config-storage.http-proxy-host=
wx.mp.config-storage.http-proxy-port=
wx.mp.config-storage.http-proxy-username=
wx.mp.config-storage.http-proxy-password=
Public id host
#wx.mp.hosts.api-host=http://proxy.com/
#wx.mp.hosts.open-host=http://proxy.com/
#wx.mp.hosts.mp-host=http://proxy.com/
Copy the code

Service Access Authentication

@API (tags = "wechat official account ")
@ApiSupport(order = 4)
@RequestMapping("/wx")
@RestController
@Slf4j
public class WxController {
    @Autowired
    WxMpService wxMpService;

    /** * The url is set to: http://ip:port/wx * If you cannot receive the call from wechat service, open this interface larger, do not limit GET */
    @GetMapping
    @ApiOperationSupport(order = 1)
    @apiOperation (value = "service authentication ")
    public String transfer(String signature, String timestamp, String nonce, String echostr) {
        log.info(Received authentication message from wechat server: signature: {}, TIMESTAMP: {}, nonce: {}, echostr: {}", signature, timestamp, nonce
                , echostr);
        if(! wxMpService.checkSignature(timestamp, nonce, signature)) { log.error("Message is illegal.");
            return "error";
        }
        return echostr;
    }
Copy the code

Note that the interface address here corresponds to the URL configured on the wechat platform above.

Service Access Authentication Flowchart:

It’s a good connection at this point.

Commonly used functions

Get a list of concerned users

String nextOpenid = null;// Optional, the first pull OPENID, null is pulled from scratch
WxMpUserList wxMpUserList = wxMpService.getUserService().userList(nextOpenid);
Copy the code

Results:

{
    "total": 1."count": 1."openids": [
      "xxxx"]."nextOpenid": "xxxx"
  }
Copy the code

Obtaining User information

After message interaction between the follower and the public account, the public account can obtain the follower’s OpenID (encrypted wechat signal, and each user’s OpenID of each public account is unique. For different public accounts, the openID of the same user is different. Through this interface, public accounts can obtain user basic information according to OpenID, including nickname, profile picture, gender, city, language and following time.

Please note that if developers have the need to unify user accounts in multiple public accounts or between public accounts and mobile applications, they need to go to the wechat open platform (open.weixin.qq.com) to bind the public account before using the UnionID mechanism to meet the above requirements.

To obtain user information in other scenarios, refer to the authorization section of wechat web page

String lang = "zh_CN"; // The language openId can be derived from the following user list interface or fromuser, where users send messages
WxMpUser user = wxMpService.getUserService().userInfo(openId, lang);
Copy the code

Results:

 {
    "subscribe": true."openId": "xxx"."nickname": "laker"."sexDesc": "Male"."sex": 1."language": "zh_CN"."city": Hefei ""."province": "Anhui province"."country": "China"."headImgUrl": "http://xxx"."subscribeTime": 1618311163."unionId": null."remark": ""."groupId": 0."tagIds": []."privileges": null."subscribeScene": "ADD_SCENE_QR_CODE"."qrScene": "0"."qrSceneStr": ""
  }
Copy the code

Wechat web page authorization

Realize third-party wechat login function.

If a user accesses a third-party web page in the wechat client, the public account can obtain the user’s basic information through the wechat web page authorization mechanism, so as to realize the business logic.

Address: document developers.weixin.qq.com/doc/offiacc…

1. Set the webpage authorization callback domain name

Before the wechat public account requests the user’s webpage authorization, the developer needs to modify the authorization callback domain name in the configuration option of “development – interface permission – Webpage service – Webpage account – Webpage authorization to obtain the user’s basic information” in the official website of the public platform. Please note that this is the domain name (a string), not the URL, so do not include protocol headers such as http:// (enter: www.laker.com).

Matters needing attention:

  • The sandbox (test) callback address supports the domain name and IP address. The official public callback address supports only the domain name and the combination of letters, digits, and hyphens (-). The domain name must be verified by ICP.
  • Test number: find web page authorization to get basic user information > Modify > Set domain name
  • Service number: Go to Development > Interface Rights > Web page Rights to obtain basic user information >> Click Modify > Set Domain name
  • Do not add protocol headers such as http:// to the domain name

2. Wechat webpage authorization – Sequence diagram of process

3. Construct a web page authorization URL

First, construct a web page authorization URL, and then form a hyperlink for users to click, for example, build a custom menu jump URL button type (VIEW).

WxMpService wxMpService = ... ; String url = ... ; wxMpService.getOauth2Service().buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_USERINFO,null)
Copy the code

4. Obtain basic user information

When the user agrees to authorize, the url will be called back and the authorization code will be transmitted. Then, the code will be used to obtain access token, which also contains the user’s OpenID and other information.

WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxMpService.getOAuth2Service().getAccessToken(code);
WxMpUser wxMpUser = wxMpService.getOAuth2Service().getUserInfo(wxMpOAuth2AccessToken, null);
Copy the code

Updated the user remarks

wxMpService.getUserService().userUpdateRemark(openid, "Test Note Name");
Copy the code

Create a custom menu

Including new and modify, modify is equivalent to overwrite the previous menu.

WxMenu wxMenu = new WxMenu();
// Set the menu
wxMpService.getMenuService().menuCreate(wxMenu);
Copy the code

Delete a custom menu

wxMpService.getMenuService().menuDelete();
Copy the code

Get custom menus

WxMenu wxMenu = wxMpService.getMenuService().menuGet();
Copy the code

Other features

Check it out on the Wiki page

conclusion

Overall, the integration is still relatively smooth, but there are a few points that should be emphasized:

  1. Environment preparation is very important, many articles are not clear, do not know what to prepare at the beginning, here see the need for an external network can access the service and a public account, the public account can directly use the test account.
  2. You can go to Baidu for Internet servicesIntranet throughThere are a lot of free ones that you can just use.
  3. Configure the service interface authentication URL, be sure to be specific to our interface.
  4. When entering the domain name for web page authorization, do not add the protocol header such as http://www.xxx.comCan.

Reference:

🍎QQ group [837324215] 🍎 pay attention to my public number [Java Factory interview officer], learn together 🍎🍎🍎 🍎 personal vx [Lakernote]