微信公众号-微信接口

2022-09-14 17:59:37 浏览数 (1)

接入微信公众平台开发,开发者需要按照如下步骤完成:

  1. 填写服务器配置
  2. 验证服务器地址的有效性
  3. 依据接口文档实现业务逻辑

填写服务器配置

说明:现在选择提交肯定是验证token失败,因为还需要完成代码逻辑

注意:如果没有注册公众号,也可以利用测试平台完成上述过程(在开发过程中建议使用测试账号,待真实上线时使用自己真实的公众号即可)

测试平台:http://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login

验证服务器地址的有效性

开发者提交信息后,微信服务器将发送GET请求到填写的服务器地址URL上,GET请求携带四个参数

  • 原理 开发者通过检验signature对请求进行校验。若确认此次GET请求来自微信服务器,请原样返回echostr参数内容,则接入生效,成为开发者成功,否则接入失败
  • 流程
    1. 将token、timestamp、nonce三个参数进行字典序排序
    2. 将三个参数字符串拼接成一个字符串进行sha1加密
    3. 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信
  • 搭建Django服务

创建Django工程并添加应用

修改配置文件settings.py

代码语言:javascript复制
ALLOWED_HOSTS = [<span class="hljs-string">"*"</span>]


<span class="hljs-comment"># Application definition</span>

INSTALLED_APPS = [
    <span class="hljs-string">'django.contrib.admin'</span>,
    <span class="hljs-string">'django.contrib.auth'</span>,
    <span class="hljs-string">'django.contrib.contenttypes'</span>,
    <span class="hljs-string">'django.contrib.sessions'</span>,
    <span class="hljs-string">'django.contrib.messages'</span>,
    <span class="hljs-string">'django.contrib.staticfiles'</span>,
    <span class="hljs-string">'myApp'</span>,
]

添加主路由与子路由

project/urls.py

代码语言:javascript复制
<span class="hljs-keyword">from</span> django.contrib <span class="hljs-keyword">import</span> admin
<span class="hljs-keyword">from</span> django.urls <span class="hljs-keyword">import</span> path, re_path, include

urlpatterns = [
    path(<span class="hljs-string">'admin/'</span>, admin.site.urls),
    path(<span class="hljs-string">''</span>, include((<span class="hljs-string">"myApp.urls"</span>, <span class="hljs-string">"myApp"</span>), namespace=<span class="hljs-string">"myApp"</span>)),
]

myApp/urls.py

代码语言:javascript复制
<span class="hljs-keyword">from</span> django.urls <span class="hljs-keyword">import</span> path, re_path
<span class="hljs-keyword">from</span> myApp <span class="hljs-keyword">import</span> views

urlpatterns = [
    path(<span class="hljs-string">r'index/'</span>, views.index),
]

添加测试视图

myApp/views.py

代码语言:javascript复制
<span class="hljs-keyword">from</span> django.shortcuts <span class="hljs-keyword">import</span> render, HttpResponse

<span class="hljs-comment"># Create your views here.</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">index</span><span class="hljs-params">(request)</span>:</span>
    <span class="hljs-keyword">return</span> HttpResponse(<span class="hljs-string">"sunck is a good man"</span>)

测试基础服务

启动命令:python manage.py runserver 0.0.0.0:8080

浏览器地址栏输入:http://39.107.226.105:8080/index/

验证微信服务器请求

myApp/urls.py

代码语言:javascript复制
<span class="hljs-keyword">from</span> django.urls <span class="hljs-keyword">import</span> path, re_path
<span class="hljs-keyword">from</span> myApp <span class="hljs-keyword">import</span> views

urlpatterns = [
    path(<span class="hljs-string">r'index/'</span>, views.index),
    path(<span class="hljs-string">r'weixin/'</span>, views.weixin),
]

myApp/views.py

