python中如何实现微信分享功能

1. 微信公众平台申请测试号

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

2. 代码如下:

import requests
import hashlib
import time

from flask import Flask, request, jsonify, views, make_response
from flask_cors import CORS

import redis

app = Flask(__name__)
CORS(app, supports_credentials=True, resources=r"/*")

pool = redis.ConnectionPool(host="localhost", port=6379, db=0, decode_responses=True)
sr = redis.StrictRedis(connection_pool=pool)

APP_ID = 'wxa77a00333cd8d99a'
APP_SECRET = '6f616f770203c4cc930829f6fdfc2396'


class GetSignature(views.MethodView):
    @staticmethod
    def get_access_token():
        # 获取access_token
        access_token = sr.get("wx:access_token")
        if access_token:
            return access_token
        url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={}&secret={}".format(APP_ID,
                                                                                                               APP_SECRET)
        res = requests.get(url).json()  # dict类型
        """
        {
            "access_token": "44_kWjrbaVXVS0E5Ctuu89yXAqUJI9eJEH1qTX8g-HJfCHqOyCzwdU295GiU5yaCiFjvW6st0ytAgrbkeORc8Qxfs2zsL_StblS_Xgrmezj__g5ynw9DVmJK34zf18UKZkRGIkfh04Hw-OvAuLpVXMaAHAMOD",
            "expires_in": 7200
        }
        """
        access_token = res["access_token"]
        sr.setex("wx:access_token", 7200, access_token)
        return access_token

    @staticmethod
    def create_nonce_str():
        # 获取noncestr(随机字符串)
        import random
        chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
        str = ""
        for i in range(0, 16):
            s = random.randint(0, len(chars) - 1)
            str += chars[s:s + 1]
        return str

    def get_jsapi_ticket(self):
        # 获取jsapi_ticket
        jsapi_ticket = sr.get("wx:jsapi_ticket")
        if jsapi_ticket:
            return jsapi_ticket
        access_token = self.get_access_token()
        url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={access_token}&type=jsapi".format(
            access_token=access_token)
        jsapi_ticket = requests.get(url).json()["ticket"]
        sr.setex("wx:jsapi_ticket", 7200, jsapi_ticket)
        return jsapi_ticket

    def get(self):
        url = request.args.get("url", request.url)
        url = url.split('#')[0]
        timestamp = int(time.time())
        js_ticket = self.get_jsapi_ticket()
        nonce = self.create_nonce_str()
        ret = {
            "noncestr": nonce,
            "jsapi_ticket": js_ticket,
            "timestamp": timestamp,
            "url": url
        }
        temp = "&".join(['%s=%s' % (key.lower(), ret[key]) for key in sorted(ret)])
        # 2. 将三个参数字符串拼接成一个字符串进行sha1加密
        # sig是计算出来的签名结果
        sig = hashlib.sha1(temp.encode("utf8")).hexdigest()
        sign_package = {
            "appid": APP_ID,
            "noncestr": nonce,
            "timestamp": timestamp,
            "url": url,
            "signature": sig
        }
        # res = make_response(jsonify(sign_package))
        # res.headers['Access-Control-Allow-Origin'] = '*'
        # res.headers['Access-Control-Allow-Method'] = '*'
        # res.headers['Access-Control-Allow-Headers'] = '*'
        return jsonify(sign_package)


app.add_url_rule("/get_signature", view_func=GetSignature.as_view("get_signature"))

if __name__ == "__main__":
    app.run(debug=True, host="192.168.31.12", port="5000")

3. 浏览器访问:

http://127.0.0.1:5000/get_signature

4. 效果如图

python中如何实现微信分享功能_第1张图片

你可能感兴趣的:(Python)