时间:2023-05-28 13:18:02 | 来源:网站运营
时间:2023-05-28 13:18:02 来源:网站运营
Python进行微信公众号开发:django-admin.py startproject weixin
python manage.py startapp weixin
或django-admin.py startapp weixin
INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'weixin',)
urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^weixin/', include('weixin.urls',namespace="weixin")), ]
app_name = 'weixin'urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^$', views.index, name='weixin_index'), ]
from django.http.response import HttpResponse, HttpResponseBadRequestfrom django.views.decorators.csrf import csrf_exemptfrom wechat_sdk import WechatBasicfrom wechat_sdk.exceptions import ParseErrorfrom wechat_sdk.messages import TextMessage# Create your views here.wechat_instance = WechatBasic( token='您设置的token', appid='您的公众号id', appsecret='您的公众号的秘钥')@csrf_exemptdef index(request): if request.method == 'GET': # 检验合法性 # 从 request 中提取基本信息 (signature, 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") # 解析本次请求的 XML 数据 else: try: print(request.body) wechat_instance.parse_data(data=request.body) except ParseError: return HttpResponseBadRequest('Invalid XML Data') # 获取解析好的微信请求信息 message = wechat_instance.get_message() # 关注事件以及不匹配时的默认回复 response = wechat_instance.response_text( content=( '感谢您的关注!/n回复【功能】两个字查看支持的功能,还可以回复任意内容开始聊天' )) if isinstance(message, TextMessage): # 当前会话内容 content = message.content.strip() if content == '功能': reply_text = ( '目前支持的功能:/n1. 关键词后面加上【教程】两个字可以搜索教程,' '比如回复 "Django 后台教程"/n' '2.回复任意词语,查天气,陪聊天,讲故事,无所不能!/n' '还有更多功能正在开发中哦 ^_^/n' ) response = wechat_instance.response_text(content=reply_text) print(response) return HttpResponse(response, content_type="application/xml")
python manage.py runserver 0.0.0.0:80
发现不能正常使用,提示“该公众号提供的服务出现故障,请稍后再试”。关键词:公众