近日重虑,因公司業(yè)務(wù)需要,需將原兩個公眾號合并為一個全封,即要將其中一個公眾號(主要是粉絲)遷移到另一個公眾號。按微信規(guī)范桃犬,同一用戶在不同公眾號內(nèi)的 openid 是不同的售貌,我們的業(yè)務(wù)系統(tǒng)不例外地記錄了用戶的 openid,因此,涉及到兩個公眾號的 openid 的轉(zhuǎn)換疫萤。幸好颂跨,微信公眾號平臺在賬號遷移描述提供了方法和API供調(diào)用,詳見:http://kf.qq.com/faq/170221aUnmmU170221eUZJNf.html
這里使用 Python 寫個程序來完成扯饶,簡單快捷恒削,主要知識點(diǎn)有:
- MySQL connector 使用池颈,也就是 Python DB API 規(guī)范
- HTTP客戶端庫 requests 使用
- 微信公眾號平臺 API 使用
首先,建立新舊 openid 對照表钓丰。
CREATE TABLE change_openidlist(
id BIGINT NOT NULL AUTO_INCREMENT,
ori_openid varchar(100) NOT NULL,
new_openid varchar(100) NOT NULL,
CONSTRAINT crm_change_openidlist_pk PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci ;
如果沒有安裝躯砰,則需先安裝以下類庫。
pip install mysql-connector-python
pip install requests
接著携丁,運(yùn)行下面 python 程序琢歇,即可將新舊 openid 對照數(shù)據(jù)寫到 change_openidlist,然后就可以根據(jù)這個表的數(shù)據(jù)去更新其它數(shù)據(jù)表了梦鉴。
其它可見注釋李茫,不詳述,當(dāng)然不要忘了將 appid 和 secret 替換為自己公眾號肥橙。
# -*- coding: utf-8 -*-
import requests
import mysql.connector
def handle_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('select openid from wxmembers')
size = 100
while True:
list = qcursor.fetchmany(size)
if not list:
break
changeopenid_list = get_changeopenid_list(list,token)
wcursor.executemany('insert into change_openidlist (ori_openid,new_openid) values (%s, %s)',changeopenid_list)
except mysql.connector.Error as e:
print ('Error : {}'.format(e))
finally:
qcursor.close
wcursor.close()
conn.close
print 'openid handle finished!'
def get_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()
return response['access_token']
def get_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']] for result in result_list if result['err_msg'] == 'ok']
return openid_list
if __name__ == '__main__':
handle_data()