代码语言:javascript复制
<span class="hljs-keyword">from</span> django.shortcuts <span class="hljs-keyword">import</span> render, HttpResponse
<span class="hljs-keyword">from</span> django.views.decorators.csrf <span class="hljs-keyword">import</span> csrf_exempt
<span class="hljs-keyword">import</span> hashlib

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">index</span><span class="hljs-params">(request)</span>:</span>
    <span class="hljs-keyword">return</span> HttpResponse(<span class="hljs-string">"sunck is a good man"</span>)

<span class="hljs-meta">@csrf_exempt</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">weixin</span><span class="hljs-params">(request)</span>:</span>
    <span class="hljs-keyword">if</span> request.method == <span class="hljs-string">"GET"</span>:
        <span class="hljs-comment"># 接收微信服务器get请求发过来的参数</span>
        signature = request.GET.get(<span class="hljs-string">'signature'</span>, <span class="hljs-keyword">None</span>)
        timestamp = request.GET.get(<span class="hljs-string">'timestamp'</span>, <span class="hljs-keyword">None</span>)
        nonce = request.GET.get(<span class="hljs-string">'nonce'</span>, <span class="hljs-keyword">None</span>)
        echostr = request.GET.get(<span class="hljs-string">'echostr'</span>, <span class="hljs-keyword">None</span>)

        <span class="hljs-comment"># 服务器配置中的token</span>
        token = <span class="hljs-string">'sunck'</span>
        
        <span class="hljs-comment"># 把参数放到list中排序后合成一个字符串,再用sha1加密得到新的字符串与微信发来的signature对比,如果相同就返回echostr给服务器,校验通过</span>
        hashlist = [token, timestamp, nonce]
        hashlist.sort()
        hashstr = <span class="hljs-string">''</span>.join([s <span class="hljs-keyword">for</span> s <span class="hljs-keyword">in</span> hashlist])
        hashstr = hashlib.sha1(hashstr.encode(<span class="hljs-string">"utf-8"</span>)).hexdigest()
        <span class="hljs-keyword">if</span> hashstr == signature:
            <span class="hljs-keyword">return</span> HttpResponse(echostr)
        <span class="hljs-keyword">else</span>:
            <span class="hljs-keyword">return</span> HttpResponse(<span class="hljs-string">"field"</span>)

启动Django服务

启动服务:python manage.py runserver 0.0.0.0:8080

配置Nginx

因为微信服务器只请求80或者443端口,但是DJango服务无法使用这两个端口。所以需要配合Nginx作为反向代理分发请求给DJango服务

代码语言:javascript复制
     user nginx;
     worker_processes 1;
     error_log /var/log/nginx/error.log;
     pid /run/nginx.pid;
     include /usr/share/nginx/modules/*.conf;
     events {
       use epoll;
         worker_connections 1024;
   }
     http {
       log_format  main  '$remote_addr - $remote_user [$time_local] "$request"' 
                           '$status $body_bytes_sent "$http_referer" '
                         '"$http_user_agent" "$http_x_forwarded_for"';
         access_log  /var/log/nginx/access.log  main;
         sendfile            on;
         tcp_nopush          on;
         tcp_nodelay         on;
         keepalive_timeout   65;
         types_hash_max_size 2048;
         include             /etc/nginx/mime.types;
         default_type        application/octet-stream;
         include             /etc/nginx/conf.d/*.conf;
     
         server {
             listen       80 default_server;
             listen       [::]:80 default_server;
             server_name  _;
             charset      koi8-r;
             location / {
                 proxy_pass   http://39.107.226.105:8080;
             }
             location /static {
                 alias /var/www/ty/collectedstatic/;
             }
             error_page 404 /404.html;
                 location = /40x.html {
             }
             error_page 500 502 503 504 /50x.html;
                 location = /50x.html {
             }
         }
     }

重启Nginx服务:systemctl restart nginx.service

浏览器地址栏输入:http://39.107.226.105/index/

注意:此时无需输入8080端口,默认使用80端口请求Nginx服务,Nginx再将请求转发给DJango服务

  • 公众平台点击提交 自有公众号开发:

微信测试平台:

0 人点赞