使用 Python 实现微信公众号粉丝迁移流程
近日,因公司业务需要,需将原两个公众号合并为一个,即要将其中一个公众号(主要是粉丝)迁移到另一个公众号。按微信规范,同一用户在不同公众号内的openid是不同的,我们的业务系统不例外地记录了用户的openid,因此,涉及到两个公众号的openid的转换。幸好,微信公众号平台在账号迁移描述提供了方法和API供调用,详见:
http://kf.qq.com/faq/170221aUnmmU170221eUZJNf.html
这里使用Python写个程序来完成,简单快捷,主要知识点有:
- MySQLconnector使用,也就是PythonDBAPI规范
- HTTP客户端库requests使用
- 微信公众号平台API使用
首先,建立新旧openid对照表。
CREATETABLEchange_openidlist( idBIGINTNOTNULLAUTO_INCREMENT, ori_openidvarchar(100)NOTNULL, new_openidvarchar(100)NOTNULL, CONSTRAINTcrm_change_openidlist_pkPRIMARYKEY(id) )ENGINE=InnoDBDEFAULTCHARSET=utf8COLLATE=utf8_general_ci;
如果没有安装,则需先安装以下类库。
pipinstallmysql-connector-python pipinstallrequests
接着,运行下面python程序,即可将新旧openid对照数据写到change_openidlist,然后就可以根据这个表的数据去更新其它数据表了。
其它可见注释,不详述,当然不要忘了将appid和secret替换为自己公众号。
#-*-coding:utf-8-*- importrequests importmysql.connector defhandle_data(): try: token=get_access_token() #自动提交方式autocommit=True conn=mysql.connector.connect(host='127.0.0.1',port='3306',user='user',password='password',database='wx',use_unicode=True,autocommit=True); qcursor=conn.cursor(buffered=True) wcursor=conn.cursor() #旧公众号openid qcursor.execute('selectopenidfromwxmembers') size=100 whileTrue: list=qcursor.fetchmany(size) ifnotlist: break changeopenid_list=get_changeopenid_list(list,token) wcursor.executemany('insertintochange_openidlist(ori_openid,new_openid)values(%s,%s)',changeopenid_list) exceptmysql.connector.Errorase: print('Error:{}'.format(e)) finally: qcursor.close wcursor.close() conn.close print'openidhandlefinished!' defget_access_token(): new_appid='00000' new_secret='11111' url='https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential'#grant_type为固定值 payload={'appid':new_appid,'secret':new_secret} r=requests.get(url,params=payload) response=r.json() returnresponse['access_token'] defget_changeopenid_list(ori_openid_list,token): new_access_token=token ori_appid='33333' url='http://api.weixin.qq.com/cgi-bin/changeopenid?access_token='+new_access_token payload={'to_appid':ori_appid,'openid_list':ori_openid_list} r=requests.post(url,json=payload) response=r.json() result_list=response['result_list'] openid_list=[[result['ori_openid'],result['new_openid']]forresultinresult_listifresult['err_msg']=='ok'] returnopenid_list if__name__=='__main__': handle_data()
总结
以上所述是小编给大家介绍的使用Python实现微信公众号粉丝迁移流程,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!