I. Preparation of wechat public account:

1. Register

Access the address: https://mp.weixin.qq.com/ sign up according to clew Note: this article sample use personal public, because public, no personal interface permissions, custom menu to development, the students do not register!


The information of applying public account is as follows, you can also scan the code to follow

This wechat public account is committed to AI, development, security, data, operation and maintenance in the direction of technology promotion and technology dissemination, looking forward to the dissemination of technology and knowledge promotion you join. Click to scan the QR code:

https://img.wuage.com/1.jpgimg.wuage.com

2. The configuration

Need to prepare their own server address, you can use Tencent Cloud Ali cloud JINGdong cloud and so on, no domain name with IP can also. On the development – Basic Settings page of the official website of the public platform, check the protocol to become a developer, click the “Modify Configuration” button, and fill in the server address (URL), Token and EncodingAESKey, where THE URL is the interface URL that the developer uses to receive wechat messages and events. The Token can be filled in at will by the developer and used to generate the signature (the Token is compared to the Token contained in the interface URL to verify security). EncodingAESKey is manually filled in or randomly generated by the developer and used as the message body encryption and decryption key.

Wechat public platformmp.weixin.qq.com

Configure basic development information as required, as follows:


3. The connection

After the server configuration is submitted, the wechat server sends a GET request to the entered server ADDRESS URL. The parameters of the GET request include Signature, TIMESTAMP, nonce and Echostr. The server program verifies the request by checking signature (see the verification method below). If you confirm that the GET request is from the wechat server, return echostr parameters to the wechat server for confirmation. The encryption/verification process is as follows, and the specific code implementation is as follows: 1) Lexicographical ordering of the token, TIMESTAMP and nonce parameters 2) Splicing the three parameter strings into a string for SHA1 encryption 3) The encrypted string obtained by the developer can be compared with signature to indicate that the request comes from wechat

Ii. Steps to develop wechat official account background based on Django

1. Preparation

  • Create a New Django project named weixin
django-admin.py startproject weixinCopy the code

  • Create app go to the project directory, CD weixin and run the following command
python manage.py startapp weixinCopy the code

or

django-admin.py startapp weixinCopy the code

  • Modify settings.py to add the weixin application you just created
INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'weixin',
)Copy the code

  • Modify urls.py in the app of the same name of the project and add a new weixin route resolution redirect
urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^weixin/', include('weixin.urls',namespace="weixin")),
   ]Copy the code

2. Write urls.py for weixin application

Modify urls.py in app weixin to add resolution for view functions, default access to the weixin_index method pointing to view functions.

app_name = 'weixin'

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^$', views.index, name='weixin_index'),
    ]Copy the code

3. Write views.py for weinxin application

Get method for verification, POST method to transfer XML data, parsing and piecing XML data to achieve automatic reply function

from django.http.response import HttpResponse, HttpResponseBadRequest from django.views.decorators.csrf import csrf_exempt from wechat_sdk import WechatBasic from wechat_sdk.exceptions import ParseError from wechat_sdk.messages import TextMessage # Create your views here. Wechat_instance = WechatBasic(token=' your token', appId =' your public id', Appsecret =' public key ') @cSRF_exempt def index(request): if request.method == 'GET': Request (timestamp, timestamp, nonce) xml) signature = request.GET.get('signature') timestamp = request.GET.get('timestamp') nonce = request.GET.get('nonce') if not wechat_instance.check_signature( signature=signature, timestamp=timestamp, nonce=nonce): return HttpResponseBadRequest('Verify Failed') return HttpResponse( request.GET.get('echostr', ''), Content_type ="text/plain") print(request.body) wechat_instance.parse_data(data=request.body) except ParseError: Return HttpResponseBadRequest('Invalid XML Data') # wechat_instance.get_message() # Response = wechat_instance.response_text(content=(' Thanks for your attention! \n reply 【 function 】 two words to view the supported function, can also reply to any content start chat ')) if isinstance(message, TextMessage): # Current session content = message.content.strip() if content == 'function ': reply_text = (' currently supported function: n1. To search for tutorials, add "tutorial" to the keyword, as in "Django backend tutorials "\n "2. Reply to any word, check the weather, chat with others, tell stories, do anything! Response = wechat_instance.response_text(content=reply_text) print(response) return HttpResponse(response, content_type="application/xml")Copy the code

3. After configuring public domain name mapping, run the program to display the mapping effect

Python manage. Py runserver then executes 0.0.0.0:80Copy the code


If the public account cannot be used, the system prompts “The service provided by this public account is faulty. Please try again later.

So baidu in all kinds of information, but also view wechat public number development documents, all kinds of Baidu and Google, have not been solved. Wechat public platform was disabled and the key was reset. Check and fill in carefully, there is no problem. There are no errors.

I opened the development – operation center – interface alarm – alarm rules all set to “once /5 minutes”, occasionally received such an error: 302 web page redirection error.


Finally, I found wechat public platform – development – Basic configuration – Server configuration – server address (URL), where the http:// header is changed to https://.


Try auto reply again.



If it’s helpful, give it a pat on the back, give it a thumbs-up. Please take a look at my sign (Zhihu No. : Cloth Road), look at”Development operations”Column!