Search code examples
pythonpython-requestswechat

Got 503 error code while retrieveing mediaid in wechat?


API http://admin.wechat.com/wiki/index.php?title=Transferring_Multimedia_Files

import requests
r='https://api.wechat.com/cgi-bin/token?grant_type=client_credential&appid=wx82c6ebdb6e33ad33&secret=c2861ec348b3c94087c4b64cbe166fbb' #credentials sharing no problem
a=(requests.get(r).json()['access_token'])
print(a)
params = (
    ('access_token', a),
    ('type', 'image'),
)

import os
files = {
    'media': ('1.jpg', open('static/1.jpg', 'rb'),'image/jpg',),
}
print()
response = requests.post('http://file.api.wechat.com/cgi-bin/media/upload', params=params, files=files)

def uprint(x,file=None):
  try:
    pass
    if x:
      print(x.encode('cp65001',errors='backslashreplace').decode('cp1252'),file=file)
  except Exception as e:
    return f'{x}\n{e}'
def prin(*a):print(ascii(*a))    
print(response.text,file=open('z.html','a',encoding="utf-8"))
print(response.headers)

Solution

  • Looks like you are using http for the upload call. I have seen this error returned from sites for this reason before.

    The HTTP error 503 means "Service Unavailable". It is usually returned by a server when it is unable to handle the request due to a temporary overloading or maintenance of the server.

    After checking the API documentation for wechat, I notided this:

    1. This API must be used via HTTPS.

    And then I noticed this in the Q&A:

    Q: Which server should I send API requests to?

    A: If you have an International Official Account, use api.wechat.com.

    If you have a China Official Account, use api.weixin.qq.com.

    So, in your case I think you need to use https, and the domain api.wechat.com, like this:

    response = requests.post('https://api.wechat.com/cgi-bin/media/upload', params=params, files=files)